How to replace a substring in a string object in Python

Let’s consider that you need to replace a substring with a new substring within a string object.

>>> s1 = 'Dan is 39 years old. 39 is a nice age although other people think that you are old when you are 39 yea
>>> s2 = s1.replace('39', '40')
>>> s2
'Dan is 40 years old. 40 is a nice age although other people think that you are old when you are 40 years old.'

We use here the replace() method of the string object to replace all the instances of the substring 39 with the substring 40.

We could also use the replace() method to replace only one instance of the substring 39.

>>> s3 = s1.replace('39', '40', 1)
>>> s3
'Dan is 40 years old. 39 is a nice age although other people think that you are old when you are 39 years old.'

Leave a Reply