Python String replace() method
Python String replace() method
The string.replace() method in Python returns a copy of the string with all occurrences of substring old replaced by new.
Syntax
replace(old, new[, count])
Parameter
old: This parameter represents a substring you want to replace.
new: This parameter represents a substring which would replace the old substring.
count(optional): It signifies the number of times you want to replace the old substring with the new substring.
Return
This method returns a copy of the string where all occurrences of a substring is replaced with another substring.
Example 1
# Python program explaining
# the string.replace() method
# initializing the String
string ="Virat Kohli is my favourite cricketer."
print("Actual string:",string)
# replacing virat kohli with Ms Dhoni
val = string.replace("Virat Kohli", "Ms Dhoni")
print("After replacing the string: ")
# printing the replaced string
print(val)
Output
Actual string: Virat Kohli is my favourite cricketer. After replacing the string: Ms Dhoni is my favourite cricketer.
Example 2
# Python program explaining
# the string.replace() method
# initializing the String
string ="She sells seashells by the seashore"
print("Actual string:",string)
# replacing virat kohli with Ms Dhoni
val = string.replace("e", "i")
print("After replacing the string... ")
# printing the replaced string
print(val)
# replacing only the first two 'e' with 'i'
val = string.replace("e", "i",2)
print("After replacing only the first 2 'e' characters... ")
# printing the replaced string
print(val)
Output
Actual string: She sells seashells by the seashore After replacing the string... Shi sills siashills by thi siashori After replacing only the first 2 'e' characters... Shi sills seashells by the seashore
