2014-01-29 38 views
3

所以我知道str.index(substring,begin,end = len(str))返回從begin開始的子串的第一個索引。有沒有更好的(更快,更乾淨)的方式來獲取字符串的下一個索引,而不僅僅是將開始索引更改爲最後發生的索引+目標字符串的長度?即(這是我運行的代碼)找到一個字符串中的子串的第一個索引 - python 2.7

full_string = "the thing is the thingthe thing that was the thing that did something to the thing." 
target_string = "the thing" 

count = full_string.count(target_string) 
print 'Count:', count 

indexes = [] 
if (count > 0): 
    indexes.append(full_string.index(target_string)) 
    i = 1 
    while (i < count): 
     start_index = indexes[len(indexes) - 1] + len(target_string) 

     current_index = full_string.index(target_string, start_index) 
     indexes.append(current_index) 
     i = i + 1 

print 'Indexes:', indexes 

輸出:

Count: 5 
Indexes: [0, 13, 22, 41, 73] 

回答

3

您可以使用re.finditer和列表理解:

>>> import re 
>>> [m.start() for m in re.finditer(target_string, full_string)] 
[0, 13, 22, 41, 73] 

match objects有兩個有用的方法.start().end(),這些返回當前組匹配的子串的開始和結束索引。

另一種方法使用切片:

>>> [i for i in xrange(len(full_string) - len(target_string) + 1) 
          if full_string[i:i+len(target_string)] == target_string] 
[0, 13, 22, 41, 73] 
2

您可以創建一個簡單的發電機:

def gsubstrings(string, sub): 
    i = string.find(sub) 
    while i >= 0: 
     yield i 
     i = string.find(sub, len(sub) + i) 

>>> list(gsubstrings(full_string, target_string)) 
[0, 13, 22, 41, 73] 
相關問題