Possible Duplicate:
Why empty string is on every string?
I wonder why Python returns True whenever I check if the empty string is in a string, and why its index is zero.
For instance:
'' in ''=> true''.index('')=> 0'' in 'notEmpty'=> true'notEmpty'.index('')=> 0
I noticed it when I was writing a ROT13 function, and testing it I found that when I call it on an empty string, it returns 'n' ('n' is index13 in the alphabet).
A string
Sis a substring of the stringTif and only if there exist an indexisuch thatT[i:i+len(S)] == S. WhenSis the empty string you haveT[i:i] = '' = Sso all the results are correct.Also note that
T.index('')returns 0 becauseindexreturns the first index in which the substring appears, andT[0:0] = ''so that’s definitely the correct result.In summary, the empty string is a substring of every string, and all those results are a direct consequence of this.
Also note that this is peculiar to strings, because strings are sequences of characters, which are themselves strings of length one. For other kind of sequences(such as
lists ortuples) you do not get the same results:That’s because
listandtupleonly check for members, and not for sub-lists or sub-tuples, because their elements can be of arbitrary type.Imagine the case
((1,2),1,2).index((1,2)). Shouldindexcheck for “sub-tuples”(and thus return 1), for members(and thus return 0) or do some ugly mixture(e.g. first check for sub-tuples and then for members)? In python it was decided to search for members only, since it is simpler and it’s usually what you want. Checking for sub-tuples only would give really odd results in the general case and doing “mixtures” would often yield unpredictable results.