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

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

问题描述

假设我有:

action = '{bond}, {james} {bond}'.format(bond='bond', james='james')

此输出:

'bond, james bond' 

接下来我们有:

 action = '{bond}, {james} {bond}'.format(bond='bond')

这将输出:

KeyError: 'james'

是否有一些变通办法来防止发生此错误,例如:

Is there some workaround to prevent this error to happen, something like:

  • 如果keyrror:忽略,则不理会(但要解析其他人)
  • 比较格式字符串和可用的命名参数,如果缺少则添加

推荐答案

如果您使用的是Python 3.2+,则可以使用对于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格式字符串未使用的命名参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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