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: ")))
2
  • 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. Commented Oct 20, 2020 at 1:59
  • Does this answer your question? Replacing specific words in a string (Python) Commented Sep 6, 2021 at 12:00

3 Answers 3

1

Try the replace method instead:

def replace(phrase):
  replaced = phrase.replace("what","the")
  return replaced
Sign up to request clarification or add additional context in comments.

Comments

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: ")))

Comments

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 ,

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.