python-regexHow to replace a certain group using Python regex?
Regex (regular expressions) can be used to replace a certain group of characters in a string using Python. To do this, the re.sub() function can be used. This function takes three arguments: the pattern to search for, the replacement string, and the string to search in.
Example code
import re
string = "Hello World!"
new_string = re.sub("World", "Universe", string)
print(new_string)
Output example
Hello Universe!
Code explanation
import re: imports theremodule which contains there.sub()functionstring = "Hello World!": assigns the string to be searched to thestringvariablenew_string = re.sub("World", "Universe", string): uses there.sub()function to search for the patternWorldin thestringvariable and replace it withUniverseprint(new_string): prints the new string with the replaced pattern
Helpful links
More of Python Regex
- How to match a YYYY-MM-DD date with Python Regex?
- How to get a group from a regex in Python?
- How to use word boundaries in Python Regex?
- How to match whitespace in Python regex?
- How to replace in a file using Python regex?
- How to match an IP address with regex in Python?
- How to get all matches from a regex in Python?
- How to use named groups with regex in Python?
- Python regex example
- How to match a UUID using Python regex?
See more codes...