Home >>Python String Methods >Python String replace() Method

Python String replace() Method

Python String replace() Method

Python string replace() method is used to replace a given particular phrase with another specified phrase.

Syntax:
string.replace(oldvalue, newvalue, count)

Parameter Values

Parameter Description
oldvalue This is a required parameter. It defines the string to search for.
newvalue This is a required parameter. It defines the string to replace the old value with.
count This is an optional parameter. It defines a number specifying how many occurrences of the old value you want to replace.
Here is an example of Python replace() method:

txt = "I like bananas."
x = txt.replace("bananas", "mango")
print(x)

Output:
I like mango.
Example 2:

txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three", 2)
print(x)

Output:
three three was a race horse, two two was one too.