例如,我的程序存储了一个句子,然后要求用户从这个句子中输入一个单词。但是,如果单词在句子中出现两次,有没有一种方法可以使用迭代python打印出单词的位置
sentence = (' hello im jeffery hello who are you?')
print (sentence)
word = input('enter a word from the sentence')
print (word)
split = sentence.split(' ')
if word in split:
posis = split.index()
print (posis)
生成一个返回匹配索引列表的函数。如果找不到单词,则返回空列表。如果只返回一次,则只返回列表中的一个元素。例如
然后你就可以调用它来得到结果:
我在别处找到了这个答案:How to find all occurrences of an element in a list?
例如
打印[0,1]
相关问题 更多 >
编程相关推荐