1

I was coding in python to find the number of times a single sub string comes in a given string I used the predefined method of Python3 ie .count()

1The thing is here when I am trying to count the number of time 'B' or 'A' or'NA' occurs it gives me the perfect result but when I am counting number of 'ANA' present it should give me 2 but gives the output as 1

s="BANANA"
print("B = ",s.count('B'))
print("NA = ",s.count('NA'))
print("NAN = ",s.count('NAN'))
#Here the mistake occurs
print("ANA = ",s.count('ANA'))
realmanusharma
  • 330
  • 2
  • 10
Priyom saha
  • 630
  • 1
  • 9
  • 28

2 Answers2

5

str.count counts non-overlapping occurences. The first "ANA" shares the "A" with the second "ANA", so the output is 1 instead of 2.

If you want to count overlapping occurences, see the answers to this question.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
0

The string.count(sub[, start[, end]) function counts the non-overlapping substrings. That's why you get only 1 as a result.

This is the documentation of this function:

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.

See string.count(sub[, start[, end]])

Agile_Eagle
  • 1,710
  • 3
  • 13
  • 32
paweloque
  • 18,466
  • 26
  • 80
  • 136