Python String – Find the number of overlapping occurrences of a substring

Python – Find number of overlapping occurrences of a substring

There could be scenarios where the occurrences of a substring in a string could be overlapping. An example would be, the string abababa has overlapping occurrences of substring aba.

In this tutorial, we shall learn how to find the number of these overlapping occurrences of a substring, in a given string.

Steps to find the number of overlapping occurrences

To get the total number of occurrences of a substring in a string, where the occurrences could be overlapping, follow these steps.

  1. Traverse through the string using for loop and range(len(string)).
  2. Find the index of the first occurrence of the substring using String.find(substring, start).
  3. If index is non-negative, update the start with the result of index obtained in above step. Also increment the counter and update the looping variable of for loop in step 1 to index+1. If index is negative, break for loop.
  4. Counter would have the number of occurrences of a substring in the string.

Examples

1. Find number of overlapping occurrences of a search string in given string

In the following program, we have taken a string, and then a substring. We shall find the overlapping occurrences of substring in the string.

Python Program

string = 'abcdefghghghghghgh.'
substring = 'ghg'

count = 0
start = 0
if(len(string)>0 and len(string)<201):
	for i in range(len(string)):
		i = string.find(substring, start)
		if(i>0):
			start = i+1
			count += 1
		else:
			break
print(count)
Run Code Copy

Output

5

Summary

In this tutorial of Python Examples, we learned how to find the occurrences of a substring in a string, where the occurrences could be overlapping.

Related Tutorials

Code copied to clipboard successfully 👍