EDUCBA Logo

EDUCBA

MENUMENU
  • Explore
    • EDUCBA Pro
    • PRO Bundles
    • Featured Skills
    • New & Trending
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Log in
  • Sign Up
Home Software Development Software Development Tutorials Python String Tutorial Python String Replace
 

Python String Replace

Priya Pedamkar
Article byPriya Pedamkar

Updated March 31, 2023

Python String Replace

 

 

Introduction to Python String Replace

Sometimes we encounter certain problems that require minimal but efficient solutions. Say if you want to replace certain text occurrences in a phrase with some other piece of text. In the case of Python, replace() function can work out like a charm for you. replace() is an inbuilt function in Python that returns a copy of the string with all of the occurrences of the “string” that we want to replace by the specified one.

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

Syntax:

str.replace(old_string, new_string, count)

replace() function can be passed multiple arguments, which are mentioned down below:

  • old_string: It refers to the substring that we want to replace
  • new_string: It refers to the substring with which we want to replace the old_string with
  • count: It refers to the number of occurrences of the old_string that we want to replace with the new_string
Note: Here, the count is an optional argument. If you do not pass the third argument, that is count with the replace() function. Then, in that case, all of the occurrences of the old_string will be replaced by the new_string within str

In that case, the syntax will be:

str.replace(old_string, new_string)

Examples and Functions of Python String Replace

Let’s take an example to understand how does this work:

Example #1

Code:

# Python3 program to demonstrate the
# usage of replace() function
str = "Let's go to a place, from where we can go to another. But where exactly do we want to go"
# Prints the string by replacing go by GO
print(str.replace("go", "#GO"))
# Prints the string by replacing only 2 occurrence of go
print(str.replace("go", "#GO", 2))

Output:

Python String Replace-1.1

Note: In record one, As we have not passed on the optional argument count, which specified how many occurrences of the substring “go” should be replaced with “#GO”, then all of the occurrences will be replaced. And in the record second, Here only the first two occurrences of”go” are being replaced with “#GO”, as we have explicitly specified the count as 2 in the second print statement.

This is how the string replace() function works in python

Example #2

Code:

## Removing junk charachters from DF using string replace function
DF = [['Last name, first name 1'],['Last name, first name 2'],['Last name, first name 3'],['Last name,first name 4'],['Last name, first name 5'],['Last name, first name 6']]
for i in DF:
 for j in i:
  print (j.replace(',' , ''))

Output:

Python String Replace-1.2

If we are looking forward to cleaning the data having known junk character, then, in that case, replace function can be utilized as above. Here we have replaced the comma present between last and first name in a list of names with a blank.

  • If we are looking forward to cleaning the data having known junk character, then, in that case, replace function can be utilized as above.
  • Here we have replaced the comma present between last and first name in a list of names with a blank.
  • A for loop is utilized to iterate through each value present in the list, and then a replace function is used over that particular string to replace ‘,’ with a ”.
  • We do not need to explicitly specify the optional variable “count” over here as there is only a single occurrence of ‘,’ in a name.

Example #3

What will happen if the old_substring is not found in the string wherein we have applied the replace() function?. Any Clue?

Code:

## Removing junk charachters from DF using string replace function
DF = [['Last name first name 1'],['Last name first name 2'],['Last name, first name 3'],['Last name,first name 4'],['Last name, first name 5'],['Last name, first name 6']]
for i in DF:
 for j in i:
  print (j.replace(',' , ''))

Output:

Example-1.3

  • In this case, the first two strings do not even have a ‘,’ that we are looking forward to replace using the replace function().
  • So as we can see, the replace function is still returning the original string, even if the substring to be replaced is not found.
  • If we are applying the replace() function over multiple strings using a loop, then, in that case, we can experience this situation.

However, if we try to clean up the dataset for multiple types of junk characters, we may require another loop to iterate through the list of junk characters.

Example #4

Alternatively, we can not pass a list to the replacement function. It will throw an error in that case. Let’s try the same.

unkch = [['/'],['$'],['&']]
str = 'abcdef $ gh@#'
str.replace(junkch,'')

Output:

Example-1.4

Recommended Articles

We hope that this EDUCBA information on “Python String Replace” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

  1. Python Trim String
  2. Python Round Function
  3. Python Threadpool
  4. Python PEP8

Primary Sidebar

Footer

Follow us!
  • EDUCBA FacebookEDUCBA TwitterEDUCBA LinkedINEDUCBA Instagram
  • EDUCBA YoutubeEDUCBA CourseraEDUCBA Udemy
APPS
EDUCBA Android AppEDUCBA iOS App
Blog
  • Blog
  • Free Tutorials
  • About us
  • Contact us
  • Log in
Courses
  • Enterprise Solutions
  • Free Courses
  • Explore Programs
  • All Courses
  • All in One Bundles
  • Sign up
Email
  • [email protected]

ISO 10004:2018 & ISO 9001:2015 Certified

© 2025 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA Login

Forgot Password?

🚀 Limited Time Offer! - 🎁 ENROLL NOW