格式化字符串未使用的命名参数 [英] Format string unused named arguments
本文介绍了格式化字符串未使用的命名参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有:
action = '{bond}, {james} {bond}'.format(bond='bond', james='james')
这将输出:
'邦德,詹姆斯邦德'
接下来我们有:
action = '{bond}, {james} {bond}'.format(bond='bond')
这将输出:
KeyError: 'james'
是否有一些解决方法可以防止发生此错误,例如:
- 如果 keyrror: 忽略,不要管它(但要解析其他的)
- 将格式字符串与可用的命名参数进行比较,如果缺少则添加
解决方案
如果你使用的是 Python 3.2+,使用可以使用 str.format_map().
对于bond,bond
:
对于bond,{james}bond
:
在 Python 2.6/2.7 中
对于bond,bond
:
对于bond,{james}bond
:
Let's say I have:
action = '{bond}, {james} {bond}'.format(bond='bond', james='james')
this wil output:
'bond, james bond'
Next we have:
action = '{bond}, {james} {bond}'.format(bond='bond')
this will output:
KeyError: 'james'
Is there some workaround to prevent this error to happen, something like:
- if keyrror: ignore, leave it alone (but do parse others)
- compare format string with available named arguments, if missing then add
解决方案
If you are using Python 3.2+, use can use str.format_map().
For bond, bond
:
>>> from collections import defaultdict
>>> '{bond}, {james} {bond}'.format_map(defaultdict(str, bond='bond'))
'bond, bond'
For bond, {james} bond
:
>>> class SafeDict(dict):
... def __missing__(self, key):
... return '{' + key + '}'
...
>>> '{bond}, {james} {bond}'.format_map(SafeDict(bond='bond'))
'bond, {james} bond'
In Python 2.6/2.7
For bond, bond
:
>>> from collections import defaultdict
>>> import string
>>> string.Formatter().vformat('{bond}, {james} {bond}', (), defaultdict(str, bond='bond'))
'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'))
'bond, {james} bond'
这篇关于格式化字符串未使用的命名参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文