What replace() does
The replace() method swaps one piece of text for another inside a string. You give it the text to look for and the text to put in its place, and it hands back the result:
sentence = "I love cats"
result = sentence.replace("cats", "dogs")
print(result) # I love dogs
print(sentence) # I love cats
The second print is the important one. Strings in Python are immutable, which means a string can never be changed after it is created. So replace() does not edit sentence. It builds a new string and returns it, and the original stays exactly as it was. The same holds for every string method, such as upper() and strip().
Replacing all, some or none
By default, every occurrence is replaced. An optional third argument limits how many replacements are made, counting from the left:
text = "aaa"
print(text.replace("a", "b")) # bbb
print(text.replace("a", "b", 2)) # bba
print(text.replace("a", "b", 0)) # aaa
With a count of 2, the first two a characters change and the third is left alone. A count of 0 changes nothing. When the old text is not present at all, you simply get an unchanged copy of the string, with no error:
print("I love cats".replace("birds", "dogs")) # I love cats
Deleting text
Replacing with an empty string removes the old text. This is a quick way to delete characters:
print("a b c".replace(" ", "")) # abc
Chaining several replacements
Because each call returns a string, you can call another string method on the result straight away. This lets you clean up text in several passes, each pass working on the output of the previous one:
print("tel: 555-1234".replace("-", " ")) # tel: 555 1234
print("a-b-c".replace("-", "", 1)) # ab-c
The second line removes only the first hyphen, because the count of 1 stops the replacing after one change. Read a chain from left to right: the first call runs first, and the next call receives its result.
Common mistakes
- Ignoring the return value. This is the classic bug. A line like
sentence.replace("cats", "dogs")on its own does nothing useful: the new string is created and then thrown away, andsentencestill saysI love cats. Either assign the result to a new variable, as the lesson does, or reassign the same name:sentence = sentence.replace("cats", "dogs"). - Forgetting case. Matching is case sensitive.
"Cats and cats".replace("cats", "dogs")only changes the lowercase one and givesCats and dogs. - Replacing inside longer words. The method works on raw text, not on words.
"cat catalog".replace("cat", "dog")producesdog dogalog, because the letterscatalso start the second word. - Swapping the arguments. The old text comes first and the new text second. Reversing them looks for the wrong thing and usually changes nothing.
- Overlapping matches. Matches are found from left to right, and each piece of text can belong to only one match. In
"banana", replacing"ana"with"X"givesbXna, not a result that uses the second overlappingana. - Counting by mistake. The third argument is a limit on replacements, not a starting position. If you need to change only the match at a given place, find its index first and build the new string from slices.
The exercise, step by step
The lesson provides sentence set to "I love cats". The goal is to produce the same sentence with "cats" replaced by "dogs".
- Call
replaceonsentence. The first argument is the text to find,"cats". The second is the replacement,"dogs". - Keep the new string. Because
replacereturns a new string instead of changing the old one, assign the call to a new variable namedresult.
sentence = "I love cats"
result = sentence.replace("cats", "dogs")
Now result holds "I love dogs", while sentence still holds "I love cats". Having both strings available is often useful, for example to compare the text before and after a cleanup.
No count is needed here, since the text has a single occurrence of "cats". In a sentence with several, the default would replace all of them.
Key takeaways
s.replace(old, new)returns a new string with every occurrence ofoldreplaced bynew.s.replace(old, new, count)replaces only the firstcountoccurrences.- Strings are immutable, so the original is never modified. Store the returned value.
- Matching is case sensitive and works on raw text, not whole words.
- Replacing with
""deletes the matched text.