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