格式字符串中有两个错误。正如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意味着您同时使用两种语言编程。这种双重思考让一些有经验的程序员大吃一惊,但我们其他人更乐于将关注点分离开来,一次只处理一种语言。而不是
%
-字符串,考虑使用
lxml
来构造你的html。有更多的学习曲线(由优秀的
tutorial
)但是您的代码将更易于编写和维护,并且
LXML
将确保HTML没有语法错误。