Python 3.6+ 格式化解包字典中缺少键的字符串

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

在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}

但是这个代码片段在Python3.6+中不起作用,在尝试从字典中获取last_name值时返回KeyError,有没有解决方法字符串格式化的工作方式与 Python3.4 中的工作方式相同吗?

谢谢!

最佳答案

我使用 format_map 解决了它而不是 format,按照我的示例:

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

打印

I am Richard {last_name}

正如预期的那样。

关于Python 3.6+ 格式化解包字典中缺少键的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53670748/

相关文章:

python - 随着时间的推移,Tkinter 应用程序的响应速度变得越来越慢

python - 如何从Python字典的最高值中随机打破平局?

c - 使用 malloc 初始化 char 指针 VS 不使用 malloc 直接将字符串赋给 char 指针

c# - .NET 是否有任何可用的方法来获取两个字符串的差异?

python - 为计算值设置数据框中的小数位数

python - 将 float 字符串转换为圆角 float 列表

delphi - 我可以在Delphi中使用字符串 "IsEmpty"方法吗

python - python 中的极地热图

python - "yield from"另一个生成器,但经过处理

python-3.x - 在 IDLE 中关闭 getpass.getpass() 的 echo