Unexpected empty strings within Python strings

后端 未结 1 1723
轮回少年
轮回少年 2021-01-13 01:36

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         


        
1条回答
  •  长发绾君心
    2021-01-13 02:08

    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.

    0 讨论(0)
提交回复
热议问题