我有一个程序要求输入一个句子,然后要求输入一个词,并告诉你那个词的位置:
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")
但是,当我编辑程序时,如果输入的单词不在句子中,则打印“this isn't in the sentence”,我无法让程序正常工作
请您参考如下方法:
列表是序列,因此您可以使用 the in operation在它们上测试 words 列表中的成员资格。如果在里面,用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.")
带有示例输入:
enter sentence: hello world
enter word to locate position: world
Position of word: 1
并且,一个错误的案例:
enter sentence: hello world
enter word to locate position: worldz
Word is not in the given sentence.
如果您要检查多个匹配项,那么使用 enumerate 的列表理解是可行的方法:
r = [i for i, j in enumerate(words, start=1) if j == askedword]
然后检查列表是否为空并相应地打印:
if r:
print("Positions of word:", *r)
else:
print("Word is not in the given sentence.")
