Python String | replace ()

Python Methods and Functions | String Variables

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 )

Returned value:
It returns a copy of the string in which all occurrences of the substring have been replaced with another substring.

Below is the code that demonstrates replace () :

# Python3 program for demonstration
# using the replace () method


string = "geeks for geeks geeks geeks geeks"  

# Prints a line replacing geeks with Geeks

print (string.replace ( "geeks" , "Geeks" )) 

# Prints string, replacing only 3 occurrences of Geeks

print (string.replace ( "geeks" , "GeeksforGeeks" , 3 ))


 Geeks for Geeks Geeks Geeks Geeks Python.Engineering for Python.Engineering Python.Engineering geeks geeks