I have a program that asks for input of a sentence, then asks for a word, and tells you the position of that word:
sentence = input("enter sentence: ").lower()
askedword = input("enter word to locate position: ").lower()
words = sentence.split(" ")
for i, word in enumerate(words):
if askedword == word :
print(i+1)
#elif keyword != words :
#print ("this not")
However I cannot get the program to work correctly when I edit it to say that if the input word is not in the sentence, then print "this isn't in the sentence"
Lists are sequences, as such you can use the in
operation on them to test for membership in the words
list. If inside, find the position inside the sentence with words.index
:
sentence = input("enter sentence: ").lower()
askedword = input("enter word to locate position: ").lower()
words = sentence.split(" ")
if askedword in words:
print('Position of word: ', words.index(askedword))
else:
print("Word is not in the given sentence.")
With sample input:
enter sentence: hello world
enter word to locate position: world
Position of word: 1
and, a false case:
enter sentence: hello world
enter word to locate position: worldz
Word is not in the given sentence.
If you're looking to check against multiple matches then a list-comprehension with enumerate
is the way to go:
r = [i for i, j in enumerate(words, start=1) if j == askedword]
Then check on whether the list is empty or not and print accordingly:
if r:
print("Positions of word:", *r)
else:
print("Word is not in the given sentence.")
Jim's answer—combining a test for askedword in words
with a call to words.index(askedword)
—is the best and most Pythonic approach in my opinion.
Another variation on the same approach is to use try
- except
:
try:
print(words.index(askedword) + 1)
except ValueError:
print("word not in sentence")
However, I just thought I'd point out that the structure of the OP code looks like you might have been attempting to adopt the following pattern, which also works:
for i, word in enumerate(words):
if askedword == word :
print(i+1)
break
else: # triggered if the loop runs out without breaking
print ("word not in sentence")
In an unusual twist unavailable in most other programming languages, this else
binds to the for
loop, not to the if
statement (that's right, get your editing hands off my indents). See the python.org documentation here.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.