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 stringtext
print(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 the beginning of a line with Python regex?
- How to match a year with Python Regex?
- How to use word boundaries in Python Regex?
- How to match a URL path using Python regex?
- How to ignore case in Python regex?
- How to get a group from a regex in Python?
- How to match whitespace in Python regex?
- How to match a UUID using Python regex?
See more codes...