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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35185374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:06:37  来源:igfitidea点击:

How to find all the indexes of all the occurrences of a word in a string

pythonstringindexingfind-occurrences

提问by Mr.Code

This is my code:

这是我的代码:

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)

I am able to get the index of the firstoccurrence of a word in string. How can I get allof the occurrences?

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

采纳答案by Idos

Use re.finditer:

使用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())

For word = "this"and sentence = "this is a sentence this this"this will yield the output:

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

(0, 4)
(19, 23)
(24, 28)