如何查找字符串中所有单词出现的所有索引

Mr.*_*ode -64 python string indexing find-occurrences

这是我的代码:

sentence = input("Give me a sentence ")

word = input("What word would you like to find ")


sentence_split = sentence.split()


if word in sentence_split:
   print("have found",word,)
   print("The word comes in the position" )
else:
   print("error have not found",word)

wordfound = (sentence_split.index(word)+1)

print(wordfound)
Run Code Online (Sandbox Code Playgroud)

我能够获得字符串中第一次出现的单词的索引.我怎样才能得到所有的事件?

Ido*_*dos 67

用途re.finditer:

import re
sentence = input("Give me a sentence ")
word = input("What word would you like to find ")
for match in re.finditer(word, sentence):
    print (match.start(), match.end())
Run Code Online (Sandbox Code Playgroud)

对于word = "this",sentence = "this is a sentence this this"这将产生输出:

(0, 4)
(19, 23)
(24, 28)
Run Code Online (Sandbox Code Playgroud)

  • 我认为值得指出的是,它仅适用于“非重叠匹配”,因此不适用于:句子=“ ababa”和单词=“ aba” (3认同)