Count of "" is length of string + 1?

Viewed 79

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?

2 Answers

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
Related