1

so this is the code i made in pyhton and for some reason it does not work so i hoped that someone here could help me find a solution * i am just a begginer *

    def replace(phrase):
    replaced = ""
    for word in phrase:
        if word == ("what"):
            replaced = replaced + "the"
        else:
            replaced = replaced + word
    return replaced

    print(replace(input("enter a phrase: ")))
  • 4
    Your for loop is `for word in phrase` but when you iterate over a string, you are actually iterating over each character. One way to iterate over words is `for word in phrase.split()`, which will split `phrase` by whitespace. – jkr Oct 20 '20 at 01:59
  • Does this answer your question? [Replacing specific words in a string (Python)](https://stackoverflow.com/questions/12538160/replacing-specific-words-in-a-string-python) – Tzane Sep 06 '21 at 12:00

3 Answers3

1

Try the replace method instead:

def replace(phrase):
  replaced = phrase.replace("what","the")
  return replaced
Wasif
  • 14,755
  • 3
  • 14
  • 34
0

Here we use .split() to split your phrase by the space. As a result you get a list of each word ['hi', 'what', 'world']. If you don't split it, you will loop through each character if the string instead and no character will ever equal "what"

 def replace(phrase):
    phrase = phrase.split()
    replaced = ""
    for word in phrase:
        if word == ("what"):
            replaced = replaced + " the "
        else:
            replaced = replaced + word
    return replaced

print(replace(input("enter a phrase: ")))
Halmon
  • 1,027
  • 7
  • 13
0

You can try this code, I hope it helps you

def replace(phrase):
    phrase = phrase.split()
    replaced = ""
    for word in phrase:
        if word == ("what"):
            replaced = replaced + " the"
        else:
            replaced = replaced +" "+ word
    return replaced[1:]

print(replace(input("enter a phrase: ")))

The output is:

enter a phrase: where what this what when ,
where the this the when ,
ZahraRezaei
  • 251
  • 2
  • 14