- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Articles
- How to Search and Replace text in Python?
- How to find and replace within a text file using Python?\n\n\n
- How to find and replace the word in a text file using PowerShell?
- Search and Replace in Python
- How to write a single line in text file using Python?
- How to replace string in a large one line, text file in Linux?
- How to write multiple lines in text file using Python?
- How to Find the Shortest Words in a Text File using Python?
- How to Find the Longest Words in a Text File using Python?
- How to read a text file in Python?
- How to Copy Odd Lines of Text File to Another File using Python
- How to write text and output it as a text file using R?
- How to search in the file using PowerShell?
- How to Find the Most Repeated Word in a Text File using Python?
- How to read an entire line from a text file using Python?

Advertisements