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

新手上路,请多包涵

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

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

因此 ll 的第一次出现如预期的那样为 1。我如何找到它的下一次出现?

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

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

我如何找到所有 ll 及其索引?

原文由 user225312 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 350
2 个回答

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

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

原文由 poke 发布,翻译遵循 CC BY-SA 3.0 许可协议

我想你要找的是 string.count

 "Allowed Hello Hollow".count('ll')
>>> 3

希望这可以帮助

注意:这只会捕获非重叠事件

原文由 inspectorG4dget 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题