您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

使用正则表达式,您可以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

这也适用于列表和其他序列。

python 2022/1/1 18:42:44 有269人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶