【发布时间】:2016-01-31 17:33:10
【问题描述】:
我在 Python 3 中有以下代码,它查找并显示列表中搜索单词的第一个示例,即单词“now”位于位置 3,但如果该单词出现两次或列表中的更多内容,我找不到显示第二个/第三个等索引的方法。即单词“现在”出现在位置 3 和 5。
我在网上看到了一些非常复杂的版本,但想看看我是否可以让它变得非常简单。我知道 .index() 只能找到第一个索引,那么我可以使用其他方法吗?
代码:
sentence=input("Enter your sentence here: ")
sentence=sentence.lower()
words=(sentence.split())
print(words)
word_to_find=input("What word position do you want to find? ")
word_to_find=word_to_find.lower()
if word_to_find in words:
position=words.index(word_to_find)
print( "The word ", word_to_find, "is in position(s): ",position+1)
else:
print("No word exists")
非常感谢
【问题讨论】:
标签: list indexing python-3.4