1
s = "ANANAS"
print(s.count("ANA"))
print(s.count("AN"))
print(s.count("A"))

"ANA" occurs two times in "ANANAS" but python prints 1 whereas "AN" occurs two times and python prints 2. "A" occurs three times and python prints 3 as output. Why is this strange behaviour?

raviTeja
  • 338
  • 1
  • 7
  • 21

2 Answers2

1

Straight from the documentation:

str.count(sub[, start[, end]])
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.

The two occurences of "ANA" in "ANANAS" are overlapping, hence s.count("ANA") only returns 1.

glhr
  • 4,439
  • 1
  • 15
  • 26
  • then how to use count() when there is a overlap – raviTeja Apr 17 '19 at 06:00
  • `count()` is not the right tool for the job here. See [this post](https://stackoverflow.com/questions/2970520/string-count-with-overlapping-occurrences) which shows different ways of counting overlapping sub-strings. – glhr Apr 17 '19 at 06:02
1

This is because in your sub string ANA will be only counted twice if it's something like "testANAANAAN " I.e two full occurrences of ANA . As, in your case if it already checked first full substring it will not use that string part again from full string and will look for matching substring in rest of string.

A 786
  • 488
  • 1
  • 6
  • 16