假设我有:
action = '{bond}, {james} {bond}'.format(bond='bond', james='james')
这将输出:
'bond, james bond'
接下来我们有:
action = '{bond}, {james} {bond}'.format(bond='bond')
这将输出:
KeyError: 'james'
是否有一些解决方法可以防止发生此错误,例如:
- 如果 keyrror: 忽略,不要管它(但要解析其他)
- 将格式字符串与可用的命名参数进行比较,如果缺少则添加
最佳答案
如果你使用 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'
关于python - 格式化字符串未使用的命名参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17215400/