'in' operator

Tim Peters tim.one at home.com
Fri Feb 16 22:50:19 EST 2001


[Walter Moreira]
> Why the following test raise an error?
>
>   >>> '' in 'yY'
>   Traceback (most recent call last):
>     File "<stdin>", line 1, in ?
>   TypeError: 'in <string>' requires character as left operand

   elt in sequence

tests whether elt is a member of sequence.  The elements of strings are
characters.  Testing whether anything other than a character is an element
of a string is simply a TypeError:  it's a highly suspicious question
because only a character *could* be an element of a string.  And an empty
string is not a character.

> I would expect it to give 0, false. With the actual behavior, one
> must write
>
>   resp = raw_input('Yes or no: ')
>   if resp and resp in 'yY':
>       ....
> to consider the case when the user just press `return',

But fails to consider the case where the user enters more than one character
before pressing 'return' (try it:  it still blows up).  You're missing this
one:

    if resp in ("y", "Y"):

*Now* you're asking whether a string is in a sequence of strings, which
always makes sense and is much closer to your intent.  Even better:

    if resp.lower()[:1] == "y":

After all, if you're asking the user "Yes or no", it's impolite to take
"Yes" as meaning "no" <0.3 wink>.

> Is this a planned behavior?

Yes.  Python is trying to guide you toward writing code you won't regret.
TypeErrors are signs that you're doing something so questionable that Python
would rather refuse to do anything than guess your intent.

   x = 6 + "42"

"642" or 48?  Python refuses to guess -- so that's a TypeError too.

it's-for-your-own-good<wink>-ly y'rs  - tim





More information about the Python-list mailing list