0

IMO the substring BAB occurs 2 times in BABAB Why Python returns 1?

 print "BABAB".count("BAB")

Any help would be appreciated

Gnuz
  • 19
  • 2

3 Answers3

3

‍‍str.count just returns the number of non-overlapping matches, if you want to get number of all matches include overlapping matches you can use regular expression with re.findall

>>> re.findall(r'(?=(BAB))',"BABAB")
['BAB', 'BAB']

And for count the number of matches you can use a generator expression within sum function and use re.finditer instead of re.findall which is more optimized in term of memory use :

>>> sum(1 for _ in re.finditer(r'(?=(BAB))',"BABAB"))
2

(?=(BAB)) is a positive look-ahead that match the places which followed by BAB.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
1

Per the documentation (emphasis mine):

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.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
1

String is "BABAB". By using count() it'll return number of non-overlapping matches like this: "BAB|AB", so it's counted only once.. Try with string "BABBAB" and you will get 2. Example:

>>> x = "BABAB"
>>> x.count("BAB")
1
>>> x = "BABBAB"
>>> x.count("BAB")
2
NikolaTECH
  • 76
  • 10