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 whitespace in Python regex?
- How to regex match excluding a word in Python?
- How to match a question mark in Python regex?
- How to match a UUID using Python regex?
- How to match a URL using Python regex?
- How to remove special characters using Python regex?
- How to quote in Python regex?
- How to match a URL path using Python regex?
- How to replace a certain group using Python regex?
See more codes...