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
  • 70
  • 1
  • 10
Priyom saha
  • 598
  • 1
  • 5
  • 23

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
  • 35,525
  • 9
  • 94
  • 135
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,572
  • 2
  • 12
  • 27
paweloque
  • 17,890
  • 25
  • 77
  • 135