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

2024-06-01 00:00:43 发布

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

这是我的代码:

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)

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


Tags: ininputhavenotthisaresentenceword
1条回答
网友
1楼 · 发布于 2024-06-01 00:00:43

使用^{}

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)

相关问题 更多 >