Python的str.format()方法的默认kwarg值

问题描述 投票:10回答:3

我希望尝试尽可能简单地保持现有字符串的多元化,并且想知道在寻找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"

干杯

python string string-formatting default-value
3个回答
16
投票

作为PEP 3101string.format(**other_dict)不可用。

如果索引或关键字引用了不存在的项,则应引发IndexError / KeyError。

解决问题的一个提示是Customizing FormattersPEP 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
投票

基于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})

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))
© www.soinside.com 2019 - 2024. All rights reserved.