Computer >> Computer tutorials >  >> Programming >> Python

How to search and replace text in a file using Python?


There is the re.sub() method in Python module re which helps to search a pattern and replace with a new sub string. If the pattern is not found, string is returned unchanged.

Syntax of re.sub()

re.sub(pattern, repl, string):

For example in the code below, we search for ‘India’ and replace it with ‘the World’ in the string 'TP is most popular Tutorials site of India'

Example

result=re.sub(r'India','the World','TP is the most popular Tutorials site of India')
print result

Output

TP is the most popular Tutorials site of the World