格式化字符串未使用的命名参数 [英] Format string unused named arguments

查看:61
本文介绍了格式化字符串未使用的命名参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有:

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:

<预><代码>>>>从集合导入 defaultdict>>>'{bond}, {james} {bond}'.format_map(defaultdict(str, bond='bond'))'债券,债券'

对于bond,{james}bond:

<预><代码>>>>类 SafeDict(dict):... def __missing__(self, key):...返回 '{' + key + '}'...>>>'{bond}, {james} {bond}'.format_map(SafeDict(bond='bond'))'邦德,{詹姆斯} 邦德'

在 Python 2.6/2.7 中

对于bond,bond:

<预><代码>>>>从集合导入 defaultdict>>>导入字符串>>>string.Formatter().vformat('{bond}, {james} {bond}', (), defaultdict(str, bond='bond'))'债券,债券'

对于bond,{james}bond:

<预><代码>>>>从集合导入 defaultdict>>>导入字符串>>>>>>类 SafeDict(dict):... def __missing__(self, key):...返回 '{' + key + '}'...>>>string.Formatter().vformat('{bond}, {james} {bond}', (), SafeDict(bond='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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆