
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Search and Replace in Python
One of the most important re methods that use regular expressions is sub.
Syntax
re.sub(pattern, repl, string, max=0)
This method replaces all occurrences of the RE pattern in string with repl, substituting all occurrences unless max provided. This method returns modified string.
Example
#!/usr/bin/python import re phone = "2004-959-559 # This is Phone Number" # Delete Python-style comments num = re.sub(r'#.*$', "", phone) print "Phone Num : ", num # Remove anything other than digits num = re.sub(r'\D', "", phone) print "Phone Num : ", num
Output
When the above code is executed, it produces the following result −
Phone Num : 2004-959-559 Phone Num : 2004959559
- Related Articles
- How to Search and Replace text in Python?
- How to search and replace text in a file using Python?
- Recursive Search and Replace in Text Files in Linux
- Search and Replace with Java regular expressions
- How to search and replace texts in a string in Golang?
- MySQL search and replace record from a list of records
- Find and Replace Pattern in Python
- How do I search and replace specific chars at the beginning of a string in MySQL?
- Word Search in Python
- Replace duplicates in tuple in Python
- Map function and Lambda expression in Python to replace characters
- How to replace \ with in Python?
- Python - Replace duplicate Occurrence in String
- Linear Search in Python Program
- The search Function in Python

Advertisements