Skip to content Skip to sidebar Skip to footer

Python String Count Not Working Properly?

There are two occurrences of 'aba' in 'ababa' (0th index and 2nd index): myString = 'ababa' print(myString.count('aba')) Yet this code outputs a value of: 1 I know this issue seem

Solution 1:

From the Python string function documentation

Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

count does not count overlapping occurrences.

If you want to count overlapping occurrences you can use regex with a lookahead assertion:

import re
print(len(re.findall('(?=aba)', 'ababa')))

Solution 2:

Documentation to the rescue: https://docs.python.org/2/library/string.html

Return the number of (non-overlapping) occurrences of substring sub in string s[start:end]. Defaults for start and end and interpretation of negative values are the same as for slices.

Post a Comment for "Python String Count Not Working Properly?"