簡體   English   中英

找不到字符串中子串的第一個索引 - python 2.7

[英]find not just the first index of a substring in a string - python 2.7

所以我知道str.index(substring,begin,end = len(str))返回從begin開始的子字符串的第一個索引。 獲取字符串的下一個索引的方法是否更好(更快,更清晰),而不是簡單地將開始索引更改為最后一次出現的索引+目標字符串的長度? 即(這是我正在運行的代碼)

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]

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

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

匹配對象有兩個有用的方法.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]

您可以創建一個簡單的生成器:

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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM