Start learning free

LESSON 66 OF 344 · STRINGS I

String Replace in Python: Using replace() Correctly

Lesson Read the full explanation

In Python, you can replace part of a string using the replace() method:

s.replace(old, new)         # replaces all occurrences
s.replace(old, new, count)  # replaces only first `count` occurrences

Here are some examples:

sentence = "I love cats"
result = sentence.replace("cats", "dogs")
print(result)  # "I love dogs"

text = "aaa"
print(text.replace("a", "b"))     # "bbb"
print(text.replace("a", "b", 2))  # "bba"

replace() returns a new string — the original is not modified.


Assignment
Follow the Coding Tutorial and replace "cats" with "dogs" in sentence!


Hint
Use sentence.replace("cats", "dogs") and assign it to result.

STEP 1 OF 1
    Ctrl + Enter to check

    PYTHON · STRINGS I

    String Replace in Python, explained

    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, and sentence still says I 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 gives Cats and dogs.
    • Replacing inside longer words. The method works on raw text, not on words. "cat catalog".replace("cat", "dog") produces dog dogalog, because the letters cat also 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" gives bXna, not a result that uses the second overlapping ana.
    • 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".

    1. Call replace on sentence. The first argument is the text to find, "cats". The second is the replacement, "dogs".
    2. Keep the new string. Because replace returns a new string instead of changing the old one, assign the call to a new variable named result.
    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 of old replaced by new.
    • s.replace(old, new, count) replaces only the first count occurrences.
    • 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.
    Keep going with PythonAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free