String count with overlapping occurrences

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

    Function that takes as input two strings and counts how many times sub occurs in string, including overlaps. To check whether sub is a substring, I used the in operator.

    def count_Occurrences(string, sub):
        count=0
        for i in range(0, len(string)-len(sub)+1):
            if sub in string[i:i+len(sub)]:
                count=count+1
        print 'Number of times sub occurs in string (including overlaps): ', count
    

提交回复
热议问题