newbie question: if var1 == var2:

Mel mwilson at the-wire.com
Fri Nov 28 23:02:11 EST 2008


joemacbusiness at gmail.com wrote:

> Hi All,
> 
> I dont understand why the following code cannot find the
> variable "tree".  It is very simple but I could not find the answer
> to this on the Python Tutorials.  Here is the code, input and runtime:
> 
> #!/usr/bin/python
> 
> fname = open("test43.in")
> var = 'tree'
> 
> for item in fname:
>     print "item: ", item,
>     if item == var:
>         print "found tree: ", item,

Because each item from the file has a newline character at the end.
Notice how your print statements end with ','.  This suppresses the print
statement's newline, and the one on the end of the item makes the printout
look normal.
You could try

for item in fname:
    item = item.strip()
# ... etc.

        Mel.




More information about the Python-list mailing list