2014-10-20 2 views
0

Мне очень трудно получить «маркер», чтобы он появился. Я не знаю, как правильно использовать .format(), чтобы показать маркер внутри строки.Использование переменной Python в HTML/.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): если вам нужно включить символ скобки в литеральном тексте, его можно экранировать путем удвоения: '{{' and ' }} '. –

ответ

2

Вы должны избежать присутствия других фигурных скобок ({ и }) в строке, в противном случае строка будет извращено format.

Вы должны повторить символы, чтобы избежать их. В строке вы звоните format на, измените строку

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

в

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

и аналогично для закрывающей скобки.

+0

Большое вам спасибо. Это сделал трюк. Чтобы избежать всех фигурных скобок в HTML. Спасибо за быстрый ответ. Думал, что понадобится неделя, чтобы что-то вернуть! – Cesario

1

Вы должны удвоить { и } в своей строке, в противном случае format попытается интерпретировать текст между фигурными скобками.

Вы можете использовать замену, чтобы сделать это:
html = """\ 
your html code 
""".replace("{", "{{").replace("}", "}}").format(marker=marker) 

EDIT: replace превратит {marker} в {{marker}}, так что это не будет истолковано format ...

+0

Спасибо, основная идея была там, и это помогло решить проблему :) – Cesario

Смежные вопросы