String count with overlapping occurrences

前端 未结 22 3036
耶瑟儿~
耶瑟儿~ 2020-11-21 23:25

What\'s the best way to count the number of occurrences of a given string, including overlap in Python? This is one way:

def function(string, str_to_search_f         


        
22条回答
  •  迷失自我
    2020-11-21 23:50

    def count_substring(string, sub_string):
        count = 0
        for pos in range(len(string)):
            if string[pos:].startswith(sub_string):
                count += 1
        return count
    

    This could be the easiest way.

提交回复
热议问题