Google News
logo
Python Program to Using the sub() function
In the following example of Python program that uses the `sub()` function from the `re` module to replace occurrences of a pattern in a string with a specified replacement :
Program :
import re

string = "The quick brown fox jumps over the lazy dog."

# Replace all occurrences of "the" (case-insensitive) with "a"
new_string = re.sub(r"\bthe\b", "a", string, flags=re.IGNORECASE)

print(new_string)
In this program, we first import the `re` module to use its regular expression functions. We then define a string `string` that contains the phrase "The quick brown fox jumps over the lazy dog.".

We use the `sub()` function from the `re` module to replace all occurrences of the word "the" (case-insensitive) with the word "a". The first argument to `sub()` is the regular expression pattern to match, which in this case is the word "the" surrounded by word boundaries (`\b`).

The second argument is the replacement string, which is simply the string "a". The third argument is the original string to search and replace in. Finally, we use the `flags` argument to specify that the regular expression should be case-insensitive.

The resulting string is stored in the `new_string` variable, which we print to the console. The output should be :
Output :
a quick brown fox jumps over a lazy dog.