How to Replace Using Regex in Python: Simple Guide
In Python, you can replace text using regular expressions with the
re.sub() function. It takes a pattern, a replacement string, and the original text, then returns the modified text with matches replaced.Syntax
The basic syntax of re.sub() is:
pattern: The regex pattern to find in the text.replacement: The string to replace each match with.string: The original text where replacements happen.- Optional
count: Number of replacements to make (default is 0, meaning replace all).
python
import re result = re.sub(pattern, replacement, string, count=0)
Example
This example replaces all digits in a string with the '#' character using regex:
python
import re text = "My phone number is 123-456-7890." new_text = re.sub(r"\d", "#", text) print(new_text)
Output
My phone number is ###-###-####.
Common Pitfalls
Common mistakes include:
- Not using raw strings (prefix
r) for regex patterns, which can cause errors with backslashes. - Forgetting that
re.sub()returns a new string and does not change the original. - Using incorrect regex patterns that don't match what you expect.
python
import re # Wrong: pattern without raw string text = "abc123" # This will cause an error or unexpected behavior # new_text = re.sub("\d", "#", text) # Incorrect # Right: use raw string for pattern new_text = re.sub(r"\d", "#", text) # Correct print(new_text)
Output
abc###
Quick Reference
Tips for using re.sub():
- Always use raw strings for regex patterns:
r"pattern". - Remember
re.sub()returns a new string; assign it to a variable. - Use
countto limit replacements if needed. - Use parentheses in patterns to capture groups and refer to them in replacements.
Key Takeaways
Use re.sub() with a regex pattern, replacement string, and target text to replace text in Python.
Always write regex patterns as raw strings (prefix with r) to avoid errors with backslashes.
re.sub() returns a new string; it does not modify the original text in place.
Use the optional count argument to limit how many replacements happen.
Test your regex patterns to ensure they match what you want to replace.