4

I want to make the code below to get formatted as HTML. However I'm having problem formatting it as HTML.

cur.execute("SELECT Statement")

rows = cur.fetchall()

    html = """\
    <table border='1'>
    <tr><th>Date</th><th>DPC</th><th>TOTAL</th><th>Success</th></tr>
    <tr>
    for row in rows:
        for col in row:
            print "<td>"
            print "%s".replace(" ", "") % col
            print "</td>"
            print "</tr>"
        </table> 
    """

My goal is to make it html output, however I don't know how to make the for loop output as formatted html.

2 Answers 2

7

I hope this is the code you're looking for:

html = """\
    <table border='1'>
    <tr><th>Date</th><th>DPC</th><th>TOTAL</th><th>Success</th></tr>"""
for row in rows:
    html = html + "<tr>"
    for col in row:
        html = html + "<td>" + col.replace(" ", "") + "</td>"
    html = html + "</tr>"
html = html + "</table>"

Every HTML tag is appended to the html string variable. You can write the contents of this html variable to file:

f = open('temp.html','w')
f.write(html)
f.close()
Sign up to request clarification or add additional context in comments.

2 Comments

html = html + "<td>" + col.replace(" ", "") + "</td>" AttributeError: 'long' object has no attribute 'replace' i'm getting this error. i think there is no replace
Long object huh? If what you're saying is right then instead of col.replace(...) rewrite that word as str(col).
4

For that case you'll need to use jinja2.

<!DOCTYPE html>
<html lang="en">
<head>{{ title }}</head>
<body>
  <table border='1'>
    <thead>
     <tr>
       <th>Date</th>
       <th>DPC</th>
       <th>TOTAL</th>
       <th>Success</th>
     </tr>
    </thead>
    <tbody>
       <tr>
          {% for col in rows %}
              <td>{{ col }}</td>
          {% endfor %}
       </tr>
    </tbody>
</body>
</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.