HTML Tables

A

Amie

Afternoon all.

Just want to know how to create html tables using a for loop.
I need to display 34 html tables, so I figured a for loop will do.
Please show me an example of how to do that.
Also how do I display the results of an sql query onto the html
tables?

Thanks in advance
 
A

Adrian Smith

Afternoon all.

Just want to know how to create html tables using a for loop.
I need to display 34 html tables, so I figured a for loop will do.
Please show me an example of how to do that.

for i in range(33):
print "<table border>"
for j in range(numberofrows-1):
print "<tr><td>stuff</td><td>stuff</td><td>stuff</td></tr>"
print "</table>"

Or something like that. You could have for loops for the individual
rows, too.
 
G

Gabriel Genellina

for i in range(33):
print "<table border>"
for j in range(numberofrows-1):
print "<tr><td>stuff</td><td>stuff</td><td>stuff</td></tr>"
print "</table>"

Or something like that. You could have for loops for the individual
rows, too.

This can be done, but easily becomes unmaintainable.
I'd use a template engine - or at least a library for generating HTML. See this recent thread:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/950811516b29fcc/
 
F

Fredrik Lundh

Adrian said:
for i in range(33):

range(33) returns 33 numbers, not 34 (the upper bound is not inclusive).
print "<table border>"
for j in range(numberofrows-1):

This is also off by one.
print "<tr><td>stuff</td><td>stuff</td><td>stuff</td></tr>"
print "</table>"

One extra tip: if you're printing arbitrary strings, you need to encode
them (that is, map &<> to HTML entities, and perhaps also deal with
non-ASCII characters). simple ascii-only version:

from cgi import escape

print "<tr><td>", escape("stuff"), </td><td>" # etc

(the above inserts extra spaces around the cell contents, but browsers
don't care about those)

The "escape" function from the cgi module only works for (ascii)
strings; to be able to escape/encode arbitrary data, you'll need a
better escape function, e.g. something like:

import cgi

def escape(text):
if isinstance(text, unicode):
return cgi.escape(text).encode("utf-8")
elif not isinstance(text, str):
text = str(text)
return cgi.escape(text)

The above escapes Unicode strings and encodes them as UTF-8; 8-bit
strings are escaped as is, and other objects are converted to strings
before being escaped.

Tweak as necessary.

</F>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top