As PEP 3101, string.format(**other_dict)
is not available.
If the index or keyword refers to an item that does not exist, then an IndexError/KeyError should be raised.
A hint for solving the problem is in Customizing Formatters
, PEP 3101
. That uses string.Formatter
.
I improve the example in PEP 3101
:
from string import Formatter
class UnseenFormatter(Formatter):
def get_value(self, key, args, kwds):
if isinstance(key, str):
try:
return kwds[key]
except KeyError:
return key
else:
return Formatter.get_value(key, args, kwds)
string = "{number_of_sheep} sheep {has} run away"
other_dict = {'number_of_sheep' : 1}
fmt = UnseenFormatter()
print fmt.format(string, **other_dict)
The output is
1 sheep has run away