How to use the Python string replace() method?

Share Your Love

The python string replace() method is a built-in function in python programming language. It returns a copy of the string where all occurrences of a substring is replaced with another substring.

Syntax of Python string replace():

string.replace(old, new, count)

String replace() method 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.

Return Value :

It returns a copy of the string where all occurrences of a substring is replaced with another substring.

Note:

  • If count is not specified then all the occurrences of the old substring are replaced with the new substring.
  • This method returns the copy of the string i.e. it does not changes the original string.

Below is the code illustration replace() :

Demonstration-1 String replace():

# Python3 program to demonstrate the
# use of replace() method

string = "techhub for techhub techhub techhub techhub"

# Prints the string by replacing all
# geeks by Geeks
print(string.replace("techhub", "Techhub"))

# Prints the string by replacing only
# 3 occurrence of Geeks
print(string.replace("techhub", "LingarajTechhub", 3))

Output :

Techhub for Techhub Techhub Techhub Techhub

Demonstration-2 String replace():

# Python3 program to demonstrate the
# use of replace() method

string = "Techhub for techhub techhub techhub techhub"

# Prints the string by replacing
# e by o
print(string.replace("e", "o"))

# Prints the string by replacing only
# 3 occurrence of ek by o
print(string.replace("ec", "o", 3))

Output:

Tochhub for tochhub tochhub tochhub tochhub
Tohhub for tohhub tohhub tohhub tohhub

Please comment and share this article or if you wants to improve this article please WhatsApp us.

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 429

Newsletter Updates

Enter your email address below to subscribe to our newsletter