python – 字符串计数与重叠出现

什么是计数给定字符串出现次数的最好方法,包括在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

或者有更好的方式在python?

嗯,这可能更快,因为它做了比较在C:

def occurrences(string, sub):
    count = start = 0
    while True:
        start = string.find(sub, start) + 1
        if start > 0:
            count+=1
        else:
            return count
http://stackoverflow.com/questions/2970520/string-count-with-overlapping-occurrences

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:python – 字符串计数与重叠出现