假设我有:
action = '{bond}, {james} {bond}'.format(bond='bond', james='james')
这将输出:
'bond, james bond'
接下来,我们有:
action = '{bond}, {james} {bond}'.format(bond='bond')
KeyError: 'james'
是否有一些解决方法来防止发生此错误,例如:
3.2+,则可以使用str.format_map()。
对于bond, bond:
bond, bond
>>> from collections import defaultdict >>> '{bond}, {james} {bond}'.format_map(defaultdict(str, bond='bond')) 'bond, bond'
对于bond, {james} bond:
bond, {james} bond
>>> class SafeDict(dict): ... def __missing__(self, key): ... return '{' + key + '}' ... >>> '{bond}, {james} {bond}'.format_map(SafeDict(bond='bond')) 'bond, {james} bond'
>>> from collections import defaultdict >>> import string >>> string.Formatter().vformat('{bond}, {james} {bond}', (), defaultdict(str, bond='bond')) 'bond, 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'