.replace()
Published Apr 24, 2021Updated Sep 3, 2021
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 occurances in the string. However, you can add an integer to specifiy 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:
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.