0

I have a list of countries that I would like to put in an html table.

places = ['Japan','China','North Korea', 'South Korea', 'Vietnam', 'Taiwan', 'Philippines', 'Myanmar']

for now I only have this code which only put <td> and </td> at start and end of every country. I'm having difficulty on how to put <tr> and </tr> for every 3rd line or country it reads. Actually, I don't have an idea how to do it hahaha. (Note in my code I only use print just to show my desired output, I'll use write later)

for x in places:
    print('<td>' + x + '</td>')

output:

<td>Japan</td>
<td>China</td>
<td>North Korea</td>
<td>South Korea</td>
<td>Vietnam</td>
<td>Taiwan</td>
<td>Philippines</td>
<td>Myanmar</td>

desired output:

<tr>
<td>Japan</td>
<td>China</td>
<td>North Korea</td>
</tr>

<tr>
<td>South Korea</td>
<td>Vietnam</td>
<td>Taiwan</td>
</tr>

<tr>
<td>Philippines</td>
<td>Myanmar</td>
</tr>

Note: the number of list in places is not fixed. I mean sometimes it may change to something like these places = ['Japan','China'] or just places = ['Japan']

2 Answers 2

2

You can use list slicing

places = ['Japan','China','North Korea', 'South Korea', 'Vietnam', 'Taiwan', 'Philippines', 'Myanmar']

for i in range(0, len(places),3):
    row = "<tr>"
    for j in places[i:i+3]:
        row+=f"\n<td>{j}</td>"
    print(row+"\n</tr>")

Output:

<tr>
<td>Japan</td>
<td>China</td>
<td>North Korea</td>
</tr>
<tr>
<td>South Korea</td>
<td>Vietnam</td>
<td>Taiwan</td>
</tr>
<tr>
<td>Philippines</td>
<td>Myanmar</td>
</tr>
Sign up to request clarification or add additional context in comments.

1 Comment

To do it properly, you have to HTML-encode strings, otherwise you can get into problems with special characters.
1

You can also use jinja2 template engine here

Ex:

from jinja2 import Template


html_template = """{% for p in places %}
<tr>
{% for city in p %}
  <td>{{ city }}</td>
{% endfor %}
</tr>
{% endfor %}"""

places = ['Japan','China','North Korea', 'South Korea', 'Vietnam', 'Taiwan', 'Philippines', 'Myanmar']
places = [places[i: i+3] for i in range(0, len(places), 3)]
template = Template(html_template)
print(template.render(places=places))

Output:

<tr>

  <td>Japan</td>

  <td>China</td>

  <td>North Korea</td>

</tr>

<tr>

  <td>South Korea</td>

  <td>Vietnam</td>

  <td>Taiwan</td>

</tr>

<tr>

  <td>Philippines</td>

  <td>Myanmar</td>

</tr>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.