python - 迭代 CGI 文件中的列表并打印 html 中的值

标签 python html list loops cgi

我的 cgi 文件中有两个列表:

数字 = [0, 1, 2, 3]

字母 = [A、B、C、D]

如何迭代这些列表并在 html 中打印出值

理想情况下我的表格应该是这样的:

0个

1B

2C

3D

等等

这意味着表格和行必须由我的列表的长度和数量决定 list 我有。因此我还需要知道如何迭代列表并创建 当我遍历列表时,我在 html 脚本中生成了表。

到目前为止我已经这样做了:

print'''
<html>
<head>
</head>
<body> 
<center>
<table border="0" cellspacing="15">
<tr>
<td align="center" style="font-size:1.25em;">
<p class="sansserif"> <b> Number: %d </b> <br>
Letter: %s </p>
</td>
</tr>
</table>
</center>
</body>
</html>'''%(Number, Letter)

但这实际上并不是遍历列表,我只知道列表大小并且已经完成 其必要的代码。这也只是打印输出:

0

一个

在表格的单元格内

最佳答案

有两个选项

使用标准字符串格式化函数

您通过 % 创建结果内容的尝试正朝着这个方向发展。

但是,由于存在循环(输出中的行),并且 %string.format 都不支持循环,因此您必须创建此“循环内容” ” 在您的代码中,最后嵌入到结果页面中。

bigtempl = '''<html>
<head>
</head>
<body> 
    <center>
        <table border="0" cellspacing="15">
        {rows}
        </table>
    </center>
    </body>
</html>'''

rowtempl = """
<tr>
    <td align="center" style="font-size:1.25em;">
    <p class="sansserif"> <b> Number: {number:d} </b> <br>
    Letter: {letter} </p>
    </td>
</tr>
"""

numbers = [0, 1, 2, 3]
letters = ["A", "B", "C", "D"]

lst = zip(numbers, letters)

rows = [rowtempl.format(number=number, letter=letter) for number, letter in lst]
rows = "".join(rows)

wholepage = bigtempl.format(rows=rows)

print wholepage

使用高级模板库

有很多包,允许根据模板和数据结构生成内容。这些通常允许循环。

我曾经决定继续使用jinja2,对此我很满意。您的任务在 Jinja2 中如下所示:

import jinja2

templ = '''<html>
<head>
</head>
<body> 
    <center>
        <table border="0" cellspacing="15">
        {% for number, letter in lst %}
            <tr>
                <td align="center" style="font-size:1.25em;">
                <p class="sansserif"> <b> Number: {{number}} </b> <br>
                Letter: {{letter}} </p>
                </td>
            </tr>
            {% endfor %}
        </table>
    </center>
    </body>
</html>'''

numbers = [0, 1, 2, 3]
letters = ["A", "B", "C", "D"]

lst = zip(numbers, letters)

template = jinja2.Template(templ)

print template.render(lst=lst)

其他模板解决方案以非常类似的方式实现这一点。

关于python - 迭代 CGI 文件中的列表并打印 html 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23599091/

相关文章:

python - setup.py build 不起作用,但开发可以

html - Div 中的基本链接放置

java - 如何获取java html解析器中嵌套标签之间的内容?

python - xtensor 将 numpy 数组传递给具有 xt::xtensor 参数类型的函数

python - TensorFlow 模型损失的近似周期性跳跃

python - 使用 bool 数组从列表中删除项目

java - 我想通过多线程将此函数作为列表中所有值的线程执行,请指导我

Python SQLite3/从表中选择行

python - Django,在查询中使用 ANY

html - Bootstrap 4 - 响应式水平导航