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()
在打开的文件上。