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
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
- Find the
indexof the first occurrence of the
- If index is non-negative, update the
startwith the result of
indexobtained 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.
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)
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.
- Numpy sqrt() – Find Square Root of Numbers
- Python – Check if Number is Armstrong
- How to Get Number of Elements in Pandas DataFrame?
- How to Swap Two Numbers in Python?
- Python – Smallest of Three Numbers
- How to Get Number of Axes in Pandas DataFrame?
- Python – Sum of Two Numbers
- Python – Factorial of a Number
- Python Program to Add Two Numbers
- Reverse a Number in Python