Creating a HTML Table with Python

穿精又带淫゛_ 提交于 2021-01-29 08:28:03

问题


I'm stuck on creating a HTML Table for this code here. have to try to output all the dir() of list, dict, tuple, str, int, and float in a HTML table with a limit of 7 column per row. I've tried many things and is unable to produce that. I kept getting an internal server error when i try it out. I think i'm doing the tags from for the table or i'm missing something but still haven't figured it out.

#!/usr/local/bin/python3

print('Content-type: text/html\n')

d_list = [] 
d_dict = []
d_tuple = []
d_str = []
d_int = []
d_float = []

for i in dir(list):
    d_list.append(i)
for i in dir(dict):
    d_dict.append(i)
for i in dir(tuple):
    d_tuple.append(i)
for i in dir(str):    
    d_str.append(i)
for i in dir(int):
    d_int.append(i)
for i in dir(float):
    d_float.append(i)

d_list = [d_list[i:i + 7] for i in range(0, len(d_list), 7)]
d_dict = [d_dict[i:i + 7] for i in range(0, len(d_dict), 7)]
d_tuple = [d_tuple[i:i + 7] for i in range(0, len(d_tuple), 7)]
d_str = [d_str[i:i + 7] for i in range(0, len(d_str), 7)]
d_int = [d_int[i:i + 7] for i in range(0, len(d_int), 7)]
d_float = [d_float[i:i + 7] for i in range(0, len(d_float), 7)]

td_list = []
td_dict = []
td_tuple = []
td_str = []
td_int = []
td_float = []

for i in d_list:
     td_list.append(['<td>{}</td>'.format(x) for x in i])
for i in d_dict:
     td_dict.append(['<td>{}</td>'.format(x) for x in i])
for i in d_tuple:
     td_tuple.append(['<td>{}</td>'.format(x) for x in i])
for i in d_str:
     td_str.append(['<td>{}</td>'.format(x) for x in i])
for i in d_int:
     td_int.append(['<td>{}</td>'.format(x) for x in i])
for i in d_float:
     td_float.append(['<td>{}</td>'.format(x) for x in i])

<table>
for i in td_list:
     print('<tr>' + " ".join(i) + '</tr>')
</table>
<table>
for i in td_dict:
     print('<tr>' + " ".join(i) + '</tr>')
</table>
<table>
for i in td_tuple:
     print('<tr>' + " ".join(i) + '</tr>')
</table>
<table>
for i in td_str:
     print('<tr>' + " ".join(i) + '</tr>')
</table>
<table>
for i in td_int:
     print('<tr>' + " ".join(i) + '</tr>')
</table>
<table>
for i in td_float:
     print('<tr>' + " ".join(i) + '</tr>')
</table>

回答1:


Try this

#!/usr/local/bin/python3

print('Content-type: text/html\n')

table = []
table.append("<table>\n")
for obj in [list, dict, tuple, str, int, float]:
    table.append("\t<tr>\n")
    td = []
    for key in dir(obj)[:7]:
        td.append("<td>{0}</td>".format(key))
    table.append("\t\t"+"".join(td))
    table.append("\n\t</tr>\n")

table.append("</table>")

print("".join(table))


来源:https://stackoverflow.com/questions/24620442/creating-a-html-table-with-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!