Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore str.format(**foo) if key doesn't exist in foo

I am trying to get an email template together. The message content will be dependent on values within a dictionary. However, the dictionary might not contain all the keys each time.

This currently is fine as all values are in the dictionary ('Title', 'Surname', 'Additional Details'):

practise_dict = {"Additional Details":"blah blah blah blah", "Title": "Mr", "Surname": "Smith", "URL": "/test/tester"}

msg = """From: John Smith <[email protected]>
To: {Title} {Surname} <[email protected]>
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)

In the msg variable I am trying to create my 'template'. This means that I need to have all possible items that could be in the dictionary.

For example the next piece would fail as it is looking for 'Date' that doesn't exist in this dictionary:

practise_dict = {"Additional Details":"blah blah blah blah", "Title": "Mr", "Surname": "Smith", "URL": "/test/tester"}

msg = """From: John Smith <[email protected]>
To: {Title} {Surname} <[email protected]>
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)

Is there a way to ask it to ignore a string substitution if it doesn't exist as a key in the look-up dictionary?

like image 295
Bombington Avatar asked Jan 09 '23 01:01

Bombington


1 Answers

You can use Template and safe_substitute for that:

from string import Template

practise_dict = {"Additional_Details":"blah blah blah blah", "Title": "Mr", "Surname": "Smith", "URL": "/test/tester"}

msg = """From: John Smith <[email protected]>
To: $Title $Surname <[email protected]>
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)

OUTPUT

From: John Smith <[email protected]>
To: Mr Smith <[email protected]>
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>
like image 162
Nir Alfasi Avatar answered Jan 16 '23 21:01

Nir Alfasi