How to count the number of overlapping occurrences of a substring in a string with Python

3 Answers

0 votes
def countOverlappingOccurrences(s, substr): 
    count = offset = 0
     
    for i in range(len(s)):
        i = s.find(substring, offset)
        if (i > 0):
            offset = i + 1
            count += 1
        else:
            break
        
    return count;
    
s = 'abcdefefefefefefef'
substring = 'efe'

print(countOverlappingOccurrences(s, substring))


'''
run:
    
6
  
'''

 



answered Oct 28, 2020 by avibootz
edited Aug 24, 2024 by avibootz
0 votes
import re

def countOverlappingOccurrences(s, substr): 
    return len(re.findall('(?={0})'.format(re.escape(substr)), s))
    
s = 'abcdefefefefefefef'
substring = 'efe'

print(countOverlappingOccurrences(s, substring))


'''
run:
    
6
  
'''

 



answered Aug 24, 2024 by avibootz
0 votes
def countOverlappingOccurrences(s, substr): 
    count = offset = 0
     
    while True:
        offset = s.find(substr, offset) + 1
        if offset > 0:
            count += 1
        else:
            return count
            
    
s = 'abcdefefefefefefef'
substring = 'efe'

print(countOverlappingOccurrences(s, substring))


'''
run:
    
6
  
'''

 



answered Aug 24, 2024 by avibootz

Related questions

...