.replace()
Anonymous contributor
Published Apr 24, 2021Updated Oct 13, 2023
Contribute to Docs
Replace a specific substring with another substring.
Syntax
string.replace(old, new, count)
The .replace()
string method takes in three parameters:
old
: The substring to search for. (Required)new
: The substring to replace. (Required)count
: A number specifying how many occurrences of the old value to replace. Default is all occurrences.
Example 1
.replace()
can be called either directly on a string:
welcome = "Hello, world!".replace("world", "Codecademy")print(welcome)# Output: Hello, Codecademy!
Or on a variable assigned to a string:
welcome = "Hello, world!"welcome = welcome.replace("world", "Codecademy")print(welcome)# Output: Hello, Codecademy!
Because replace()
is a method, it returns a new string and does not modify the original string. Therefore:
var = "x"var.replace("x", "y")print(var)# Output: x
By default, replace()
will replace all occurrences in the string. However, you can add an integer to specify how many strings should be replaced.
var = "I like cats and cats like me"var = var.replace("like", "LOVE")print(var)# Output: "I LOVE cats and cats LOVE me"var = "I like cats and cats like me"var = var.replace("like", "LOVE", 1)print(var)# Output "I LOVE cats and cats like me"
Examples
The replace()
method can be used to remove sections of a string entirely:
It can also be called multiple times on the same string:
If there are many words that need to be removed, consider using a for
loop:
All contributors
- Anonymous contributor
- Anonymous contributor
- CyberRedPanda
- design2461360801
- christian.dinh
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
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - 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 Friendly90 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