[Tutor] trouble with function-- trying to check differences btwn 2 strings
John Fouhy
john at fouhy.net
Tue Mar 6 23:44:08 CET 2007
On 07/03/07, David Perlman <dperlman at wisc.edu> wrote:
> On Mar 6, 2007, at 11:03 AM, Alan Gauld wrote:
> > It's doing the latter and since anything that's not 'empty' in
> > Python evaluates to true we wind up checking whether
> > true == (item in word)
> >
> > So if the item is in word we get true == true which is true.
> Sorry, but this still doesn't make sense to me.
Hmm, ok, colour me confused as well. Let's try creating the
conditions in the original poster's code.
Python 2.4.3 (#1, Mar 30 2006, 11:02:16)
[GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> item = 'b'
>>> word2 = 'bees'
The test is "item == item in word2".
>>> item == item in word2
True
Let's see how we can group this:
>>> item == (item in word2)
False
That makes sense. It's not True though.
>>> (item == item) in word2
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'in <string>' requires string as left operand
That also makes sense..
>>> if (item == item) in word2:
... print 'foo'
...
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'in <string>' requires string as left operand
>>> if item == item in word2:
... print 'foo'
...
foo
So ... hmm. Not sure what's going on here.
I also notice that, according to
http://docs.python.org/ref/summary.html, '==' has higher precedence
than 'in'. Which means that
'foo == bar in baz' should group as '(foo == bar) in baz'. But Luke's
example contradicts this:
>>> lst = [1,2,3,4]
>>> 555 == 555 in lst
False
>>> (555 == 555) in lst
True
>>> 1 == 1 in lst
True
(this works because 1 == True)
--
John.
More information about the Tutor
mailing list