小编Bom*_*ton的帖子

如果键在 foo 中不存在,则忽略 str.format(**foo)

我正在尝试将电子邮件模板放在一起。消息内容将取决于字典中的值。但是,字典可能不会每次都包含所有键。

目前这很好,因为所有值都在字典 ( '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)
Run Code Online (Sandbox Code Playgroud)

msg变量中,我试图创建我的“模板”。这意味着我需要拥有字典中所有可能的项目。

例如,下一段将失败,因为它正在寻找'Date'这本词典中不存在的内容:

practise_dict = {"Additional Details":"blah blah blah blah", "Title": "Mr", "Surname": …
Run Code Online (Sandbox Code Playgroud)

python string escaping string-interpolation python-3.x

4
推荐指数
1
解决办法
774
查看次数