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

Bill Campbell bill at celestial.net
Fri Jul 17 18:37:00 CEST 2009


On Fri, Jul 17, 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"

The string find method returns -1 if the string is not found,
otherwise it returns the 0-based index into the string matching
the argument to find.  The test above will return -1 if ``Source
Heigtht'' is not in line, and one generally wants to have the
test return True if there is something to do.  The alternative
would be to say ``if not line.find('Source Height') == -1: ...''

Bill
-- 
INTERNET:   bill at celestial.com  Bill Campbell; Celestial Software LLC
URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
Voice:          (206) 236-1676  Mercer Island, WA 98040-0820
Fax:            (206) 232-9186  Skype: jwccsllc (206) 855-5792

Windows is a computer virus with a user interface!!


More information about the Tutor mailing list