【发布时间】:2015-03-21 14:06:57
【问题描述】:
我正在尝试将电子邮件模板放在一起。消息内容将取决于字典中的值。但是,字典可能不会每次都包含所有键。
目前这很好,因为所有值都在字典中('Title'、'Surname'、'Additional Details'):
practise_dict = {"Additional Details":"blah blah blah blah", "Title": "Mr", "Surname": "Smith", "URL": "/test/tester"}
msg = """From: John Smith <no-reply@somethingsomething.co.uk>
To: {Title} {Surname} <blah@blahblah.co.uk>
MIME-Version: 1.0
Content-type: text/html
Subject: New Website Enquiry
This is an e-mail message to be sent in HTML format
{Additional Details}
<b>This is HTML message.</b>
<h1>This is headline.</h1>
`""".format(**practise_dict)
print(msg)
在msg 变量中,我正在尝试创建我的“模板”。这意味着我需要拥有字典中所有可能的项目。
例如,下一段将失败,因为它正在查找此字典中不存在的 'Date':
practise_dict = {"Additional Details":"blah blah blah blah", "Title": "Mr", "Surname": "Smith", "URL": "/test/tester"}
msg = """From: John Smith <no-reply@somethingsomething.co.uk>
To: {Title} {Surname} <blah@blahblah.co.uk>
MIME-Version: 1.0
Content-type: text/html
Subject: New Website Enquiry
This is an e-mail message to be sent in HTML format
{Additional Details}
{Date}
<b>This is HTML message.</b>
<h1>This is headline.</h1>
`""".format(**practise_dict)
print(msg)
如果查找字典中不存在作为键的字符串替换,有没有办法让它忽略它?
【问题讨论】:
标签: python string python-3.x escaping string-interpolation