wbruntra
wbruntra

Reputation: 1071

Strategies for HTML processing in Python: Ambiguous Characters

I am very new to HTML, trying to write a "Signup page" for the Udacity CS253 course. I have my entire page entered as a string in Python, then I am using Python on the raw HTML text and performing string substitution. This leads to problems with ambiguous characters.

The problematic code looks like this:

    page = """
      <head>
        <style type="text/css">
          .label {text-align: right}
          .error {color: red}
        </style>

      </head>
              <td>
                <input type="text" name="username" value="{username}">
              </td>
    """
print page.format(username='JoeBlow')

Which, naturally, gives the error

> Traceback (most recent call last):   File "<pyshell#0>", line 1, in
> <module>
>     page.format() KeyError: 'text-align'

So Python interprets the curly braces in the header of my page as indicating a string substitution, which is not what I want.

Of course, I could solve this case by making the head and body separate strings, since there are no curly braces in the body that don't refer to actual (Python) string substitutions.

But I suppose that a more complex page might have curly braces in the body, making this not a very useful strategy in most cases.

More generally, as I write more complicated pages, what strategies should I be using, when feeding raw HTML to Python for processing, to prevent Python from misunderstanding and manipulating HTML code that should remain unchanged?

Upvotes: 0

Views: 353

Answers (1)

Hetzroni
Hetzroni

Reputation: 2174

As long as you're dealing with raw html, you might as well use double curly brackets, as such:

page = """
  <head>
    <style type="text/css">
      .label {{text-align: right}}
      .error {{color: red}}
    </style>

  </head>
          <td>
            <input type="text" name="username" value="{username}">
          </td>
"""
print page.format(username='JoeBlow')

Although the best solution is to use a python library designated for html templates. You should look into Django or Tornado.

Upvotes: 0

Related Questions