Python str.format() 方法的默认关键字参数值
我想尽量让已有字符串的复数形式处理得简单一些,想知道能不能让 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"
谢谢
3 个回答
1
根据mskimm和Daniel的回答,这里有一个解决方案,它预先定义了单数和复数的词(同时纠正了mskimm的一些拼写错误)。
唯一的缺点是关键字参数number
是硬编码的(所以我不能再使用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})
2
我看不出有什么好处。你还是得检查数量,因为通常你并不知道羊的确切数量。
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))
31
根据PEP 3101,string.format(**other_dict)
这个功能是不可用的。
如果你用的索引或者关键字指向一个不存在的项目,就会出现IndexError或者KeyError的错误。
解决这个问题的一个提示在于自定义格式化器
,也就是PEP 3101
中提到的内容。这个方法使用了string.Formatter
。
我对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)
输出结果是
1 sheep has run away