3 回答

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超6個(gè)贊
我會選擇Lev,但值得指出的是,如果您最終進(jìn)行了更復(fù)雜的搜索,那么使用re.finditer可能值得牢記(但是re經(jīng)常帶來的麻煩多于價(jià)值,但有時(shí)很容易知道)
test = "ooottat"
[ (i.start(), i.end()) for i in re.finditer('o', test)]
# [(0, 1), (1, 2), (2, 3)]
[ (i.start(), i.end()) for i in re.finditer('o+', test)]
# [(0, 3)]

TA貢獻(xiàn)1795條經(jīng)驗(yàn) 獲得超7個(gè)贊
def find_offsets(haystack, needle):
"""
Find the start of all (possibly-overlapping) instances of needle in haystack
"""
offs = -1
while True:
offs = haystack.find(needle, offs+1)
if offs == -1:
break
else:
yield offs
for offs in find_offsets("ooottat", "o"):
print offs
結(jié)果是
0
1
2
添加回答
舉報(bào)