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

Masklinn masklinn at masklinn.net
Wed Jul 18 19:58:17 CEST 2012


On 2012-07-18, at 19:43 , Masklinn wrote:
> On 2012-07-18, at 19:30 , anatoly techtonik 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?
> 
> Erm… yes? `in` would not be very useful for strings if you could only use
> it to check for a single character would it?

in fact, things used to work that way in older Python, this was
specifically changed to the current behavior *as noted in the documentation*:

> When s is a string or Unicode string object the in and not in
> operations act like a substring test. In Python versions before 2.3, x
> had to be a string of length 1. In Python 2.3 and beyond, x may be a
> string of any length.

A Python string, you may want to note, is a string. Not a sequence of
characters. The first item of a 1-character string is itself, all basic
(step-less) slices of a string are contained in itself (including itself
and the empty string), you can infinitely get the first item of a
non-empty string, and I'm sure I'm missing plenty.


More information about the Python-ideas mailing list