-7

I'm having fun with some challenges and one of them makes me count substrings in a string. I have a problem specifically with "banana":

str = "banana"
print(str.count("ana"))

This should return 2 because "ana" appears two times:

b a n a n a
  a n a
      a n a

But str.count("ana") returns only 1. I've also tried with regexp:

import re
str = "banana"
print(len(re.findall("ana", str)))

But it also returns 1. Am I missing something?

thank you!

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
  • 3
    As the docs say, `str.count` counts _non-overlapping_ occurrences of the the substring. – PM 2Ring May 22 '18 at 19:03
  • 1
    As an aside, you shouldn't call your variables `str` or any other built-in types/functions. – sjw May 22 '18 at 19:05
  • You can use regex module which supports overlapping pattern matching. print(len(regex.findall("ana", str,overlapped=True))) – Ash Ishh May 22 '18 at 19:14

1 Answers1

0

Yes, you are missing something.

str.count(): Return the number of (non-overlapping) occurrences of substring sub in string s

jeremysprofile
  • 10,028
  • 4
  • 33
  • 53