【问题标题】:Using Python Variable in HTML / .format()在 HTML / .format() 中使用 Python 变量
【发布时间】:2014-10-20 13:27:06
【问题描述】:

我很难让“标记”出现。我不知道如何正确使用.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)

【问题讨论】:

  • 来自the documentation:如果需要在文字文本中包含大括号字符,可以通过加倍进行转义:{{}}

标签: python html variables string.format


【解决方案1】:

您需要转义字符串中其他大括号({})的存在,否则字符串将被format 误解。

您必须重复字符才能转义它们。在您调用format 的字符串中,更改行

{mso-style-name:"Table Normal";

{{mso-style-name:"Table Normal";

同样适用于右括号。

【讨论】:

  • 非常感谢。它成功了。必须转义 HTML 中的所有大括号。感谢您的快速回复。以为要花一个星期才能收回任何东西!
【解决方案2】:

您必须将字符串中的{} 加倍,否则format 将尝试解释大括号之间的文本。

您可以使用替换来做到这一点:
html = """\
your html code
""".replace("{", "{{").replace("}", "}}").format(marker=marker)

编辑:replace 会将{marker} 转换为{{marker}},因此format 不会解释它...

【讨论】:

  • 谢谢,主要思想就在那里,它帮助解决了问题:)
【解决方案3】:

如果您不想操作 HTML 代码并添加额外的 {} 或 %,python 的 Template 字符串可能正是您要寻找的。我们来看一个例子:

from string import Template

t = Template('<body> $marker </body>')
t.substitute(marker='Hello World!')
'<body> Hello World! </body>'

【讨论】:

    猜你喜欢
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-01
    • 1970-01-01
    相关资源
    最近更新 更多