如何在Python中使用.index返回单词的多个索引

时间:2016-11-16 10:16:22

标签: python

我正在使用Python中的命令.index。我希望能够输入一个句子,然后Python返回我选择的单词的多个索引。例如,如果我输入句子“我爱你,你爱我,我们都爱巴尼”,然后选择“爱”这个词,我希望它返回“2”,“5”,“9”。但相反,我的代码只返回第一个,“2”。

sentence = input("Enter a sentence")
word = input("Enter the word")
position = sentence.index(word)
print(position)

请您帮我编辑这段代码,以便返回所选单词的多个索引。

谢谢

4 个答案:

答案 0 :(得分:0)

.index仅返回第一次出现。你可以试试这个:

position = [idx+1 for idx,w in enumerate(sentence.split()) if w == word]
print(position)

答案 1 :(得分:0)

您可以使用空格分割句子中的单词,然后搜索特定单词。

例如:

textSplit = sentence.split(' ')
for i in range(len(textSplit)):
   if textSplit[i] == word:
      print i+1

答案 2 :(得分:0)

使用enumarate(注意:第一个单词的索引为0)和split

s = "i love you you love me we all love barney"
for wordno, word in enumerate(s.split()):
    if word == "love":
        print(wordno)

输出:

1
4
8

答案 3 :(得分:0)

indices = [i+1 for i, x in enumerate(sentence.split()) if x == word]

指数包含所有位置