.replace()
design246136080119 total contributions
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
- design246136080119 total contributions
- christian.dinh2476 total contributions
- Anonymous contributorAnonymous contributor3071 total contributions
- Anonymous contributorAnonymous contributor23 total contributions
- CyberRedPanda27 total contributions
- design2461360801
- christian.dinh
- Anonymous contributor
- Anonymous contributor
- CyberRedPanda
Looking to contribute?
- 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.