Replace a specific substring with another substring.
string.replace(old, new, count)
.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.
.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!
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
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"
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
- christian.dinh2481 total contributions
- Anonymous contributorAnonymous contributor3077 total contributions
- Anonymous contributorAnonymous contributor23 total contributions
- CyberRedPanda27 total contributions