假设我有:
action = '{bond}, {james} {bond}'.format(bond='bond', james='james')
这将输出:
'bond, james bond'
接下来我们有:
action = '{bond}, {james} {bond}'.format(bond='bond')
这将输出:
KeyError: 'james'
是否有一些解决方法可以防止此错误发生,例如:
- if keyrror: 忽略,别管它(但解析其他的)
- 将格式字符串与可用的命名参数进行比较,如果缺少则添加
如果您使用的是Python 3.2+,则可以使用str.format_map().
For bond, bond
:
from collections import defaultdict
'{bond}, {james} {bond}'.format_map(defaultdict(str, bond='bond'))
Result:
'bond, bond'
For bond, {james} bond
:
class SafeDict(dict):
def __missing__(self, key):
return '{' + key + '}'
'{bond}, {james} {bond}'.format_map(SafeDict(bond='bond'))
Result:
'bond, {james} bond'
在Python 2.6/2.7中
For bond, bond
:
from collections import defaultdict
import string
string.Formatter().vformat('{bond}, {james} {bond}', (), defaultdict(str, bond='bond'))
Result:
'bond, bond'
For 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'))
Result:
'bond, {james} bond'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)