Menu Close

How to count string with overlapping occurrences with Python?

Sometimes, we want to count string with overlapping occurrences with Python.

In this article, we’ll look at how to count string with overlapping occurrences with Python.

How to count string with overlapping occurrences with Python?

To count string with overlapping occurrences with Python, we can use the string find method.

For instance, we write

def occurrences(string, sub):
    count = start = 0
    while True:
        start = string.find(sub, start) + 1
        if start > 0:
            count += 1
        else:
            return count

to create the occurrences function that finds the instances of the sub substring that from index start with find.

If start is bigger than 0, then there’s one instance of overlap, so we increment count by 1.

Once we stop finding overlaps, we return count.

Conclusion

To count string with overlapping occurrences with Python, we can use the string find method.

Posted in Python, Python Answers