Skip to content Skip to sidebar Skip to footer

Finding Number Of Times A Substring Exists In A String - Python

I am trying to find the # of times a substring, in this case 'bob' appears in a string. My solution works for some strings, but not for all. For example, the answer to the follow

Solution 1:

The problem is that s.count() returns the number of non-overlapping occurrences of substring sub in the range [start, end].

To count overlapping strings use regex

import re

text = 'bobbisbobobugbobobbobbobo'
print(len(re.findall('(?=bob)', text)))

Solution 2:

Your solution does not work because str.count does not count overlapping matches.

Despite there’s plenty other solutions, another possible way to do this is to use the advanced regex module:

import regex as re
s = 'bobbisbobobugbobobbobbobo'
print(len(re.findall("bob", s, overlapped=True)))

# 7

Solution 3:

You seem to want overlapping counts. str.count will not get you there, unfortunately, because it does not overlap substring searches. Try slicing and counting.

Here's a solution with a collections.Counter though it can be done just about any other way as long as you slice it right.

from collections import Counter

text = 'bobbisbobobugbobobbobbobo'
term = 'bob'
c = Counter([text[i : i + len(term)] for i in range(len(text))])
print(c[term])

7

Post a Comment for "Finding Number Of Times A Substring Exists In A String - Python"