在Python中的字符串中查找多个出现的字符串 [英] Finding multiple occurrences of a string within a string in Python

查看:166
本文介绍了在Python中的字符串中查找多个出现的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<预><代码>>>>text = "允许你好空心">>>text.find("ll")1>>>

所以第一次出现的 ll 和预期的一样是 1.我如何找到它的下一次出现?

同样的问题适用于列表.考虑:

<预><代码>>>>x = ['会','好的','会']

如何找到所有带有索引的 ll?

解决方案

使用正则表达式,可以使用 re.finditer 查找所有(非重叠)出现:

<预><代码>>>>进口重新>>>text = '允许你好空心'>>>对于 re.finditer('ll', text) 中的 m:打印('会找到',m.start(),m.end())我找到了 1 3我找到了 10 12我找到了 16 18

或者,如果不想正则表达式的开销,也可以反复使用str.find 获取下一个索引:

<预><代码>>>>text = '允许你好空心'>>>指数 = 0>>>而索引

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

How do I find multiple occurrences of a string within a string in Python? Consider this:

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

So the first occurrence of ll is at 1 as expected. How do I find the next occurrence of it?

Same question is valid for a list. Consider:

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

How do I find all the ll with their indexes?

解决方案

Using regular expressions, you can use re.finditer to find all (non-overlapping) occurences:

>>> 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

Alternatively, if you don't want the overhead of regular expressions, you can also repeatedly use str.find to get the next index:

>>> 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

This also works for lists and other sequences.

这篇关于在Python中的字符串中查找多个出现的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆