Start learning free

LESSON 67 OF 673 · STRINGS I

String Replace in Python

Lesson

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