Python中如何返回word using.index的多个索引

2024-03-28 09:46:54 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

请你能帮我编辑这个代码,使它返回所选单词的多个索引吗。在

谢谢


Tags: the代码命令编辑inputindexposition单词
3条回答

使用^{}(注意:第一个单词的索引将是0)和^{}

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

输出:

^{pr2}$

你可以用空格把句子中的单词分开,然后搜索特定的单词。在

例如:

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

.index只返回第一个匹配项。你可以试试这个:

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

相关问题 更多 >