Today we’ll be talking about the replace method. It’s another string method that you can use to work on strings. I already covered some other string methods in my previous articles. If you want to read about some of them, here they are:
And now let’s have a look at the method.
We can replace substrings with other substrings by using the method replace(old, new, [max]). The method returns a string in which all the occurrences of old are replaced by new. The max parameter is optional. It tells the method how many occurrences should be replaced:
>>> text = "She is waiting, but she is impatient."
>>> text.replace("is", "was")
'She was waiting, but she was impatient.'
>>> text = "COMINGSTOPHOMESTOPANDSTOPYOUSTOPCANNOTSTOPSTOPME"
>>> text.replace("STOP", " ", 5)
'COMING HOME AND YOU CANNOT STOPME'
Here’s the video version of the article: