Why does '12345'.count('') return 6 and not 5?
Question:
>>> '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?
Answers:
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
How many pieces do you get if you cut a string five times?
---|---|---|---|---|--- -> 6 pieces
The same thing is happening here. It counts the empty string after the 5
also.
len('12345')
is what you should use.
The most common way is to use len('12345')
. It returns the number of characters in a given string – in this case 5.
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.
Count and Len are two very different things. Len simply prints the length of the string (hence the name ‘Len’), while Count iterates through the string or list and gives you the number of times an object occurs, which counts the beginning and end of the string as well as in between each letter.
It’s the same reason why it makes sense for ''.count('')
to return 1
, not 0
.
>>> '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?
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
How many pieces do you get if you cut a string five times?
---|---|---|---|---|--- -> 6 pieces
The same thing is happening here. It counts the empty string after the 5
also.
len('12345')
is what you should use.
The most common way is to use len('12345')
. It returns the number of characters in a given string – in this case 5.
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.
Count and Len are two very different things. Len simply prints the length of the string (hence the name ‘Len’), while Count iterates through the string or list and gives you the number of times an object occurs, which counts the beginning and end of the string as well as in between each letter.
It’s the same reason why it makes sense for ''.count('')
to return 1
, not 0
.