Python String replace() Method
Example
Replace the word "bananas":
txt = "I like bananas" x = txt.replace("bananas", "apples") print(x)
Definition and Usage
The replace() method replaces a specified phrase with another specified phrase.
Note:If no other content is specified, it will replace all occurrences of the specified phrase.
Syntax
string.replace(oldvalue, newvalue, count)
Parameter Value
Parameter | Description |
---|---|
oldvalue | Required. The string to be searched for. |
newvalue | Required. The string to be replaced with the old value. |
count | Optional. Number, specifies 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)
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)