在Python中查找字符串中的多个子字符串出现位置
我想知道在Python中,怎么找到一个字符串中出现的多个相同的子字符串?比如说:
>>> text = "Allowed Hello Hollow"
>>> text.find("ll")
1
>>>
在这个例子中,ll
第一次出现的位置是1,这很正常。那么我怎么找到它的下一个出现位置呢?
同样的问题也适用于列表。比如:
>>> x = ['ll', 'ok', 'll']
我怎么找到所有的ll
以及它们的位置呢?
19 个回答
30
对于列表的例子,可以使用一种叫做“推导式”的写法:
>>> l = ['ll', 'xx', 'll']
>>> print [n for (n, e) in enumerate(l) if e == 'll']
[0, 2]
对于字符串也是一样:
>>> text = "Allowed Hello Hollow"
>>> print [n for n in xrange(len(text)) if text.find('ll', n) == n]
[1, 10, 16]
这个方法会列出相邻的“ll”出现的情况,这可能是你想要的,也可能不是:
>>> text = 'Alllowed Hello Holllow'
>>> print [n for n in xrange(len(text)) if text.find('ll', n) == n]
[1, 2, 11, 17, 18]
40
我觉得你想要的功能是 string.count
"Allowed Hello Hollow".count('ll')
>>> 3
希望这对你有帮助
注意:这个方法只会计算不重叠的出现次数
148
通过使用正则表达式,你可以用 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
这个方法同样适用于列表和其他序列。