Adrian Smith wrote:
>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):
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>