如何计算Python中字符串中给定子字符串的出现次数?
例如:
>>> 'foo bar foo'.numberOfOccurrences('foo')
2
Run Code Online (Sandbox Code Playgroud) 计算给定字符串出现次数的最佳方法是什么,包括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中有更好的方法吗?