Default kwarg values ​​for the Python method str.format ()

I try to keep the pluralization of existing strings as simple as possible, and wondered if str.format() to interpret the default when searching for kwargs. Here is an example:

 string = "{number_of_sheep} sheep {has} run away" dict_compiled_somewhere_else = {'number_of_sheep' : 4, 'has' : 'have'} string.format(**dict_compiled_somewhere_else) # gives "4 sheep have run away" other_dict = {'number_of_sheep' : 1} string.format(**other_dict) # gives a key error: u'has' # What I'd like is for format to somehow default to the key, or perhaps have some way of defining the 'default' value for the 'has' key # I'd have liked: "1 sheep has run away" 

Greetings

+6
source share
3 answers

Like PEP 3101 , string.format(**other_dict) not available.

If the index or keyword refers to an element that does not exist, IndexError / KeyError should be raised.

A hint for resolving the issue is in Customizing Formatters , PEP 3101 . This uses string.Formatter .

I will 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) 

Output signal

 1 sheep has run away 
+10
source

Based on the answer from mmsky and Daniel, here is a solution that determines the singular / plural number of words (at the same time correcting a couple of typos in mskimm's).

The only downside is the hard coding of the arg number keyword (so I can no longer use number_of_sheep )

 from string import Formatter class Plural(Formatter): PLURALS = {'has' : 'have'} def __init__(self): super(Plural, self).__init__() def get_value(self, key, args, kwds): if isinstance(key, str): try: return kwds[key] except KeyError: if kwds.get('number', 1) == 1: return key return self.PLURALS[key] return super(Plural, self).get_value(key, args, kwds) string = "{number} sheep {has} run away" fmt = Plural() print fmt.format(string, **{'number' : 1}) print fmt.format(string, **{'number' : 2}) 
+1
source

I do not see the benefits. You should still check for multiplicity, because usually you don’t have a fixed number of sheep

 class PluralVerb(object): EXCEPTIONS = {'have': 'has'} def __init__(self, plural): self.plural = plural def __format__(self, verb): if self.plural: return verb if verb in self.EXCEPTIONS: return self.EXCEPTIONS[verb] return verb+'s' number_of_sheep = 4 print "{number_of_sheep} sheep {pl:run} away".format(number_of_sheep=number_of_sheep, pl=PluralVerb(number_of_sheep!=1)) print "{number_of_sheep} sheep {pl:have} run away".format(number_of_sheep=number_of_sheep, pl=PluralVerb(number_of_sheep!=1)) 
0
source

All Articles