To replace all occurrences of a substring in a string in Python, you can use the replace
method.
In this example,
str
.replace
method on str
with the substring to be replaced and the replacement string as arguments.replace
method returns a new string with all occurrences of the substring replaced.str = 'Hello World Hello'
new_str = str.replace('Hello', 'Hi')
print(new_str)
Hi World Hi
In this example,
str
.replace
method on str
with the character to be replaced and the replacement character as arguments.replace
method returns a new string with all occurrences of the character replaced.str = 'Hello World Hello'
new_str = str.replace('o', 'X')
print(new_str)
HellX WXrld HellX
In this tutorial, we learned How to Replace All Occurrences of a Substring in a String in Python language with well detailed examples.