【问题标题】:Python 3.6+ formatting strings from unpacking dictionaries with missing keysPython 3.6+ 从缺少键的解包字典中格式化字符串
【发布时间】:2019-05-09 07:00:23
【问题描述】:

在 Python3.4 中你可以做以下事情:

class MyDict(dict):
    def __missing__(self, key):
        return "{%s}" % key

然后是这样的:

d = MyDict()
d['first_name'] = 'Richard'
print('I am {first_name} {last_name}'.format(**d))

按预期打印:

I am Richard {last_name}

但是这个 sn-p 在 Python3.6+ 中不起作用,在尝试从字典中获取 last_name 值时返回 KeyError,是否有任何解决方法可以使该字符串格式以相同的方式工作和 Python3.4 一样?

谢谢!

【问题讨论】:

    标签: python string python-3.x dictionary string-formatting


    【解决方案1】:

    按照我的示例,我使用format_map 而不是format 解决了这个问题:

    print('I am {first_name} {last_name}'.format_map(d))
    

    印刷

    I am Richard {last_name}
    

    正如预期的那样。

    【讨论】:

      【解决方案2】:

      在 Python 3.6+ 中,您可以使用格式化的字符串文字 (PEP 498):

      class MyDict(dict):
          def __missing__(self, key):
              return f'{{{key}}}'
      
      d = MyDict()
      d['first_name'] = 'Richard'
      
      print(f"I am {d['first_name']} {d['last_name']}")
      
      # I am Richard {last_name}
      

      【讨论】:

      • 是的,我也尝试过这个解决方案,问题是我有几个几百行长的字符串,所以按值更改值不是一种选择(极易出错),感谢您的替代方案,不过!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-29
      • 2016-12-10
      • 2018-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多