2014-10-20 107 views
0

我很難讓「標記」顯示出來。我不知道如何正確使用.format()在字符串內顯示標記。在HTML中使用Python變量/ .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) 
+0

從[文件](HTTPS ://docs.python.org/2/library/string.html#format-string-syntax):如果你需要在文本文本中包含一個大括號字符,它可以通過加倍來轉義:'{{'和' }}'。 – 2014-10-20 13:51:55

回答

2

你需要逃避串在其他大括號({})的存在,否則該字符串將被format被誤解。

你必須重複字符來逃避它們。在你正在呼籲format串,行

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

改變

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

同樣地,對於右括號。

+0

非常感謝。它做了詭計。必須逃避HTML中的所有大括號。感謝您的快速響應。認爲這需要一週的時間才能收回任何東西! – Cesario 2014-10-20 17:08:34

1

您必須將字符串中的{}加倍,否則format將嘗試解釋大括號之間的文本。

您可以使用替代來做到這一點:
html = """\ 
your html code 
""".replace("{", "{{").replace("}", "}}").format(marker=marker) 

編輯:replace將改造成{marker}{{marker}},這樣就不會被format解釋...

+0

謝謝你,主要想法在那裏,它幫助解決問題:) – Cesario 2014-10-20 17:09:43