gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:20:52 25 4
gpt4 key购买 nike

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

这目前没问题,因为所有值都在字典中('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 变量中,我试图创建我的"template"。这意味着我需要拥有所有可能出现在字典中的项目。

例如,下一段将失败,因为它正在寻找此字典中不存在的 '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)

如果它不作为查找字典中的键存在,是否有办法要求它忽略字符串替换?

最佳答案

您可以为此使用 Templatesafe_substitute:

from string import Template

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>
`"""

s = Template(msg).safe_substitute(**practise_dict)
print(s)

输出

From: John Smith <no-reply@somethingsomething.co.uk>
To: Mr Smith <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
blah blah blah blah
$Date
<b>This is HTML message.</b>
<h1>This is headline.</h1>

关于python - 如果 foo 中不存在键,则忽略 str.format(**foo),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28094590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com