【问题标题】:python HTML for loop formatpython HTML for循环格式
【发布时间】:2022-05-08 01:57:51
【问题描述】:

我想让下面的代码格式化为 HTML。但是我在将其格式化为 HTML 时遇到问题。

cur.execute("SELECT Statement")

rows = cur.fetchall()

    html = """\
    <table border='1'>
    <tr><th>Date</th><th>DPC</th><th>TOTAL</th><th>Success</th></tr>
    <tr>
    for row in rows:
        for col in row:
            print "<td>"
            print "%s".replace(" ", "") % col
            print "</td>"
            print "</tr>"
        </table> 
    """

我的目标是使其成为 html 输出,但是我不知道如何将 for 循环输出为格式化的 html。

【问题讨论】:

    标签: html python-2.7


    【解决方案1】:

    我希望这是您正在寻找的代码:

    html = """\
        <table border='1'>
        <tr><th>Date</th><th>DPC</th><th>TOTAL</th><th>Success</th></tr>"""
    for row in rows:
        html = html + "<tr>"
        for col in row:
            html = html + "<td>" + col.replace(" ", "") + "</td>"
        html = html + "</tr>"
    html = html + "</table>"
    

    每个 HTML 标记都附加到 html 字符串变量。您可以将这个html 变量的内容写入文件:

    f = open('temp.html','w')
    f.write(html)
    f.close()
    

    【讨论】:

    • html = html + "" + col.replace(" ", "") + "" AttributeError: 'long' object has no attribute 'replace' 我是收到此错误。我认为没有替代品
    • 长对象吧?如果你说的是对的,那么不要将col.replace(...) 改写为str(col)
    【解决方案2】:

    对于这种情况,您需要使用 jinja2。

    <!DOCTYPE html>
    <html lang="en">
    <head>{{ title }}</head>
    <body>
      <table border='1'>
        <thead>
         <tr>
           <th>Date</th>
           <th>DPC</th>
           <th>TOTAL</th>
           <th>Success</th>
         </tr>
        </thead>
        <tbody>
           <tr>
              {% for col in rows %}
                  <td>{{ col }}</td>
              {% endfor %}
           </tr>
        </tbody>
    </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 2021-07-25
      • 1970-01-01
      • 1970-01-01
      • 2012-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多