problem generating rows in table

Mike Meyer mwm at mired.org
Tue Nov 8 06:18:50 CET 2005


s99999999s2003 at yahoo.com writes:
> hi
> i wish to generate a table using cgi
> toprint = [('nickname', 'justme', 'someplace')]
> print '''<table  border="1">
>                 <tr>
>                 <td>User</td>
>                 <td>Name</td>
>                 <td>Address</td>
>                 </tr>
>        <tr>
>       '''
>
> for i in range(0,len(toprint)-1):
>   for j in range(0,len(toprint[0])-1):
>     print "<td> %s </td>" % toprint[i][j]
>
> print '''</tr>
> </table>'''
>
> but it only prints out a table with "User | Name | address"
> it didn't print out the values of toprint
>
> is there mistake in code? please advise 

You're not calling range right. It's designed for dealing with lists,
so range(n) returns [0, ..., n - 1], and range(to, bottom) returns
[top, ..., bottom - 1]. len(toprint) is 1, so len(toprint) - 1 is 0,
so you're calling range(0, 0), which is an empty list. So you make no
passes through the outer loop. Those two calls to range should be
range(len(toprint)) and range(len(toprint[i])) (n.b.: i, not 0, is
the index).

Of course, for is for walking elements of a list. You don't need the
indices at all. The pythonic way to write this loop would be:

for tup in toprint:
    for el in tup:
        print "<td> %s </td>" % el

But your HTML is also broken. The loop as you have it will print one
row containing all the elements in toprint concatenated together. You
need to put each tuple in toprint into a separate row, like so:

for tup in toprint:
    print "<tr>"
    for el in tup:
        print "<td> %s </td>" % el
    print "</tr>"
print "</table>"

and of course leave out the trailing <tr> in the print statement that
precedes the loop.

         <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list