[Python-ideas] '' in 'abc' == True

Lefavor, Matthew (GSFC-582.0)[MICROTEL LLC] matthew.lefavor at nasa.gov
Wed Jul 18 19:38:31 CEST 2012


Strings have a common use case which lists do not: finding
subsequences/substrings.

Consider the following:

>>> string = 'abcdefghijklmnop'
>>> 'def' in string
True
>>> list('def') in list(string)
False

The contains operator ("in") has a different meaning than the contains
operator for a list. A list contains an object if (and only if) that
object is a single element of the list. A string contains another string
if (and only if) the other string is a substring of the first string.


Matthew Lefavor

NASA GSFC [Microtel, LLC]
Mail Code 699.0/Org Code 582.0
matthew.lefavor at nasa.gov
(301) 614-6818 (Desk)
(443) 758-4891 (Cell)





On 7/18/12 1:30 PM, "anatoly techtonik" <techtonik at gmail.com> wrote:

>I've just spotted inconsistency between string and lists handling:
>
>>>> '' in 'abc'
>True
>>>> '' in 'abc'.split()
>False
>>>> [] in ['a', 'b', 'c']
>False
>
>Why strings here behave differently than other sequence types? Is that
>by design?
>_______________________________________________
>Python-ideas mailing list
>Python-ideas at python.org
>http://mail.python.org/mailman/listinfo/python-ideas




More information about the Python-ideas mailing list