Let's say I have:
action = '{bond}, {james} {bond}'.format(bond='bond', james='james') this wil output:
'bond, james bond' Next we have:
action = '{bond}, {james} {bond}'.format(bond='bond') this will output:
KeyError: 'james' Is there some workaround to prevent this error to happen, something like:
For bond, bond:
>>> from collections import defaultdict >>> '{bond}, {james} {bond}'.format_map(defaultdict(str, bond='bond')) 'bond, bond' For bond, {james} bond:
>>> class SafeDict(dict): ... def __missing__(self, key): ... return '{' + key + '}' ... >>> '{bond}, {james} {bond}'.format_map(SafeDict(bond='bond')) 'bond, {james} bond' For bond, bond:
>>> from collections import defaultdict >>> import string >>> string.Formatter().vformat('{bond}, {james} {bond}', (), defaultdict(str, bond='bond')) 'bond, bond' For bond, {james} bond:
>>> from collections import defaultdict >>> import string >>> >>> class SafeDict(dict): ... def __missing__(self, key): ... return '{' + key + '}' ... >>> string.Formatter().vformat('{bond}, {james} {bond}', (), SafeDict(bond='bond')) 'bond, {james} bond'
You could use a template string with the safe_substitute method.
from string import Template tpl = Template('$bond, $james $bond') action = tpl.safe_substitute({'bond': 'bond'})
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