[Tutor] trouble with function-- trying to check differences btwn 2 strings
David Perlman
dperlman at wisc.edu
Tue Mar 6 23:41:16 CET 2007
On Mar 6, 2007, at 4:28 PM, wesley chun wrote:
>> >>> x=('i' in 'i')
>> >>> x
>> True
>> >>> y='i'
>> >>> x==y
>> False
>
> you're right when you talk about "casting" altho that's not what
> python does. it merely performs an object value comparison when you
> use '=='. for example, change your code above to:
>
>>>> True == 'i' # because this is what you're really doing with x==y
> False
>
> so the reason why you get a false is that those 2 values *are*
> different from each other, even if their boolean truthfulness may be
> the same:
>
>>>> bool(True) == bool('i')
> True
>
> how's *that* for casting? :-)
>
> just remember that the interpreter compares *values* and not boolean
> truthfulness, and you'll be ok. if you really want the latter, then
> use bool().
>
> hope this helps!
> -- wesley
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?
--
-dave----------------------------------------------------------------
Science arose from poetry... when times change the two can meet again
on a higher level as friends. -Göthe
More information about the Tutor
mailing list