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})
source share