[Tutor] trouble with function-- trying to check differences btwn 2 strings

Kent Johnson kent37 at tds.net
Wed Mar 7 02:13:41 CET 2007


David Perlman wrote:
> This helps convince me that I still don't understand why the original  
> code snippet worked at all.  :)
> 
> These code examples make perfect sense.  This one doesn't, and  
> appears to be an inconsistency:
> 
>  >>> word2 = 'hello'
>  >>> item = 'e'
>  >>> item in word2
> True
>  >>> item == item in word2
> True
>  >>> (item == item) in word2
> Traceback (most recent call last):
>    File "<stdin>", line 1, in ?
> TypeError: 'in <string>' requires string as left operand
>  >>> item in word2
> True
>  >>> item == True
> False
>  >>> item == (item in word2)
> False
> 
> Notice that forcing the precedence of "in" and "==" using parentheses  
> gives either False or an error, but without parentheses, it's True.   
> So what's going on?

'==' and 'in' are both comparison operators and they have equal 
precedence. Python semantics for comparison operators have a wrinkle 
that usually makes sense but in this case is confusing.

In general, if op1 and op2 are comparison operators,
   a op1 b op2 c
means the same as
   a op1 b and b op2 c

This is handy in the case, for example, of
   a < b < c
which has its conventional meaning of
   a < b and b < c

but for the current question
   item == item in word
this is the same as
   item == item and item in word
which is not what you would expect.

http://docs.python.org/ref/comparisons.html

Kent


More information about the Tutor mailing list