replace() method in Python String can be used to replace a given substring in an original string with another substring.
The replace() method by default, replaces all the occurrences of old substring with the new substring in the original string.
Syntax
mainstring.replace(old, new, count)
old: Substring that has to be replaced.
new: Substring that has to replace old substring.
count: Number of occurrences of a substring you want to replace.
Please note that, replace() method does not alter the original string rather it returns a copy of the string where all or specified occurrences of a substring are replaced with another substring.
s = "Python loves me. I love Python."
old = "Python"
new = "Node"
print(s.replace(old, new)) # replace all occurrence of substring
print(s.replace(old, new, 1)) # replace only first occurrence of substring
O/P
Node loves me. I love Node.
Node loves me. I love Python.
Let’s try to understand what happened in the above code :
s.replace(old, new) replaced all the occurrence of “Python” in the original string with “Node”.
s.replace(old, new, 1) replaced only the first occurrence of “Python” in the original string with “Node”.
That’s all here.
