Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,954 questions

51,896 answers

573 users

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
...