0

I am new to python and learning. As given here count() method when used on strings gives the number of occurrences of sub string in a string.

So when i Do :

'BANANA'.count('ANA')

Expected output should be 2 as 'ANA' occurs twice in 'BANANA' but count returns 1.

Can someone please explain this, or maybe i have misunderstood something.

Please point me in the right direction.

Mohan
  • 4,677
  • 7
  • 42
  • 65

2 Answers2

9
>>> help(str.count)
Help on method_descriptor:

count(...)
    S.count(sub[, start[, end]]) -> int

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

Notice the non-overlapping.

Christian König
  • 3,437
  • 16
  • 28
6

You can use regular expressions to find it. Use the function findall from module re to find overlapping occurences

import re
len(re.findall('(?=ANA)', 'BANANA'))

which yields 2.

Or yields 3 here:

import re
len(re.findall('(?=ANA)', 'BANANAANA'))
Philipp
  • 222
  • 3
  • 9
  • is there any easy way to do this without using a library ? – Mohan Feb 21 '17 at 13:43
  • 4
    You cannot load libraries? That the point of python. And re is surely no exotic library. – Philipp Feb 21 '17 at 13:43
  • Also `re` is part of the standard library so it's not like "using a library" in my opinion (at least not like using an external library). – MSeifert Feb 21 '17 at 13:46
  • @AngryCoder `re` is packaged with python so you just sticking an `import` statement in is not bother – WhatsThePoint Feb 21 '17 at 13:46
  • @AngryCoder Sure, you could use the `.find` method in a loop, but doing that's a bit messy compared to using the standard `re` module, since you need to keep track of the `start` arg you pass to `.find`. – PM 2Ring Feb 21 '17 at 13:47