I have a string interpolation issue which I am not sure how to get it straight. Much appreciate any help towards solving this.
Abstract: I have a string template that composes an email body. This string template has both static and dynamic contents. The aim is to fill all dynamic parts of the template with context-specific values that will be supplied with the help of a dictionary.
Question: If you look at the code and output, I am able to extract the Key/Value from the dictionary (first and second print output). However, when the Values become collection type such as list or tuple, I have trouble in extracting them; especially the dynamic part of the text is getting embedded with the [ ] or ( )(third print output).
Is it possible to avoid [ ] or ( ) constructs from the output ? I would prefer the output as
'foo', 'bar'
instead of
['foo', 'bar']
import string
values = {'dynamic': 'foo'}
t = string.Template("""
Static contents : $dynamic
More static contents.
""")
print('Body:', t.substitute(values))
values = {'dynamic': 'foo, bar'}
print('Body:', t.substitute(values))
values = {'dynamic': ['foo', 'bar']}
print('Body:', t.substitute(values))

Note: Given logic and example only represent the idea of how I am injecting one dynamic content. In reality, I have more than one dynamic variables to be filled. Something like what Mail Merge does in Microsoft Word. E.g:
values = {'surname': 'xxx',
'email':'[email protected]',
'title':'Mr',
'reference':'xxxxx'
'contacts':['a','b','c']
}
I don't have complete grasp over what exactly you want but instead of using templates why not use regular strings with string formatting?
For Example:
t = """
Static contents : {dynamic}
More static contents.
"""
values = {
'str': 'foo, bar',
'dict': {'test': 'foo'},
'list': ['foo', 'bar'],
'list2': ["'foo'", "'bar'"],
}
print('Body:', t.format(dynamic=values['str']))
print('Body:', t.format(dynamic=', '.join(values['dict'].values())))
print('Body:', t.format(dynamic=str(values['list'])[1:-1]))
# OR (the less exception prone way)
print('Body:', t.format(dynamic=', '.join(values['list2'])))
Output:
Body:
Static contents : foo, bar
More static contents.
Body:
Static contents : foo, bar2
More static contents.
Body:
Static contents : 'foo', 'bar'
More static contents.
Body:
Static contents : 'foo', 'bar'
More static contents.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With