Why empty string is on every string?

For example:

>>> s = 'python'
>>> s.index('')
0
>>> s.index('p')
0

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x