+ 1
I wrote a code to solve the last question of pyton for beginners but it doesn't work properly. Can you help me?
text = input() word = input() def search(text,word): if text.index(word ): return"Word found" else: return"Word not found" print(search(text, word))
6 Respostas
+ 6
Mohammad Gheisari
text.index(word) produces a number as a position where the word was discovered
whereas
if word in text searches to see if the word exist
https://code.sololearn.com/cc2vlh9738Bv/?ref=app
+ 2
Mohammad Gheisari try
if word in text:
instead of
if text.index(word):
Also watch your indentations and spacing as it looks like
return"Word..
return "Word ..
+ 2
Mohammad Gheisari the advice from BroFar is best. Here is a little more about why your original approach might not work. Beware that text.index(word) returns 0 if word is found at the beginning of text. But in Boolean expressions 0 means false, so 'if text.index(word):' fails.
When there is no match, then index() raises an exception and again fails. To avoid an exception you may use find(), which returns -1 if not found, or the index if found. Now the if statement might alternatively work like this:
if text.find(word)>=0:
+ 1
Thanks a lot 🙏
+ 1
Thanks Briant.
0
Thanks a lot.
Would you describe me what is different between "if word in text" and " if text.index(word)??
When I used first code, it work when the word was in the text but when it's not I doesn't work.