Python String replace() Method

Example

Replace the word "bananas":

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

Run Instance

Definition and Usage

The replace() method replaces a specified phrase with another specified phrase.

Note:If no other content is specified, replace all occurrences of the specified phrase.

Syntax

string.replace(oldvalue, newvalue, count)

Parameter Value

Parameter Description
oldvalue Required. String to be retrieved.
newvalue Required. String to replace the old value.
count Optional. Number, specify the number of times the old value appears to be replaced. The default is all occurrences.

More Examples

Example

Replace all occurrences of the word "one":

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

Run Instance

Example

Replace the first two occurrences of the word "one":

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

Run Instance