problem generating rows in table
Steve Holden
steve at holdenweb.com
Mon Nov 7 23:59:20 EST 2005
s99999999s2003 at yahoo.com wrote:
> 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
> thanks
>
Your problem is in trying to emulate the C looping structures rather
than using those native to Python: the toprint list has only one
element, and the range computations suffer from out-by-one errors,
leaving you iterating zero times!
It might be simpler to build the output as follows:
print '''<table border="1">
<tr>
<td>User</td>
<td>Name</td>
<td>Address</td>
</tr>
'''
rows = []
for row in toprint:
print " <tr>"
for cell in row:
print " <td>%s</td>" % cell
print " </tr>"
print "</table>"
Of course you should really be ensuring that the cell contents correctly
escape any special characters in the cell content (such as turning "<"
into "<") but I'll leave that as an exercise.
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/
More information about the Python-list
mailing list