>>> '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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With