[Tutor] != -1: versus == 1

Lie Ryan lie.1296 at gmail.com
Fri Jul 17 19:42:28 CEST 2009


pedro wrote:
> Hi I have been trying to understand a python script and I keep coming
> across this kind of structure
> that says "If it is not equal to negative one"
> 
> ################################
> for line in theLines:
>    if line.find("Source Height") != -1:
> #etc...
> ###################################
> 
> Is there some special reason for this. Why not just write "If it is
> equal to one"
> 
> #########################
> for line in theLines:
>    if line.find("Source Height") == 1:
> #etc...
> ###################################

Nothing special, it just they have different meaning (and different
results). The former (!= -1) tests whether the str.find() method does
not fail finding "Source Height" (i.e. str.find() succeeds finding
"Source Height") while the latter tests whether "Source Height" is in
the second position in the string.

But if it were me, I'd write the former (!= -1) with 'in' operator:

for line in theLines:
    if "Source Height" in line:
        ...



More information about the Tutor mailing list