.replace()
In Python, the .replace()
method replaces all occurrences of a specified substring with another substring in a string. It is commonly used for text processing, data cleaning, and formatting tasks.
Syntax
string.replace(old, new, count)
Parameters:
old
: The substring to be replaced.new
: The substring to replace with.count
(optional): Specifies the number of occurrences of the given substring to be replaced. If not specified, all occurrences of the given substring is replaced.
Return value:
The .replace()
method returns another string with the given substring replaced.
Example 1: Basic Usage of .replace()
This example uses the .replace()
method to replace “world” with “Codecademy” in the welcome
string:
welcome = "Hello, world!"welcome = welcome.replace("world", "Codecademy")print(welcome)
Here is the output:
Hello, Codecademy!
Example 2: Using .replace()
with count
This example uses the .replace()
method with the count
parameter to replace only the first occurrence (count = 1
) of “like” with “love” in the var
string:
var = "I like cats and cats like me."var = var.replace("like", "love", 1)print(var)
Here is the output:
I love cats and cats like me.
Codebyte Example: Removing Substrings Using .replace()
This codebyte example uses the .replace()
method to remove “elephant “ from the myVar
string:
Frequently Asked Questions
1. Is .replace()
case-sensitive?
Yes, .replace()
is case-sensitive. For example, "Hello".replace("h", "J")
won’t work because “h” is not the same as “H”.
2. Can .replace()
be used with variables?
Yes. You can use variables for both old and new values in .replace()
:
old = "apple"new = "orange"fruit_text = "I like apple pie."print(fruit_text.replace(old, new))
Here is the output:
I like orange pie.
3. Can you replace substrings in a loop using .replace()
?
Yes, and you can also chain .replace()
calls for multiple replacements:
text = "I love red and blue."text = text.replace("red", "green").replace("blue", "yellow")print(text)
Here is the output:
I love green and yellow.
All contributors
- Sriparno08
- design2461360801
- christian.dinh
- Anonymous contributor
- Anonymous contributor
- CyberRedPanda
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Data Scientist: Machine Learning Specialist
Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.Includes 27 CoursesWith Professional CertificationBeginner Friendly95 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours