Search and Replace in Python

PythonServer Side ProgrammingProgramming

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

 Live Demo

#!/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
raja
Published on 30-Jan-2020 12:02:26
Advertisements