The Wayback Machine - https://web.archive.org/web/20230323192519/https://www.geeksforgeeks.org/python-string-replace/
Skip to content
Related Articles
Open in App
Not now

Related Articles

Python String replace() Method

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 14 Mar, 2023
Improve Article
Save Article

String replace() in Python returns a copy of the string where occurrences of a substring are replaced with another substring. 

Syntax of String replace() method

The replace() method in Python strings has the following syntax:

Syntax: string.replace(old, new, count)

Parameters: 

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

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

Examples of Python replace() Methods

Replace all Instances of a single character using replace() in Python

In this example, we are only replacing a single character from a given string. The Python replace() method is case-sensitive, and therefore it performs a case-sensitive substring substitution, i.e. R in FOR is unchanged.

Python3




string = "grrks FOR grrks"
  
# replace all instances of 'r' (old) with 'e' (new)
new_string = string.replace("r", "e" )
  
print(string)
print(new_string)

Output : 

grrks FOR grrks
geeks FOR geeks

Replace all Instances of a String using replace() in Python

Here, we will replace all the geeks with GeeksforGeeks using replace() function.

Python3




string = "geeks for geeks \ngeeks for geeks"
  
print(string)
  
# Prints the string by replacing only
# 3 occurrence of Geeks
print(string.replace("geeks", "GeeksforGeeks"))

Output : 

geeks for geeks 
geeks for geeks
GeeksforGeeks for GeeksforGeeks 
GeeksforGeeks for GeeksforGeeks
 

Replace only a certain number of Instances using replace() in Python

In this example, we are replacing certain numbers of words. i.e. “ek” with “a” with count=3.

Python3




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

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!