Files
freeCodeCamp/guide/english/python/string-methods/string-replace-method/index.md
Gokul Manohar 7b022e2d72 Provided a better code. (#33478)
* Provided a better code.

Updated the code to give desired output.

* fix: corrected some verbiage
2019-06-28 00:00:46 -07:00

1.2 KiB

title
title
String Replace Method

String Replace Method

The str.replace(old, new, max) method is used to replace the substring old with the string new for a total of max times. This method returns a new copy of the string with the replacement. The original string str is unchanged.

Examples

  1. Replace all occurrences of "is" with "WAS"
string = "This is nice. This is good."
newString = string.replace("is","WAS")
print(newString)

Output:

ThWAS WAS nice. ThWAS WAS good.

As you can see above, the "is" in This is also replaced with Was.

To prevent this we can use

string = "This is nice. This is good."
newString = string.replace(" is "," WAS ")
print(newString)

Now the output becomes:

This WAS nice. This WAS good.

Here the "is" between whitespaces gets changed to "Was"

  1. Replace the first 2 occurrences of "is" with "WAS"
string = "This is nice. This is good."
newString = string.replace("is","WAS", 2)
print(newString)

Output:

ThWAS WAS nice. This is good.

More Information:

Read more about string replacement in the Python docs