Python string replace() method is used to replace all occurrences of a specified substring with another substring.
Syntax
string.replace(oldvalue, newvalue, count)
Parameters
- oldvalue(required): It is the value we must search for.
- newvalue(required): It is the value we need to replace.
- count(optional): It specifies how many occurrences of the old value you want to replace.
Return Value
This method returns the copy of the string where the old substring is replaced with the new substring — one thing to remember is that the original string is unchanged.
Visual RepresentationExample 1: How to Use String replace() Method
line = 'Every DC Movies are great movies'
replacedString = line.replace('DC', 'Marvel')
print(replacedString)
Output
Every Marvel Movies are great movies
Example 2: Passing the “count” argument
line = 'Every DC Movies are great Movies!! Really great Movies'
replacedString = line.replace('Movies', 'Cartoons', 2)
print(replacedString)
Output
Every DC Cartoons are great Cartoons!! Really great Movies
Example 3: Replace multiple characters in a string
main_str = "Millie Bobby Brown"
# printing original string
print("The original string is : " + str(main_str))
# Using nested replace()
# Replace multiple characters at once
res = main_str.replace('M', "L").replace('B', 'G')
# printing result
print("The string after replacement of positions : " + res)
Output
The original string is : Millie Bobby Brown
The string after replacement of positions: Lillie Gobby Grown