2016-02-03 27 views
-65

这是我的代码:如何找到一个单词的所有出现的所有指标中的字符串

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) 

我能够得到第一发生在串词的索引。我怎样才能得到全部的发生?

+5

纯代码编写请求是题外话堆栈溢出 - 我们希望有关问题在这里以*特定*编程问题 - 但我们会很乐意帮助你自己写!告诉我们[您尝试过的](http://whathaveyoutried.com),以及您卡在哪里。这也将帮助我们更好地回答你的问题。 – Cerbrus

+4

@GeorgeStocker:虽然我可以理解它不应该被删除,但这是一个教科书的代码请求的情况下... – Cerbrus

+3

@Cerbrus我还没有找到一个关于“纯代码写入请求”的关闭理由脱离主题;事实上,如果他们不要求太多,我们可以明确地与他们联系:http://meta.stackexchange.com/a/224104/16587 –

回答

57

使用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) 
+0

我认为值得指出的是,它仅适用于“非重叠匹配”,因此不适用于:sentence =“ababa”和word =“aba” – AnukuL

相关问题