The Wayback Machine - https://web.archive.org/web/20220404115430/https://www.geeksforgeeks.org/python-string-replace/amp/

Python String | replace()

replace() is an inbuilt function in the Python programming language that returns a copy of the string where all occurrences of a substring are replaced with another substring. 
 

Syntax : 

string.replace(old, new, count)

Parameters : 
 

old – old substring you want to replace. 
new – new substring which would replace the old substring.
count – the number of times you want to replace the old substring with the new substring. (Optional
 



Return Value : 
It returns a copy of the string where all occurrences of a substring are replaced with another substring. 
 

Note: 

Below is the code demonstrating replace()
 

Example 1: 




# Python3 program to demonstrate the
# use of replace() method 
 
string = "geeks for geeks geeks geeks geeks"
  
# Prints the string by replacing all
# geeks by Geeks
print(string.replace("geeks", "Geeks"))
 
# Prints the string by replacing only
# 3 occurrence of Geeks 
print(string.replace("geeks", "GeeksforGeeks", 3))

Output : 
 

Geeks for Geeks Geeks Geeks Geeks
GeeksforGeeks for GeeksforGeeks GeeksforGeeks geeks geeks

Example 2:




# Python3 program to demonstrate the
# use of replace() method
 
string = "geeks for geeks geeks geeks geeks"
 
# Prints the string by replacing
# e by a
print(string.replace("e", "a"))
 
# Prints the string by replacing only
# 3 occurrence of ek by a
print(string.replace("ek", "a", 3))

Output: 
 

gaaks for gaaks gaaks gaaks gaaks
geas for geas geas geeks geeks

 


Article Tags :