格式化字符串未使用的命名参数

新手上路,请多包涵

假设我有:

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

这将输出:

 'bond, james bond'

接下来我们有:

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

这将输出:

 KeyError: 'james'

是否有一些解决方法可以防止发生此错误,例如:

  • if keyrror: ignore,别管它(但要解析其他的)
  • 将格式字符串与可用的命名参数进行比较,如果缺少则添加

原文由 nelsonvarela 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 418
2 个回答

如果您使用的是 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.62.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'

原文由 falsetru 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以将 模板字符串safe_substitute 方法一起使用。

 from string import Template

tpl = Template('$bond, $james $bond')
action = tpl.safe_substitute({'bond': 'bond'})

原文由 Martin Maillard 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题