如何找到一个单词在字符串中所有出现的所有索引
How to find all the indexes of all the occurrences of a word in a string
这是我的代码:
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)
我能够获取字符串中第 次 出现的单词的索引。我怎样才能得到所有的出现?
使用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())
对于 word = "this"
和 sentence = "this is a sentence this this"
这将产生输出:
(0, 4)
(19, 23)
(24, 28)
这是我的代码:
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)
我能够获取字符串中第 次 出现的单词的索引。我怎样才能得到所有的出现?
使用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())
对于 word = "this"
和 sentence = "this is a sentence this this"
这将产生输出:
(0, 4)
(19, 23)
(24, 28)