Python string replace() Method

In this tutorial, We will see the python string replace() method with examples.

replace() Method

The replace() method is one of the methods in a python string. The python string replace() method is used to replace a substring in a string with another substring.

Syntax of Python string replace() method: Using 2 Parameter
string.replace(old,new)
  • This replace() method syntax will use 2 parameters. The first parameter would be the substring to be replaced and the second parameter would be the substring with which to replace.
  • If the substring to be replaced occurs many times, it will replace all substring with the new substring.
Syntax of Python string replace() method: Using 3 Parameter
string.replace(old,new,count)
  • In replace() method syntax, 3 parameter are used. The first 2 parameters are the same as the previous syntax.
  • Here count is the third parameter. The count parameter determines how many times to replace the old substring with the new substring if the substring to be replaced occurs many times.
replace() Method Parameters
ParametersDescription
oldSubstring to be replaced.
newWith which the old substring is replaced.
countThis parameter is optional. Determines how many times the old substring replaced by new substring.
Examples of the Python string replace() method
#Example 1
text = "python is a programming language" 

"""Here python is a substring, to replace python with a substring named java.""" 

b = text.replace("python","java") 

print(b)

#output: java is a programming language

For example, if the substring to be replaced occurs many times.

#Example 2
sentence = '''Raj is a software developer. Raj is also a good human being. Raj is a very talented man.'''

"""Here Raj word has come many times. We have to replace Raj with the word Ram."""

sent = sentence.replace("Raj","Ram")

print(sent)

#output: Ram is a software developer. Ram is also a good human being. Ram is a very talented man.
#Example 3
sentence = '''Raj is a software developer. Raj is also a good human being. Raj is a very talented man.''' 

"""Here Raj word has come many times. We have to change Raj word to Ram word with specific no. Off times.""" 

#Using count parameter

sent = sentence.replace("Raj","Ram",2)

#Raj word replaced by Ram with 2 times only.

print(sent)
 
#output: Ram is a software developer. Ram is also a good human being. Raj is a very talented man.
#Example 4
msg = "python3"

#Replace 3 by 4 using replace() method

msg1 = msg.replace("3","4")

print(msg1)

#output: python4

Related Posts