在Python中的字符串中查找多个出现的字符串 [英] Finding multiple occurrences of a string within a string in Python
问题描述
如何在 Python 中的字符串中找到多个出现的字符串?考虑一下:
<预><代码>>>>text = "允许你好空心">>>text.find("ll")1>>>所以第一次出现的 ll
和预期的一样是 1.我如何找到它的下一次出现?
同样的问题适用于列表.考虑:
<预><代码>>>>x = ['会','好的','会']如何找到所有带有索引的 ll
?
使用正则表达式,可以使用 re.finditer
查找所有(非重叠)出现:
或者,如果不想正则表达式的开销,也可以反复使用str.find
获取下一个索引:
这也适用于列表和其他序列.
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屋!