What is the function of re.sub in Python?
The re.sub function in Python is a function in the re module that is used to replace matching items in a string.
Specifically, the re.sub function takes three parameters: pattern, replacement string, and target string. The function searches for parts in the target string that match the pattern, and then replaces the matching parts with the replacement string.
The function re.sub is used to replace all matching patterns in the target string with a specified replacement string and returns the resulting string. If there are no matches, the original string is returned.
For example, if we have a target string “hello, world!”, and we want to replace “world” with “Python”, we can use the re.sub function for replacement.
import re
string = "hello, world!"
pattern = "world"
replacement = "Python"
new_string = re.sub(pattern, replacement, string)
print(new_string)
The output is “hello, Python!”