Leaving values blank if not passed in str.format
You can follow the recommendation in PEP 3101 and use a subclass Formatter:
import stringclass BlankFormatter(string.Formatter): def __init__(self, default=''): self.default=default def get_value(self, key, args, kwds): if isinstance(key, str): return kwds.get(key, self.default) else: return string.Formatter.get_value(key, args, kwds)kwargs = {"name": "mark", "adj": "mad"} fmt=BlankFormatter()print fmt.format("My name is {name} and I'm really {adj}.", **kwargs)# My name is mark and I'm really mad.print fmt.format("My name is {name} and I'm really {adjective}.", **kwargs)# My name is mark and I'm really .
As of Python 3.2, you can use .format_map as an alternative:
class Default(dict): def __missing__(self, key): return '{'+key+'}'kwargs = {"name": "mark"}print("My name is {name} and I'm really {adjective}.".format_map(Default(kwargs)))
which prints:
My name is mark and I'm really {adjective}.
Here is one option which uses collections.defaultdict
:
>>> from collections import defaultdict>>> kwargs = {"name": "mark"}>>> template = "My name is {0[name]} and I'm really {0[adjective]}.">>> template.format(defaultdict(str, kwargs))"My name is mark and I'm really ."
Note that we aren't using **
to unpack the dictionary into keyword arguments anymore, and the format specifier uses {0[name]}
and {0[adjective]}
, which indicates that we should perform a key lookup on the first argument to format()
using "name"
and "adjective"
respectively. By using defaultdict
a missing key will result in an empty string instead of raising a KeyError.
For the record:
s = "My name is {name} and I'm really {adjective}."kwargs = dict((x[1], '') for x in s._formatter_parser())# Now we have: `kwargs = {'name':'', 'adjective':''}`.kwargs.update(name='mark')print s.format(**kwargs) # My name is mark and I'm really .