python-regexHow to replace all using Python regex?
Regex (or Regular Expressions) is a powerful tool for string manipulation in Python. It can be used to replace all occurrences of a given pattern in a string with a different string.
Example code
import re
text = "This is a test string"
# Replace all occurrences of 'test' with 'example'
new_text = re.sub('test', 'example', text)
print(new_text)
Output example
This is a example string
Code explanation
import re: imports the Python regex modulere.sub('test', 'example', text): uses thesub()function from the regex module to replace all occurrences of 'test' with 'example' in the stringtextprint(new_text): prints the new string with all occurrences of 'test' replaced with 'example'
Helpful links
More of Python Regex
- How to match a YYYY-MM-DD date with Python Regex?
- How to match a question mark in Python regex?
- How to match a plus sign in Python regex?
- How to ignore case in Python regex?
- How to use word boundaries in Python Regex?
- How to match one or more occurence in Python regex?
- How to match a URL path using Python regex?
- How to match a URL using Python regex?
- How to match a year with Python Regex?
- How to match zero or one occurence in Python regex?
See more codes...