Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why empty string is on every string? [duplicate]

Tags:

python

string

For example:

>>> s = 'python'
>>> s.index('')
0
>>> s.index('p')
0
like image 453
fotis Avatar asked Mar 05 '11 20:03

fotis


People also ask

Is the empty string in every string?

The empty string is the special case where the sequence has length zero, so there are no symbols in the string. There is only one empty string, because two strings are only different if they have different lengths or a different sequence of symbols.

Is the empty string a subset of all strings?

The entire string is usually considered a substring of itself. The empty string is always a substring of any string, even the empty string. There are two useful operations with substrings. You can ask if some string is a substring of another.

Is an empty string in every string python?

Of course every substring of length zero of any string is equal to the empty string.


2 Answers

You can see "python" as "the empty string, followed by a p, followed by fifteen more empty strings, followed by a y, followed by forty-two empty strings, ...".

Point being, empty strings don't take any space, so there's no reason why it should not be there.

The index method could be specified like this:

s.index(t) returns a value i such that s[i : i+len(t)] is equal to t

If you substitute the empty string for t, this reads: "returns a value i such that s[i:i] is equal to """. And indeed, the value 0 is a correct return value according to this specification.

like image 163
Thomas Avatar answered Oct 24 '22 02:10

Thomas


This is because the substring of length 0 starting at index 0 in 'python' is equal to the empty string:

>>> s[0:0]
''

Of course every substring of length zero of any string is equal to the empty string.

like image 42
Sven Marnach Avatar answered Oct 24 '22 03:10

Sven Marnach