EDUCBA

EDUCBA

MENUMENU
  • Explore
    • Lifetime Membership
    • All in One Bundles
    • 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.

ADVERTISEMENT
Popular Course in this category
PYTHON Course Bundle - 81 Courses in 1 | 59 Mock Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

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
ADVERTISEMENT
GOLANG Course Bundle - 6 Courses in 1
23+ Hours of HD Videos
6 Courses
Verifiable Certificate of Completion
Lifetime Access
4.5
ADVERTISEMENT
iOS DEVELOPER Course Bundle - 61 Courses in 1
147+ Hours of HD Videos
61 Courses
Verifiable Certificate of Completion
Lifetime Access
4.5
ADVERTISEMENT
JAVA SERVLET Course Bundle - 18 Courses in 1 | 6 Mock Tests
56+ Hours of HD Videos
18 Courses
6 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
ADVERTISEMENT
RED HAT LINUX Course Bundle - 5 Courses in 1
28+ Hours of HD Videos
5 Courses
Verifiable Certificate of Completion
Lifetime Access
4.5
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - 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

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

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

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

Forgot Password?

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

🚀 Extended Cyber Monday Price Drop! All in One Universal Bundle (3700+ Courses) @ 🎁 90% OFF - Ends in ENROLL NOW