Change language

Python | Count the overlapping substring in a given string

| |

Note that in Python the count () function returns the number of substrings in a given string, but it does not produce correct results when two occurrences of a substring overlap. Consider this example —

string = "GeeksforGeeksforGeeksforGeeks"

 

print (string.count ( "GeeksforGeeks" ))

Exit :

 2 

The output we got here is 2, but the expected result is 3 because we also wanted to count the occurrence of the overlapping substring.

To solve this problem, we can use the find () function in Python. It returns the starting position of the first occurrence of a substring in a given string, then we increment that position by 1 and continue searching from that position to the end of the string.

Below is the implementation —

def CountOccurrences (string, substring):

# Initialize counter and start at 0

count = 0

start = 0

 

# Search string before

# we’ve reached the end of this

while start & lt;  len (string):

 

# Check if a substring from

# start position to end

flag = string.find (substring, start)

 

if flag! = - 1 :

# If substring is present, move & # 39; start & # 39; in

# next position from the beginning of the substring

start = flag + 1

 

# Increase score

count + = 1

else :

# If there is no more substring

  # return count

  return count

 
Driver code

string = "GeeksforGeeksforGeeksforGeeks"

print (CountOccurrences (string, " Python.Engineering " ))

Exit :

 3 

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically