3

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
  • 2
    Strange that this question was asked by a different user: stackoverflow.com/questions/3214926/python-print-in-rows Commented Jul 9, 2010 at 17:57
  • Yup were on the same team trying to get this website up and running Commented Jul 9, 2010 at 18:01
  • The code posted won't work, since the list created is 'random_list', but the list parsed is 'food_list'. Commented Jul 9, 2010 at 18:17

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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>'

2 Comments

What are the benefits of using join over concatenation? Seems rather silly (no offense, I'm genuinely curious).
@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).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.