tags:

views:

43

answers:

2

I'm using the code below to print out rows containing 4 columns. How would I append each value in the list to a HTML table that also contains rows with four columns?

   random_list = ['car', 'plane', 'van', 'boat', 'ship', 'jet','shuttle']
    for i in xrange(0, len(food_list), 4):
        print '\t'.join(food_list[i:i+4])
+3  A: 

With some minor modification...

food_list = ['car', 'plane', 'van', 'boat', 'ship', 'jet','shuttle']
for i in xrange(0, len(food_list), 4):
    print '<tr><td>' + '</td><td>'.join(food_list[i:i+4]) + '</td></tr>'

This basically changes the delimiter to not be tab, but the table elements. Also, puts the open row and close row at the beginning and end.

orangeoctopus
+1  A: 

Slight variation on orangeoctopus' answer, using another join, rather than concatenation:

random_list = ['car', 'plane', 'van', 'boat', 'ship', 'jet','shuttle']
print "<table>"
for i in xrange(0, len(random_list), 4):
    print ''.join(['<tr><td>','</td><td>'.join(random_list[i:i+4]),'</td></tr>'])
print '</table>'
GreenMatt
What are the benefits of using join over concatenation? Seems rather silly (no offense, I'm genuinely curious).
orangeoctopus
@orangeoctopus: When gluing together strings, it seems join() is considered more pythonic than concatenation. Also, when the number of items being glued gets large, join() runs faster. However, for a small number of items, I think concatenation is fine and is what I usually do (habit from other languages).
GreenMatt