2
votes

I know that str.count(sub) return the number of occurrences of substring sub. But I faced a strange problem that I cannot understand.
My code is as below:

str = 'helloworld'
print(str.count(''))
>>>11

The output is puzzling. Why does it return 11? If '' means any letters, why not return the length of it (10)? I haven't found any answers about this. Can anybody tell me about the implementation?

1
'' doesn't mean any letters, it means an empty string. There are 11 empty strings in 'helloworld', one at the start, nine between each pair of letters and one at the end. If you want the length, use len('helloworld'). - jonrsharpe
A string starts with an empty string and also ends with one – so always one more than the number of characters. - Jongware
Try looking at str.count.__doc__ - Scott Hunter
Think of "foo" as being equal to "" + "f" + "" + "o" + "" + "o" + "", which is in some sense the minimal number of empty strings to be found contained in the string "foo". - chepner

1 Answers

6
votes

'' doesn't mean any string, it means no string (aka, the empty string, or the 0-length string). There are, strictly speaking, an infinite number of 0-length strings in a string, but practically, len(string) + 1 is returned - one for just before first character, and one each for after every character.

This scenario has been explicitly special-cased in count.h:

if (sub_len == 0)
    return (str_len < maxcount) ? str_len + 1 : maxcount;

When the search string is the empty string, len(string) + 1 is returned by default.