I was making a quiz for a class that I am TA-ing and I wanted to know what the output of what "hello".count("")
would be. Turns out, the count of an empty string is always the length of the string + 1. To me, it would make sense that the count is the length (or infinity I guess), but why the length + 1?
Asked
Active
Viewed 221 times
1
2 Answers
2
According to this other question Why are str.count('') and len(str) giving different output?, it appears that a python string consists of an empty string, an empty between each character, and an empty afterwards. So hi
is really ''h''i''

JNichols
- 66
- 6
-1
The count()
method returns the number of occurrences of a substring in the given string. The empty string, when used as a substring, is an edge case.
As you can see from the first example below, the empty string is considered to be a substring of itself. Therefore, if the empty string is a substring of every character, and of the empty string, then count should return the number of characters plus one. I suppose larger substrings were not considered to be valid, otherwise a higher value would be returned.
$ python
Python 3.8.5 (default, Jan 27 2021, 15:41:15)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> "".count("")
1
>>> "Hello wonderful world".count("")
22
>>> "Hello wonderful world".count("e")
2
>>> "Hello wonderful world".count("o")
3
>>> "Hello wonderful world".count("oink")
0

Mike Slinn
- 7,705
- 5
- 51
- 85
-
2that is the same observation OP stated – the question asked was a *why* is that a sensible value for that edge case, and you're leaving that unanswered! – Marcus Müller Apr 16 '21 at 18:08