The string method replace(old, new) returns a new string where every old is changed to new. A third argument limits how many are changed.
The program
python
text = "the cat sat on the mat with the other cat" print(text.replace("cat", "dog")) print(text.replace("cat", "dog", 1)) print(text)
output
the dog sat on the mat with the other dog the dog sat on the mat with the other cat the cat sat on the mat with the other cat
How it works
replace("cat", "dog")changes every "cat".replace("cat", "dog", 1)changes only the first one. The1is the count: the largest number of replacements to make.- Strings cannot be changed, so
replace()returns a new string. The last line shows thattextis the same as before. To keep the result, assign it:text = text.replace("cat", "dog"). replace()is case-sensitive, and it changes the text wherever it appears, even inside a longer word. The next two sections fix both of these.
Ignoring capital letters
The re module (regular expressions) has re.sub(pattern, new, text). With flags=re.IGNORECASE, it matches "cat", "Cat" and "CAT":
python
import re text = "Cat food. The cat likes CAT toys." print(text.replace("cat", "dog")) print(re.sub("cat", "dog", text, flags=re.IGNORECASE))
output
Cat food. The dog likes CAT toys. dog food. The dog likes dog toys.
Whole words only
\b in a pattern means a word boundary: the start or end of a word. \bcat\b matches "cat" on its own, but not the "cat" inside "category":
python
import re text = "The cat sat in the category of concatenated cats." print(text.replace("cat", "dog")) print(re.sub(r"\bcat\b", "dog", text)) def replace_word(text, old, new): pattern = rf"\b{re.escape(old)}\b" return re.sub(pattern, new, text, flags=re.IGNORECASE) print(replace_word("Cat or cat? Not the category.", "cat", "dog"))
output
The dog sat in the dogegory of condogenated dogs. The dog sat in the category of concatenated cats. dog or dog? Not the category.
- The
rbefore the string makes it a raw string, so\breachesreas written. In a normal string,"\b"is a backspace character. - "cats" is not changed, because "cat" is followed by "s", so there is no word boundary after it.
re.escape(old)adds a backslash before characters that have a special meaning in patterns, such as.and?. Use it when the word comes from the user.
To count a word before you replace it, see count occurrences of a substring.