Boolean confusion

Antoon Pardon apardon at forel.vub.ac.be
Wed May 9 08:47:33 EDT 2007


On 2007-05-09, Greg Corradini <gregcorradini at gmail.com> wrote:
>
> Hello all,
> I'm having trouble understanding why the following code evaluates as it
> does:
>
>>>> string.find('0200000914A','.') and len('0200000914A') > 10
> True
>>>> len('0200000914A') > 10 and string.find('0200000914A','.')
> -1
>
> In the 2.4 Python Reference Manual, I get the following explanation for the
> 'and' operator in 5.10 Boolean operations:
> " The expression x and y first evaluates x; if x is false, its value is
> returned; otherwise, y is evaluated and the resulting value is returned."
>
> Based on what is said above, shouldn't my first expression (
> string.find('0200000914A','.') and len('0200000914A') > 10) evaluate to
> false b/c my 'x' is false? And shouldn't the second expression evaluate to
> True?

The find method doesn't return a boolean, but returns the index where
the substring was found with -1 indicating it wasn't found. If you just
want to check wether one string is a substring of an other, use the in
operator.

>>> '.' in '0200000914A' and len('0200000914A') > 10
False
>>> len('0200000914A') > 10 and  '.' in '0200000914A'
False

-- 
Antoon Pardon



More information about the Python-list mailing list