Contents

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

- Traverse through the string using for loop and
`range(len(string))`

. - Find the
`index`

of the first occurrence of the`substring`

using`String.find(substring, start)`

. - 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. - Counter would have the number of occurrences of a substring in the string.

### Example 1: Number of overlapping occurrences of substring

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

- Python – Factorial of a Number
- Python – Sum of Two Numbers
- How to Swap Two Numbers in Python?
- Python – Largest of Three Numbers
- How to Get Number of Axes in Pandas DataFrame?
- Python – Smallest of Three Numbers
- Numpy sqrt() – Find Square Root of Numbers
- Python – Sum of First N Natural Numbers
- Python Program to Add Two Numbers
- How to Get Number of Elements in Pandas DataFrame?