How is the re.sub function used in Python?
The re.sub function is used to replace matching text in a string. Its basic syntax is as follows:
Replace the pattern with the replacement in the given string.
Pattern is the regular expression pattern to match, repl is the string to replace, string is the string to be processed, count is the maximum number of replacements to be made (default is 0, meaning all matches will be replaced), and flags indicate the matching pattern.
Here is an example:
import re
string = "Today is a sunny day."
result = re.sub(r"sunny", "cloudy", string)
print(result)
The output result is “Today is a cloudy day.”
In the example above, we used the re.sub function to replace “sunny” with “cloudy” in the string.
The re.sub function also supports using a replacement function as the repl parameter, allowing you to customize the replacement logic using a function. For example:
import re
def double(match):
return match.group(0) * 2
string = "Hello, World!"
result = re.sub(r"\w", double, string)
print(result)
The output result is: “HHeelllloo, WWoorrlldd!!”
In the example above, we defined a replacement function called ‘double’ which takes a match object as its parameter and returns the replaced string. We then passed this replacement function as the ‘repl’ parameter in the re.sub function, achieving the effect of repeating each letter in the string.