i2tutorials

replace() method in Python String Module

replace() method in Python String Module


replace methodin string module is a static method which creates a connection with the characters and maps itself to its translation or replacement.


Syntax:

str.replace()


Parameters:

There are 3 parameters in the replace method.

  1. Old: this is the substring which needs to replaced
  2. New: this substring which replaces the old substring
  3. Count: this is an optional parameter. This is used replace the old substring with the new one as many times we want


Example-1:

Replace method using old and new parameters.

text = "I love Harry Potter"
x = text.replace("Harry Potter", "Barbie")
print(x)


Output:


Example-2:

replace method using old, new and count parameters.

text = "I like Barbie. Barbie goes to Hogwards. Barbie has magic wand. 
x = text.replace("Barbie", "Harry Potter",3)
print(x)


Output:


Example-3:

text = "I like Barbie. Barbie goes to Hogwards. Barbie has magic wand."
x = text.replace("Barbie", "Harry Potter",2)
print(x)


Output:

Exit mobile version