Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does '12345'.count('') return 6 and not 5?

>>> '12345'.count('')
6

Why does this happen? If there are only 5 characters in that string, why is the count function returning one more?

Also, is there a more effective way of counting characters in a string?

like image 418
Macondo Avatar asked Jun 19 '15 22:06

Macondo


2 Answers

count returns how many times an object occurs in a list, so if you count occurrences of '' you get 6 because the empty string is at the beginning, end, and in between each letter.

Use the len function to find the length of a string.

like image 62
Bill the Lizard Avatar answered Oct 20 '22 01:10

Bill the Lizard


That is because there are six different substrings that are the empty string: Before the 1, between the numbers, and after the 5.

If you want to count characters use len instead:

>>> len("12345")
5
like image 28
nanofarad Avatar answered Oct 20 '22 01:10

nanofarad