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]
Run Code Online (Sandbox Code Playgroud) 如何在Python中的字符串中找到多次出现的字符串?考虑一下:
>>> text = "Allowed Hello Hollow"
>>> text.find("ll")
1
>>>
Run Code Online (Sandbox Code Playgroud)
所以第一次出现的ll是1,如预期的那样.我如何找到它的下一个出现?
同样的问题对列表有效.考虑:
>>> x = ['ll', 'ok', 'll']
Run Code Online (Sandbox Code Playgroud)
如何查找所有ll索引?
计算给定字符串出现次数的最佳方法是什么,包括python中的重叠?这是最明显的方式:
def function(string, str_to_search_for):
count = 0
for x in xrange(len(string) - len(str_to_search_for) + 1):
if string[x:x+len(str_to_search_for)] == str_to_search_for:
count += 1
return count
function('1011101111','11')
returns 5
Run Code Online (Sandbox Code Playgroud)
?
或者在python中有更好的方法吗?