[Tutor] Printing output from Python program to HTML

Brett Ritter swiftone at swiftone.org
Tue May 10 14:31:55 CEST 2011


On Tue, May 10, 2011 at 8:16 AM, Spyros Charonis <s.charonis at gmail.com> wrote:
>           newline = line.replace(item, "<p> <font color = "red"> item
...
> The Python compiler complains on the line I try to change the font color,
> saying "invalid syntax".

Your issue here is not importing libraries, but your quotations.  When
you get to "red", it takes that first double quote as ENDING the
string of HTML that starts with "<p>.  It doesn't know that you're
putting quotes inside your string, as the only way it knows when a
string ends is when it reaches the quoting character that matches the
beginning.

The easiest solution is to use 'red' (using single quotes) as HTML accepts both.

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

As alternative you could use a different quoting for your string (note
the single quotes on the outside):

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

Alternatively you could escape your string.  This tells Python that
the quotes are NOT ending the string, and the backslashes will not
appear in the resulting output:

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

Note that the first option works because HTML accepts single or double
quotes for it's attribute values.  The second option works because
single and double quotes for strings work the saem in Python (this is
not true of all languages).  The third option is pretty standard
across languages, but can be annoying because it becomes harder to
cut-and-paste strings to/from other places (for example, template
files, raw HTML files, etc).

Hope that helps!
-- 
Brett Ritter / SwiftOne
swiftone at swiftone.org


More information about the Tutor mailing list