3 回答

TA贡献1845条经验 获得超8个赞
使用正则表达式,您可以使用re.finditer查找所有(非重叠)出现的事件:
>>> import re
>>> text = 'Allowed Hello Hollow'
>>> for m in re.finditer('ll', text):
print('ll found', m.start(), m.end())
ll found 1 3
ll found 10 12
ll found 16 18
或者,如果您不想要正则表达式的开销,您也可以重复使用str.find以获取下一个索引:
>>> text = 'Allowed Hello Hollow'
>>> index = 0
>>> while index < len(text):
index = text.find('ll', index)
if index == -1:
break
print('ll found at', index)
index += 2 # +2 because len('ll') == 2
ll found at 1
ll found at 10
ll found at 16
这也适用于列表和其他序列。

TA贡献1804条经验 获得超3个赞
使用正则表达式,您可以使用re.finditer查找所有(非重叠)出现的事件:
>>> import re
>>> text = 'Allowed Hello Hollow'
>>> for m in re.finditer('ll', text):
print('ll found', m.start(), m.end())
ll found 1 3
ll found 10 12
ll found 16 18
或者,如果您不想要正则表达式的开销,您也可以重复使用str.find以获取下一个索引:
>>> text = 'Allowed Hello Hollow'
>>> index = 0
>>> while index < len(text):
index = text.find('ll', index)
if index == -1:
break
print('ll found at', index)
index += 2 # +2 because len('ll') == 2
ll found at 1
ll found at 10
ll found at 16
这也适用于列表和其他序列。
添加回答
举报