Reputation: 19
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: ")))
Upvotes: 1
Views: 224
Reputation: 261
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 ,
Upvotes: 0
Reputation: 1077
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: ")))
Upvotes: 0
Reputation: 15488
Try the replace method instead:
def replace(phrase):
replaced = phrase.replace("what","the")
return replaced
Upvotes: 1