To replace all occurrences of a substring in a string using regular expression in Python, you can use the re.sub
function.
In this example,
str
.re
module.re.sub
function to replace all occurrences of "Hello" with "Hi".import re
str = 'Hello World Hello'
new_str = re.sub('Hello', 'Hi', str)
print(new_str)
Hi World Hi
In this example,
str
.re
module.re.sub
function to replace all occurrences of digits (\d) with 'Y'.import re
str = 'Hello123World789'
new_str = re.sub('\\d', 'Y', str)
print(new_str)
HelloYYYWorldYYY
In this tutorial, we learned How to Replace a Substring in a String using Regular Expression in Python language with well detailed examples.