- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Search and Replace in Python
One of the most important re methods that use regular expressions is sub.
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.
#!/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
When the above code is executed, it produces the following result −
Phone Num : 2004-959-559 Phone Num : 2004959559
- How to Search and Replace text in Python?
- How to search and replace text in a file using Python?
- 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
- Map function and Lambda expression in Python to replace characters
- Replace duplicates in tuple in Python
- Difference between Organic Search and Paid Search
- Difference Between Linear Search and Binary Search
- Binary Search Tree - Search and Insertion Operations in C++
- How to replace \ with in Python?
- Python - Replace duplicate Occurrence in String