Python String | replace()

replace() is an inbuilt function in Python programming language that returns a copy of the string where all occurrences of a substring is 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 is replaced with another substring.

Below is the code demonstrating replace() :

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output :

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


My Personal Notes arrow_drop_up

Striver(underscore)79 at Codechef and codeforces D

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.