PythonMastery
Python programs · Strings · beginner

Replace a word in a string in Python

Replace every match or only the first with str.replace(), ignore capital letters with re.sub(), and replace whole words only with \\b.

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

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.

To count a word before you replace it, see count occurrences of a substring.

Learn the idea: Working with Strings, Regular Expressions