Python有string.find()和string.rfind()来获取字符串中子字符串的索引。
我想知道是否有像string.find_all()这样的东西可以返回所有找到的索引(不仅是从开始的第一个索引,还是从结束的第一个索引)。
例如:
string = "test test test test"
print string.find('test') # 0
print string.rfind('test') # 15
#this is the goal
print string.find_all('test') # [0,5,10,15]
要统计出现次数,请参见计算字符串中子字符串出现的次数。
同样,旧线程,但这里是我的解决方案使用生成器和普通str.find。
def findall(p, s):
'''Yields all the positions of
the pattern p in the string s.'''
i = s.find(p)
while i != -1:
yield i
i = s.find(p, i+1)
例子
x = 'banananassantana'
[(i, x[i:i+2]) for i in findall('na', x)]
返回
[(2, 'na'), (4, 'na'), (6, 'na'), (14, 'na')]
同样,旧线程,但这里是我的解决方案使用生成器和普通str.find。
def findall(p, s):
'''Yields all the positions of
the pattern p in the string s.'''
i = s.find(p)
while i != -1:
yield i
i = s.find(p, i+1)
例子
x = 'banananassantana'
[(i, x[i:i+2]) for i in findall('na', x)]
返回
[(2, 'na'), (4, 'na'), (6, 'na'), (14, 'na')]
这不完全是OP要求的,但你也可以使用split函数来获得所有子字符串不出现的列表。OP没有指定代码的最终目标,但如果您的目标是删除子字符串,那么这可能是一个简单的一行程序。对于更大的字符串,可能有更有效的方法来做到这一点;在这种情况下,正则表达式更可取
# Extract all non-substrings
s = "an-example-string"
s_no_dash = s.split('-')
# >>> s_no_dash
# ['an', 'example', 'string']
# Or extract and join them into a sentence
s_no_dash2 = ' '.join(s.split('-'))
# >>> s_no_dash2
# 'an example string'
我简单浏览了一下其他的答案,如果这个已经在上面了,我很抱歉。