Pat*_*ick 13 python string string-formatting default-value
我希望尝试尽可能简单地保持现有字符串的多元化,并且想知道str.format()在寻找kwargs时是否有可能解释默认值.这是一个例子:
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"
Run Code Online (Sandbox Code Playgroud)
干杯
eme*_*eth 20
作为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)
Run Code Online (Sandbox Code Playgroud)
输出是
1 sheep has run away
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11339 次 |
| 最近记录: |