我希望尽可能简化现有字符串的复数形式,并想知道是否可能让str.format()
在查找关键字参数时解释默认值。这里是一个例子:
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"
干杯