我希望尽可能简单地尝试保持现有字符串的多元化,并且想知道在查找kwargs时是否有可能让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"
干杯
答案 0 :(得分:16)
由于PEP 3101,string.format(**other_dict)
无效。
如果索引或关键字引用了不存在的项,则为 应该引发IndexError / KeyError。
解决问题的提示是Customizing Formatters
,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
答案 1 :(得分:1)
基于mskimm和Daniel回答,这是一个预定义单数/复数单词的解决方案(同时纠正mskimm中的几个拼写错误)。
唯一的缺点是关键字arg 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 :(得分:0)
无法看到优势。无论如何你必须检查多个,因为通常你没有固定数量的羊
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))