replace the word "dog" with the word "cat" in the following sentence: "the quick brown fox jumps over the lazy dog." in python

Here's the Python code that uses the replace() method to replace the word "dog" with "cat" in the given sentence:

main.py
sentence = "the quick brown fox jumps over the lazy dog."
new_sentence = sentence.replace("dog", "cat")
print(new_sentence)
124 chars
4 lines

Output:

main.py
the quick brown fox jumps over the lazy cat.
45 chars
2 lines

Alternatively, you can use regular expressions to replace the word "dog" with "cat" in the given sentence. Here's the Python code for it:

main.py
import re

sentence = "the quick brown fox jumps over the lazy dog."
new_sentence = re.sub(r'\bdog\b', 'cat', sentence)
print(new_sentence)
140 chars
6 lines

Output:

main.py
the quick brown fox jumps over the lazy cat.
45 chars
2 lines

In this code, re.sub() is used to replace the word "dog" with "cat" using the regular expression r'\bdog\b'. \b denotes a word boundary.

gistlibby LogSnag