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 there
module which contains there.sub()
functionstring = "Hello World!"
: assigns the string to be searched to thestring
variablenew_string = re.sub("World", "Universe", string)
: uses there.sub()
function to search for the patternWorld
in thestring
variable and replace it withUniverse
print(new_string)
: prints the new string with the replaced pattern
Helpful links
More of Python Regex
- How to match a year with Python Regex?
- How to split using Python regex?
- How to quote in Python regex?
- How to ignore case in Python regex?
- How to perform a zero length match with Python Regex?
- How to match a URL path using Python regex?
- How to remove numbers from a string using Python regex?
- How to replace all using Python regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to use word boundaries in Python Regex?
See more codes...