3 回答

TA贡献1828条经验 获得超4个赞
fstrings 是现在很酷的孩子们使用的东西。
titles = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
html_text = f"""<html>
<head>
<style type="text/css">
table {{ border-collapse: collapse;}}
td {{ text-align: center; border: 5px solid #ff0000; border-style: dashed; font-size: 30px; }}
</style>
</head>
<body>
<table width="100%" height="100%" border="5px">
<tr>
<td>{titles[0]}</td>
</tr>
<tr>
<td>{titles[1]}</td>
</tr>
<tr>
<td>{titles[2]}</td>
</tr>
<tr>
<td>{titles[3]}</td>
</tr>
<tr>
<td>{titles[4]}</td>
</tr>
</table>
</body>
</html>"""
with open('temp.html', 'w') as f:
f.write(html_text)
您将变量放入{}文本中,并且您的样式必须使用 double 进行转义{{}}。试试看。
此外,pythonic 写入文件的方式是使用上下文管理器。它处理关闭而不需要.close()打开的文件。

TA贡献1840条经验 获得超5个赞
您可以使用一些模板引擎将逻辑混合到模板中。
jinja2示例:
安装 pip install jinja2
2 那么代码将是:
html_text = """<html>
<head>...</head>
<body>
<table width="100%" height="100%" border="5px">
{% for title in titles %}
<tr>
<td>{{title}}</td>
</tr>
{% endfor %}
</table>
</body>
</html>"""
from jinja2 import Template
titles = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
my_templ = Template(html_text)
with open('temp.html', 'w') as f:
f.write(my_templ.render(titles=titles))
请注意,处理可变长度列表是灵活的。Web 框架中使用了模板引擎。

TA贡献1993条经验 获得超5个赞
您的格式字符串中有两个错误。第一个,正如 U9-Forward 所指出的,在这里:
</html> % (titles[0], titles[1], titles[2], titles[3], titles[4])"""
这%是一个插值运算符,因此它需要在字符串和数据之间进行:
</html>""" % (titles[0], titles[1], titles[2], titles[3], titles[4])
第二个错误,只有在你修复了那个错误后才明显,在这里:
<table width="100%" height="100%" border="5px">
当您使用%运算符时,该字符%变得特殊,因此%s符合您的预期。但是当发生这种情况时,这"100%"是不合法的,因为正如错误消息告诉您的那样,它会将unsupported format character '"' (0x22) at index 237. 通过将光标放在字符串的开头并按向右箭头 237 次,您可以在一分钟内为自己找到这一点。
在这种情况下,%您要留下的%必须加倍:
<table width="100%%" height="100%%" border="5px">
那给
html_text = '''<html>
<head>
<style type="text/css">
table { border-collapse: collapse;}
td { text-align: center; border: 5px solid #ff0000; border-style: dashed; font-size: 30px; }
</style>
</head>
<body>
<table width="100%%" height="100%%" border="5px">
<tr>
<td>%s</td>
</tr>
<tr>
<td>%s</td>
</tr>
<tr>
<td>%s</td>
</tr>
<tr>
<td>%s</td>
</tr>
<tr>
<td>%s</td>
</tr>
</table>
</body>
</html>''' % (titles[0], titles[1], titles[2], titles[3], titles[4])
但这里的基本问题是 Python%字符串是一种格式化迷你语言,而 HTML 是一种格式化语言,因此像这样构造 HTML 意味着您同时使用两种语言进行编程。这涉及的双重思考让一些有经验的程序员感到兴奋,但我们其他人更乐意将我们的关注点分开并一次处理一种语言。而不是%-strings,考虑使用lxml来构造你的 HTML。有更多的学习曲线(通过优秀的教程缓解),但您的代码将更易于编写和维护,并lxml确保您的 HTML 没有语法错误。
添加回答
举报