String count with overlapping occurrences

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

    0 讨论(0)
  • 2020-11-22 00:00

    You can also try using the new Python regex module, which supports overlapping matches.

    import regex as re
    
    def count_overlapping(text, search_for):
        return len(re.findall(search_for, text, overlapped=True))
    
    count_overlapping('1011101111','11')  # 5
    
    0 讨论(0)
  • 2020-11-22 00:01

    Here is my edX MIT "find bob"* solution (*find number of "bob" occurences in a string named s), which basicaly counts overlapping occurrences of a given substing:

    s = 'azcbobobegghakl'
    count = 0
    
    while 'bob' in s:
        count += 1 
        s = s[(s.find('bob') + 2):]
    
    print "Number of times bob occurs is: {}".format(count)
    
    0 讨论(0)
  • 2020-11-22 00:01
    def count_overlaps (string, look_for):
        start   = 0
        matches = 0
    
        while True:
            start = string.find (look_for, start)
            if start < 0:
                break
    
            start   += 1
            matches += 1
    
        return matches
    
    print count_overlaps ('abrabra', 'abra')
    
    0 讨论(0)
提交回复
热议问题