Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string count not working properly? [duplicate]

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 seems really simple, but shouldn't the answer be 2 here?
If not, then isn't the count function not really doing what it's supposed to?

Is there a simple alternative?

like image 513
Dan Avatar asked Dec 07 '25 07:12

Dan


1 Answers

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')))
like image 198
Max Feng Avatar answered Dec 09 '25 19:12

Max Feng