String count with overlapping occurrences

前端 未结 22 3395
耶瑟儿~
耶瑟儿~ 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:58

    An alternative very close to the accepted answer but using while as the if test instead of including if inside the loop:

    def countSubstr(string, sub):
        count = 0
        while sub in string:
            count += 1
            string = string[string.find(sub) + 1:]
        return count;
    

    This avoids while True: and is a little cleaner in my opinion

提交回复
热议问题