在HTML中使用Python变量 / .format()
我在让“标记”显示出来这件事上遇到了很大的困难。我不知道怎么正确使用 .format()
来把标记放进字符串里。
这个变量需要放在字符串的特定位置吗?这是我第一次尝试理解这个,抱歉如果我问的问题太基础了。
我总是得到这个错误:""".format(marker) KeyError: 'font-family'
。我不太确定问题出在哪里。
marker = "AUniqueMarker"
# Create the body of the message (a plain-text and an HTML version).
text = "This is a test message.\nText and html."
html = """\
<html xmlns:v="urn:schemas-microsoft-com:vml"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:w="urn:schemas-microsoft-com:office:word"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:m="http://schemas.microsoft.com/office/2004/12/omml"
xmlns="http://www.w3.org/TR/REC-html40">
<head>
<meta http-equiv=Content-Type content="text/html; charset=windows-1252">
<meta name=ProgId content=Word.Document>
<meta name=Generator content="Microsoft Word 15">
<meta name=Originator content="Microsoft Word 15">
<link rel=File-List href="Law_files/filelist.xml">
<!--[if gte mso 9]><xml>
# (...)
-->
</style>
<!--[if gte mso 10]>
<style>
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:"Table Normal";
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-parent:"";
mso-padding-alt:0in 5.4pt 0in 5.4pt;
mso-para-margin:0in;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:10.0pt;
font-family:"Calibri","sans-serif";
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;}
</style>
<![endif]--><!--[if gte mso 9]><xml>
<o:shapedefaults v:ext="edit" spidmax="1026"/>
</xml><![endif]--><!--[if gte mso 9]><xml>
<o:shapelayout v:ext="edit">
<o:idmap v:ext="edit" data="1"/>
</o:shapelayout></xml><![endif]-->
</head>
<body lang=EN-US style='tab-interval:.5in'>
{marker}
</body>
</html>
""".format(marker=marker)
3 个回答
0
如果你不想去修改HTML代码,也不想添加额外的{}或者%,那么Python的模板字符串可能正是你需要的。我们来看一个例子:
from string import Template
t = Template('<body> $marker </body>')
t.substitute(marker='Hello World!')
'<body> Hello World! </body>'
1
你必须把字符串中的 {
和 }
各写两次,不然 format
会试图把大括号里的内容当成特殊指令来处理。
html = """\
your html code
""".replace("{", "{{").replace("}", "}}").format(marker=marker)
更新:replace
会把 {marker}
变成 {{marker}}
,这样就不会被 format
解释了...
5
你需要对字符串中其他的大括号({
和 }
)进行转义处理,否则字符串会被 format
错误地理解。
为了转义这些字符,你需要重复它们。在你调用 format
的字符串中,把这一行
{mso-style-name:"Table Normal";
改成
{{mso-style-name:"Table Normal";
同样的处理也适用于闭合的大括号。