[Tutor] Comparing two lines of print

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Jun 2 14:29:25 EDT 2004

On Wed, 2 Jun 2004, Bob Heasman wrote:

> Alan Gauld wrote:
> >>When I attempt to run this script I get a syntax error:-
> >>
> >>[root at penguin bob]# ./readfile.py
> >>   File "./readfile.py", line 14
> >>     if text_file.readline() == [PORT 6 (PTCPACTOR) - 19 - UA6ADV-0]
> >>                                      ^
> >>SyntaxError: invalid syntax
> >
> >
> > You are comparing a string (from raw_input()) with a list.
> > I assume you need quotes around the [PORT....-0] stuff?
> >
> >
> Hello Alan,
> Yes I now see what is happening. When I had the quotes in it appeared to
> be ignoring two lines of code. Now I see that it IS comparing them and,
> due to the quotes, it says they are not the same.

Hi Bob,

Let's elaborate on this point a little.  When we say things like:

>>> msg = "hello world"

then the 'msg' itself won't have quotes embedded in it.  The value of the
name 'msg' is the string

    hello world

(The indentation, too, isn't part of the string, but is there just to set
it off from my explanation.)

The quotes allow us to tell Python that we're defining a "string literal".
This is a detail that matters, since the following:

>>> "hello" + " world" == "hello world"

is True, even though we can see four quote characters on the left side,
and only two quote characters on the right side.  And so is:

>>> 'hello world' == "hello world"

The quote characters are really for us, to tell the Python system: "Ok,
I'm defining a string constant.  Anything between the quote characters
should be treated as a string."

We could live without using string literals, since we can construct string
values based on the individual ASCII character values:

>>> chr(104) + chr(101) + chr(108) + chr(108) + chr(111) + chr(32) + \
...     chr(119) + chr(111) + chr(114) + chr(108) + chr(100)
'hello world'

but this is just... well... painful.  *grin*

Anyway, getting back to the subject: the quote characters themselves are
probably not the reason why the expression:

    text_file.readline() == "[PORT 6 (PTCPACTOR) - 19 - UA6ADV-0]"

is evaluating to False.  Instead, it's better to assume, for the moment,
that the value of text_file.readline() isn't exactly equal to that other
string value, and to find out why.  So keep the quotes there:  removing
them, just because the comparison was failing, was a wrong turn.  *grin*

Michael Janssen's suggestion to make sure that the "newline" character
'\n' isn't interfering with the comparison, on the other hand, sounds

Hope this helps!

More information about the Tutor mailing list