我正在尝试制作一份电子邮件模板。信息内容将取决于字典中的值。然而,每次字典可能不包含所有键。
目前情况还好,因为字典中包含所有的值 ('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)
有没有办法让它忽略字符串替换,如果在查找字典中不存在该键?