【问题标题】:Keyerror in multiple key string interpolation in PythonPython中多键字符串插值中的Keyerror
【发布时间】:2017-06-15 20:29:39
【问题描述】:

我遇到了类似的问题

In [5]: x = "this string takes two like {one} and {two}"

In [6]: y = x.format(one="one")
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-6-b3c89fbea4d3> in <module>()
----> 1 y = x.format(one="one")

KeyError: 'two'

我有一个复合字符串,其中包含许多保存在配置文件中的键。对于 8 个不同的查询,它们都使用相同的字符串,除了 1 个键是不同的设置。我需要能够替换该文件中的密钥以保存字符串以供以后使用:

"this string takes two like one and {two}"

如何使用format 一次替换一个键?

【问题讨论】:

  • 你至少可以做y = x.format(one="one", two="{two}"),但这可能不是最好的方法......
  • y = x.replace('{one}', 'whatever') 怎么样?

标签: python string python-2.7


【解决方案1】:

我认为string.Template 做你想做的事:

from string import Template

s = "this string takes two like $one and $two"
s = Template(s).safe_substitute(one=1)
print(s)
# this string takes two like 1 and $two

s = Template(s).safe_substitute(two=2)
print(s)
# this string takes two like 1 and 2

【讨论】:

    【解决方案2】:

    如果字符串中的占位符没有任何格式规范,在 Python 3 中,您可以使用 str.format_map 并提供映射,返回缺失字段的字段名称:

    class Default(dict):
        def __missing__(self, key):
            return '{' + key + '}'
    
    In [6]: x = "this string takes two like {one} and {two}"
    
    In [7]: x.format_map(Default(one=1))
    Out[7]: 'this string takes two like 1 and {two}'
    

    如果您确实有格式规范,则必须继承 string.Formatter 并覆盖一些方法,或切换到不同的格式设置方法,例如 string.Template

    【讨论】:

    • 相当有趣的方法。
    【解决方案3】:

    你可以通过加倍大括号来逃避{two}的插值:

    x = "this string takes two like {one} and {{two}}"
    y = x.format(one=1)
    z = y.format(two=2)
    print(z) # this string takes two like 1 and 2
    

    另一种方法是template strings

    from string import Template
    
    t = Template('this string takes two like $one and $two')
    y = t.safe_substitute(one=1)
    print(y)  # this string takes two like 1 and $two
    z = Template(y).safe_substitute(two=2)
    print(z) # this string takes two like 1 and 2
    

    this answer 在我之前用于模板字符串......)

    【讨论】:

    • 让我们看看那个
    • 由于某种原因,这在 shell 中有效,但是当我尝试运行服务器时爆炸了
    【解决方案4】:

    您可以将{two} 替换为{two} 以便以后进行进一步替换:

    y = x.format(one="one", two="{two}")
    

    这很容易在多个替换段落中扩展,但它要求您在每次迭代中提供所有键。

    【讨论】:

      【解决方案5】:

      所有很好的答案,我将很快开始使用这个Template 包。对这里的默认行为非常失望,不理解为什么字符串模板每次都需要传递所有键,如果有 3 个键,我看不出你不能传递 1 或 2 的逻辑原因(但我也没有知道编译器是如何工作的)

      通过使用%s 解决我在配置文件中立即替换的项目,并使用{key} 解决我稍后在执行烧瓶服务器时替换的键

      In [1]: issue = "Python3 string {item} are somewhat defective: %s"
      
      In [2]: preformatted_issue = issue % 'true'
      
      In [3]: preformatted_issue
      Out[3]: 'Python3 string {item} are somewhat defective: true'
      
      In [4]: result = preformatted_issue.format(item='templates')
      
      In [5]: result
      Out[5]: 'Python3 string templates are somewhat defective: true'
      

      【讨论】:

        猜你喜欢
        • 2011-11-15
        • 1970-01-01
        • 1970-01-01
        • 2019-09-16
        • 1970-01-01
        • 1970-01-01
        • 2013-07-02
        • 1970-01-01
        • 2016-08-05
        相关资源
        最近更新 更多