Observe the following interactive session:
In [1]: s = \'emptiness\'
In [2]: s.replace(\'\', \'*\')
Out[2]: \'*e*m*p*t*i*n*e*s*s*\'
In [3]: s.count(\'\')
O
Python strings follow the principle that an empty string is a subset of every other string. Furthermore, python strings are also concatenations of byte strings, implying that a string consists of bytes sandwiched between empty strings. You can see that by the following examples:
>>>'a'.count('')
2
>>>'aa'.count('')
3
>>>'string'.count('')
7
So 'a'
must be ''+'a'+''
, and 'aa'
must be ''+'a'+''+'a'+''
.
When you check 'a'.startswith('')
, it sees that the string 'a' technically starts with an empty string. Same for 'a'.endswith('')
. However when you check 'a'.startswith('a')
, it ignores the empty string and looks at the first byte.