-2

how to use python loop function to replace all "cat" with "dog" in the statement of "The cat saw another cat and called the other cat to see the cat in the cat house"?

martineau
  • 119,623
  • 25
  • 170
  • 301

3 Answers3

1

You should just use the string replace function instead -

s = "The cat saw another cat and called the other cat to see the cat in the cat house"
s.replace("cat", "dog")
'The dog saw another dog and called the other dog to see the dog in the dog house'
Sam Dolan
  • 31,966
  • 10
  • 88
  • 84
0

Just use .replace():

s="The cat saw another cat and called the other cat to see the cat in the cat house".replace('cat','dog')
Wasif
  • 14,755
  • 3
  • 14
  • 34
0

More noob-ish way for you to experiment with for loops and string manipulation using lists.

my_string ="The cat saw another cat and called the other cat to see the cat in the cat house"

new_string = []

for i in my_string.split():
  if i != 'cat':
    new_string.append(i)
  else:
    new_string.append('dog')

print(' '.join(new_string))
DarknessPlusPlus
  • 543
  • 1
  • 5
  • 18