在Python中查找字符串中多次出现的字符串

在Python中查找字符串中多次出现的字符串

如何在Python中的字符串中找到多次出现的字符串?考虑一下:

>>> text = "Allowed Hello Hollow">>> text.find("ll")1>>>

所以第一次出现的ll是1,如预期的那样。我如何找到它的下一个出现?

同样的问题对列表有效。考虑:

>>> x = ['ll', 'ok', 'll']

如何查找所有ll索引?


饮歌长啸
浏览 3271回答 3
3回答

精慕HU

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

狐的传说

使用正则表达式,您可以使用re.finditer查找所有(非重叠)出现的事件:>>> import re>>> text = 'Allowed Hello Hollow'>>> for m in re.finditer('ll', text):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;print('ll found', m.start(), m.end())ll found 1 3ll found 10 12ll found 16 18或者,如果您不想要正则表达式的开销,您也可以重复使用str.find以获取下一个索引:>>> text = 'Allowed Hello Hollow'>>> index = 0>>> while index < len(text):&nbsp; &nbsp; &nbsp; &nbsp; index = text.find('ll', index)&nbsp; &nbsp; &nbsp; &nbsp; if index == -1:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; print('ll found at', index)&nbsp; &nbsp; &nbsp; &nbsp; index += 2 # +2 because len('ll') == 2ll found at&nbsp; 1ll found at&nbsp; 10ll found at&nbsp; 16这也适用于列表和其他序列。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python