所以我知道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]