首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >格式字符串未使用的命名参数

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

Stack Overflow用户
提问于 2013-06-20 21:50:19
回答 9查看 32.9K关注 0票数 67

假设我有:

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

这个wil输出:

'bond, james bond' 

接下来我们有:

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

这将输出:

KeyError: 'james'

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

keyrror if keyrror: ignore,不管它(但要使用可用的命名参数解析others)

  • compare格式的字符串,如果缺少,则添加
EN

回答 9

Stack Overflow用户

回答已采纳

发布于 2013-06-20 21:55:50

如果您使用的是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'
票数 109
EN

Stack Overflow用户

发布于 2013-06-20 21:59:16

您可以在safe_substitute方法中使用template string

from string import Template

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

Stack Overflow用户

发布于 2015-11-10 09:59:14

您可以遵循PEP 3101和子类格式化程序中的建议:

from __future__ import print_function
import string

class MyFormatter(string.Formatter):
    def __init__(self, default='{{{0}}}'):
        self.default=default

    def get_value(self, key, args, kwds):
        if isinstance(key, str):
            return kwds.get(key, self.default.format(key))
        else:
            return string.Formatter.get_value(key, args, kwds)

现在试一下:

>>> fmt=MyFormatter()
>>> fmt.format("{bond}, {james} {bond}", bond='bond', james='james')
'bond, james bond'
>>> fmt.format("{bond}, {james} {bond}", bond='bond')
'bond, {james} bond'

您可以通过将self.default中的文本更改为您希望在KeyErrors中显示的文本来更改标记关键错误的方式:

>>> fmt=MyFormatter('">>{{{0}}} KeyError<<"')
>>> fmt.format("{bond}, {james} {bond}", bond='bond', james='james')
'bond, james bond'
>>> fmt.format("{bond}, {james} {bond}", bond='bond')
'bond, ">>{james} KeyError<<" bond'

该代码在Python2.6、2.7和3.0+上运行不变

票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17215400

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档