Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format string unused named arguments [duplicate]

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:

  • if keyrror: ignore, leave it alone (but do parse others)
  • compare format string with available named arguments, if missing then add
like image 784
nelsonvarela Avatar asked Jun 20 '13 13:06

nelsonvarela


2 Answers

If you are using Python 3.2+, use can use str.format_map().

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' 

In Python 2.6/2.7

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' 
like image 100
falsetru Avatar answered Oct 06 '22 23:10

falsetru


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'}) 
like image 20
Martin Maillard Avatar answered Oct 07 '22 00:10

Martin Maillard