

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Questions & Answers
- How to Search and Replace text in Python?
- How to find and replace within a text file using Python?
- 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 write text and output it as a text file using R?
- How to read a text file in Python?
- How to search and replace texts in a string in Golang?
- How to find and replace text in Oracle?
- How to write multiple lines in text file using Python?
- How to replace only text inside a div using jQuery?
- How to search in the file using PowerShell?
- How to work with a text file in Python?
- How to read an entire line from a text file using Python?
- How to read a number of characters from a text file using Python?
Advertisements