0

For this code,

f='ana'
g='banana'
print(g.count(f))

Why it gives 1 as output and not 2.Is their any mistake in my code. Also could anyone suggest any alternate method.

aDEp
  • 1
  • 3
  • The [documentation](https://docs.python.org/2/library/string.html) for `count` says that it returns "the number of (non-overlapping) occurrences of substring sub in string s[start:end]." – David Conrad Sep 24 '20 at 20:29
  • Better link for Python 3 [documentation](https://docs.python.org/3/library/stdtypes.html#string-methods); still says non-overlapping. – David Conrad Sep 24 '20 at 20:33
  • @DavidConrad Thanks for my doubt clearing. Also Is their any method for counting 'overlapping' occurrences. – aDEp Sep 24 '20 at 20:34
  • I don't know of a standard method, but you could write your own. Search for the first occurrence, then search again starting one character after it, and so on. The reason the built-in method only finds non-overlapping is that as it searches for occurrences, it skips ahead to after the complete match to search again, rather than advancing only one character when searching again for the next match. – David Conrad Sep 28 '20 at 18:58

1 Answers1

0

Per the answers to this question which is a duplicate of your question, a potential approach would be:

def str_count(string, sub):
    count = start = 0
    while True:
        start = string.find(sub, start) + 1
        if start > 0:
            count+=1
        else:
            return count
2Clutch
  • 129
  • 10