Skip to content
Home » The replace Method

The replace Method

Spread the love

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:

1) joining strings

2) splitting strings

3) stripping strings

replace method
replace method

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'

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version of the article:


Spread the love

Leave a Reply