Tutorial Study Image

Python replace()

The replace() function in python helps to return a copy of the original string after replacing the 'old' substring with the 'new' substring. The function also allows specifying the number of times the old string needs to replace.


str.replace(old, new [, count])  #where old & new are strings
 

replace() Parameters:

The replace() function takes three parameters. If the count parameter is not given, the replace() method will replace all the old substring with the new substring. The replace() method can also use with numbers and symbols.

Parameter Description Required / Optional
old old substring you want to replace Required
new new substring which will replace the old substring Optional
count the number of times you want to replace the old substring with the new substring Optional

replace() Return Value

The return value is always a new string after the replacement. This method performs a case-sensitive search. If the specified old string is not found it will return the original string.

Input Return Value
string string (old replaced with new)

Examples of replacing () method in Python

Example 1: How to use replace() in Python?


string = 'Hii,Hii how are you'

# replacing 'Hii' with 'friends'
print(string.replace('Hii', 'friends'))

string = 'Hii, Hii how are you, Hii how are you, Hii'

# replacing only two occurences of 'Hii'
print(string.replace('Hii', "friends", 2))
 

Output:


friends,friends how are you
Hii, friends how are you, friends how are you, Hii

Example 2: Working of replace() in Python


string = 'Hii,Hii how are you'

# returns copy of the original string because of count zero
print(string.replace('Hii', 'friends',0))

string = 'Hii, Hii how are you, Hii how are you, Hii'

# returns copy of the original string because old string not found
print(string.replace('fine', "friends", 2))
 

Output:


Hii,Hii how are you
Hii, Hii how are you, Hii how are you, Hii