[Tutor] Printing output from Python program to HTML

Steven D'Aprano steve at pearwood.info
Tue May 10 14:31:53 CEST 2011


Spyros Charonis wrote:

>           newline = line.replace(item, "<p> <font color = "red"> item
> </font> </p>") # compiler complains here about the word "red"

You should pay attention when Python tells you where there is an error. 
If it says there is a syntax error, then your syntax is invalid and you 
need to fix it.

> The Python compiler complains on the line I try to change the font color,
> saying "invalid syntax".  Perhaps I
> need to import the cgi module to make this a full CGI program?

And how will that fix your syntax error?


The offending line of code looks like this:

newline = line.replace(item,
     "<p> <font color = "red"> item> </font> </p>")

split into two lines because my mail program doesn't like long lines. 
The important part is the replacement string:

"<p> <font color = "red"> item> </font> </p>"

Only it's not a string, the syntax is broken. Each quote " starts and 
then stops a string:

OPEN QUOTE ... END QUOTE red OPEN QUOTE ... CLOSE QUOTE

This is invalid syntax. You can't have the word red sitting outside of a 
string like that.

How to fix it? There are two ways. You can escape the inner quotes like 
this:


"<p> <font color = \"red\"> item> </font> </p>"


That will stop Python using the escaped quotes \" as string delimiters, 
and use them as ordinary characters instead.

Or, you can take advantage of the fact that Python has two different 
string delimiters, double and single quotes, and you can safely nest 
each inside the other:


'<p> <font color = "red"> item> </font> </p>'




-- 
Steven



More information about the Tutor mailing list