+ 4
What am I doing wrong in this code?
You’re working on a search engine. Watch your back Google! The given code takes a text and a word as input and passes them to a function called search(). The search() function should return "Word found" if the word is present in the text, or "Word not found", if it’s not. Sample Input "This is awesome" "awesome" Sample Output Word found This is what I've written - https://code.sololearn.com/cfVAbzE5oF5E/?ref=app The problem in my code is that it's not able to find the word and is always giving "Word not found" as the the output. So what am I missing in the code? Where is the error? Am I not using the "in" operator correctly or is it something else?
6 ответов
+ 4
You are doing it wrong. If you iterate it like this:
for element in text:
what you are actually doing is going through the text character by character. It will never find a match.
try printing the element.
for element in text:
print(element)
it will give you a character by character iteration. None of that will satisfy your condition.
Split the text into a list first and search for it in the list.
Like the answer above:
text.split() is what you need to do first.
+ 6
The variable c that you are using inside the function is not the same as the one outside the function. The first is local, the latter global.
You need to work with "return". Take another look at lesson 42.1.
+ 5
def search(text, word):
return "Word"+" not"*(not word in text.split())+ " found"
print(search("hello world",'hello'))
+ 2
I also think it is possible to use the "in" operator
If word in text:
return 1
+ 2
yes, it is the one to use for strings.
I think this should be the best answer.
I always forget this use of 'in' for strings. It is the simplest method.
Everone should upvote Dylan Heslop !
+ 1