How do you check if the words exist in the sentence in Python?
So far I have got... the_sentence = ("I love chocolate and chocolate loves me")
sentence = the_sentence.split() print(sentence) sentence_1 = raw_input("Enter a word") def "word": if word in the_sentence: print "Yes" elif word not in the_sentence: print "Nope" Thanks

Respuesta :

First off, the function word needs to be before the rest of the code or else when you call word() it would be undefined and error.

The string.split() method splits a string on the word boundary that you pass to it. If nothing is passed, split() defaults to space. split() splits the string into a list:

foo = "Hello World"
bar = foo.split( ' ' )
print bar
[ "Hello", "World" ]

The word function just needs to iterate ( a for loop ) through sentence and

if sentence[ ] == sentence_1:
   print "Yes"
   return
elif:
   pass
print "Nope"