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.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
