假设我有:
action = '{bond}, {james} {bond}'.format(bond='bond', james='james')
这个wil输出:
'bond, james bond'
接下来我们有:
action = '{bond}, {james} {bond}'.format(bond='bond')
这将输出:
KeyError: 'james'
是否有一些解决方法可以防止此错误发生,例如:
keyrror if keyrror: ignore,不管它(但要使用可用的命名参数解析others)
发布于 2013-06-20 21:55:50
如果您使用的是Python 3.2+,则可以使用str.format_map()。
对于bond, bond
>>> from collections import defaultdict
>>> '{bond}, {james} {bond}'.format_map(defaultdict(str, bond='bond'))
'bond, bond'
对于bond, {james} bond
>>> class SafeDict(dict):
... def __missing__(self, key):
... return '{' + key + '}'
...
>>> '{bond}, {james} {bond}'.format_map(SafeDict(bond='bond'))
'bond, {james} bond'
在Python 2.6/2.7中
对于bond, bond
>>> from collections import defaultdict
>>> import string
>>> string.Formatter().vformat('{bond}, {james} {bond}', (), defaultdict(str, bond='bond'))
'bond, bond'
对于bond, {james} bond
>>> from collections import defaultdict
>>> import string
>>>
>>> class SafeDict(dict):
... def __missing__(self, key):
... return '{' + key + '}'
...
>>> string.Formatter().vformat('{bond}, {james} {bond}', (), SafeDict(bond='bond'))
'bond, {james} bond'
发布于 2013-06-20 21:59:16
您可以在safe_substitute
方法中使用template string。
from string import Template
tpl = Template('$bond, $james $bond')
action = tpl.safe_substitute({'bond': 'bond'})
发布于 2015-11-10 09:59:14
您可以遵循PEP 3101和子类格式化程序中的建议:
from __future__ import print_function
import string
class MyFormatter(string.Formatter):
def __init__(self, default='{{{0}}}'):
self.default=default
def get_value(self, key, args, kwds):
if isinstance(key, str):
return kwds.get(key, self.default.format(key))
else:
return string.Formatter.get_value(key, args, kwds)
现在试一下:
>>> fmt=MyFormatter()
>>> fmt.format("{bond}, {james} {bond}", bond='bond', james='james')
'bond, james bond'
>>> fmt.format("{bond}, {james} {bond}", bond='bond')
'bond, {james} bond'
您可以通过将self.default
中的文本更改为您希望在KeyErrors中显示的文本来更改标记关键错误的方式:
>>> fmt=MyFormatter('">>{{{0}}} KeyError<<"')
>>> fmt.format("{bond}, {james} {bond}", bond='bond', james='james')
'bond, james bond'
>>> fmt.format("{bond}, {james} {bond}", bond='bond')
'bond, ">>{james} KeyError<<" bond'
该代码在Python2.6、2.7和3.0+上运行不变
https://stackoverflow.com/questions/17215400
复制相似问题