The replace() Function in Python

Last updated by Abhinav Rawat on Sep 25, 2024 at 11:02 PM
| Reading Time: 3 minutes

Python supports object-oriented programming and has a concise, readable, and easy-to-learn syntax. It is no wonder that it is one of the most popular programming languages. An integral part of Python are its built-in functions.

We’ve written a series of articles to help you learn and brush up on the most useful Python functions. In this article, we’ll learn about Python’s replace() function and how to use it.

If you are preparing for a tech interview, check out our technical interview checklist, interview questions page, and salary negotiation e-book to get interview-ready! Also, read Python String join() Method, Python Exit commands, and Type and Isinstance In Python for more content on Python coding interview preparation.

Having trained over 10,000 software engineers, we know what it takes to crack the toughest tech interviews. Our alums consistently land offers from FAANG+ companies. The highest ever offer received by an IK alum is a whopping $1.267 Million!

At IK, you get the unique opportunity to learn from expert instructors who are hiring managers and tech leads at Google, Facebook, Apple, and other top Silicon Valley tech companies.

Want to nail your next tech interview? Sign up for our FREE Webinar.

In this article, we’ll cover:

  • What Is the replace() Function in Python and What Does It Do?
  • The replace() Function in Python: Syntax
  • The replace() Function in Python: Example
  • FAQs on the replace() Function in Python

What Is the replace() Function in Python and What Does It Do?

The built-in function replace() in Python replaces all or some specified number of occurrences of a substring in the original string with a different substring. It returns a copy of the original string with instances of the old substring replaced with the new desired substring as required.

The replace() Function in Python: Syntax


string.replace(originalSubstring, newSubstring, timesReplaced)

Parameters: 

  • originalSubstring: The original substring we want to replace.
  • newSubstring: The new substring that should replace the original substring.
  • timesReplaced (optional): The number of times we want the original substring to be replaced by the new one. By default, it replaces all instances of the original substring with the desired substring in the copy of the string.

Return Value: 

Python’s replace() function returns a copy of the original string with some or all occurrences of a substring replaced with another desired substring.

Note that replace() does not change the original string.

The replace() Function in Python: Example

Here, we take a look at how to use the function replace() in Python when needed:

Code


# Using the replace() function in Python 3

stringExample = "She sells seashells on the seashore."
  
# Replaces all occurrences of sh with replaced
print(stringExample.replace("sh", "*replaced*"))

# Replaces all occurrences of se with replaced
print(stringExample.replace("se", "*replaced*"))

# Replaces all occurrences of s with replaced
print(stringExample.replace("s", "*replaced*"))
 
# Replaces 2 occurrences of s with replaced
print(stringExample.replace("s", "*replaced*", 2))
 
# Replaces all occurrences of ells with empty string, effectively removing ells from the string
print(stringExample.replace("ells", ""))

# Replaces all occurrences of ss with empty rr. Note the search begins after the previous match has been replaced at the next index
stringExample2 = "sssss"
print(stringExample2.replace("ss", "rr"))

# Note that after index 0, the next replacement check is at index 2, which passes, and the last replacement check is at index 4, which fails.

# Note that if after index 0 the next replacement check had happened at index 1, and so on, all instances of s would have been replaced.

Output


She sells sea*replaced*ells on the sea*replaced*ore.
She *replaced*lls *replaced*ashells on the *replaced*ashore.
She *replaced*ell*replaced* *replaced*ea*replaced*hell*replaced* on the *replaced*ea*replaced*hore.
She *replaced*ell*replaced* seashells on the seashore.
She s seash on the seashore.
rrrrs

Found this article helpful? You can learn about more Python functions on the learn page.

FAQs on the replace() Function in Python

Q1. What does replace() do in Python?

Python’s replace() function returns a copy of the original string with instances of the old substring replaced with the new desired substring as required.

Q2. What is the default value in the replace() function for the number of replacements argument?

All instances of the old substring are replaced with the desired substring by default in Python’s replace() function.

Q3. How do you replace two characters in a string in Python?

We can use functions like replace(), sub(), subn(), translate(), and maketrans() in Python to replace multiple characters in a string.

Q4. What arguments does replace() require?

replace() takes the old substring we want to replace and the new substring to replace all instances of the old substring with as mandatory arguments.

Q5. How can we replace a string in a list in Python?

We can replace a string in a list in Python by using the replace() function along with a for loop.

Ready to Nail Your Next Coding Interview?

Whether you’re a coding engineer gunning for a software developer or software engineer role, a tech lead, or you’re targeting management positions at top companies, IK offers courses specifically designed for your needs to help you with your technical interview preparation!

If you’re looking for guidance and help with getting started, sign up for our FREE webinar. As pioneers in the field of technical interview preparation, we have trained thousands of software engineers to crack the most challenging coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!

Sign up now!

Last updated on: September 25, 2024
Register for our webinar

Uplevel your career with AI/ML/GenAI

Loading_icon
Loading...
1 Enter details
2 Select webinar slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Strange Tier-1 Neural “Power Patterns” Used By 20,013 FAANG Engineers To Ace Big Tech Interviews

100% Free — No credit card needed.

Register for our webinar

Uplevel your career with AI/ML/GenAI

Loading_icon
Loading...
1 Enter details
2 Select webinar slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

IK courses Recommended

Land high-paying DE jobs by enrolling in the most comprehensive DE Interview Prep Course taught by FAANG+ engineers.

Fast filling course!

Ace the toughest backend interviews with this focused & structured Backend Interview Prep course taught by FAANG+ engineers.

Elevate your engineering career with this interview prep program designed for software engineers with less than 3 years of experience.

Ready to Enroll?

Get your enrollment process started by registering for a Pre-enrollment Webinar with one of our Founders.

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC

Register for our webinar

How to Nail your next Technical Interview

Loading_icon
Loading...
1 Enter details
2 Select slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Almost there...
Share your details for a personalised FAANG career consultation!
Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!

Registration completed!

🗓️ Friday, 18th April, 6 PM

Your Webinar slot

Mornings, 8-10 AM

Our Program Advisor will call you at this time

Register for our webinar

Transform Your Tech Career with AI Excellence

Transform Your Tech Career with AI Excellence

Join 25,000+ tech professionals who’ve accelerated their careers with cutting-edge AI skills

25,000+ Professionals Trained

₹23 LPA Average Hike 60% Average Hike

600+ MAANG+ Instructors

Webinar Slot Blocked

Register for our webinar

Transform your tech career

Transform your tech career

Learn about hiring processes, interview strategies. Find the best course for you.

Loading_icon
Loading...
*Invalid Phone Number

Used to send reminder for webinar

By sharing your contact details, you agree to our privacy policy.
Choose a slot

Time Zone: Asia/Kolkata

Choose a slot

Time Zone: Asia/Kolkata

Build AI/ML Skills & Interview Readiness to Become a Top 1% Tech Pro

Hands-on AI/ML learning + interview prep to help you win

Switch to ML: Become an ML-powered Tech Pro

Explore your personalized path to AI/ML/Gen AI success

Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!
Registration completed!
🗓️ Friday, 18th April, 6 PM
Your Webinar slot
Mornings, 8-10 AM
Our Program Advisor will call you at this time

Get tech interview-ready to navigate a tough job market

Best suitable for: Software Professionals with 5+ years of exprerience
Register for our FREE Webinar

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC

Your PDF Is One Step Away!

The 11 Neural “Power Patterns” For Solving Any FAANG Interview Problem 12.5X Faster Than 99.8% OF Applicants

The 2 “Magic Questions” That Reveal Whether You’re Good Enough To Receive A Lucrative Big Tech Offer

The “Instant Income Multiplier” That 2-3X’s Your Current Tech Salary