\"ABCDE\" has no empty character. But when I type
\"\" in \"ABCDE\"
Python interpreter returns True
.
Why?
is there
For people with background in languages where string objects represented as arrays of characters it may be surprising, but if we try to follow such approach like
string = 'ABCDE'
characters_list = list(string)
then
'' in characters_list
will be False
statement.
Empty string probably came from mathematics, where it is a neutral element for binary operation of string concatenation, i. e. for every string a
a + empty_string == empty_string + a == a
where +
is a string concatenation symbol. Then "substringing" can be defined as follows:
for every strings a
, b
we say a
is substring of b
iff exists strings c
, d
such that
b == c + a + d
Let's denote a
is substring of b
as a in b
.
With these definitions of empty string and substringing relation can be proved lemma
empty_string
is a substring of any string a
:
a == (definition of empty_string) == empty_string + a ==
== (definition of empty_string) == empty_string + empty_string + a
then if we define c = empty_string
and d = a
:
a == c + empty_string + d
and by definition empty_string in a
.
Here's a qualitative way to think about it. Consider the following:
>>> "foo"[0:0]
''
Doing a zero-width slice of a string returns ''
. So, if you can get ''
out of a string, it must be in the string and therefore '' in "foo"
must be true.