-2

My question is that why python giving the ans is 7 without having the string in the count method

txt = "banana"
x = txt.count("")
print(x)
001
  • 13,291
  • 5
  • 35
  • 66

2 Answers2

0

According to python docs, if the string parameter is empty, the count method returns the length of the original string + 1.

If sub is empty, returns the number of empty strings between characters which is the length of the string plus one.

azro
  • 53,056
  • 7
  • 34
  • 70
Lior v
  • 464
  • 3
  • 12
-3

It can be fix by passing ' ' instead of '':

>>> 'banana'.count()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: count() takes at least 1 argument (0 given)
>>> 'banana'.count('')
7
>>> len('banana' ) + len('!')
7
>>> 'banana'.count( ' ')
0
>>> 'banana'.swapcase().count('B')
1

Explained

Q: Why it's printing the 7?

A: The len of an input string ("bnanana" == 6) + one extra character (1) --> total: 7

rv.kvetch
  • 9,940
  • 3
  • 24
  • 53