用字符串格式化dict键的正确方法是什么?
当我这样做时:
>>> foo = {'one key': 'one value', 'second key': 'second value'}
>>> "In the middle of a string: {foo.keys()}".format(**locals())
我期望的是:
"In the middle of a string: ['one key', 'second key']"
我得到的是:
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
"In the middle of a string: {foo.keys()}".format(**locals())
AttributeError: 'dict' object has no attribute 'keys()'
但正如你所见,我的字典有钥匙:
>>> foo.keys()
['second key', 'one key']
不能在占位符中调用方法。您可以访问属性和属性,甚至为值编制索引,但不能调用方法:
方法示例(失败):
具有属性(工作)的示例:
格式化语法清楚地表明,您只能访问属性(a la
getattr
)或索引(a la__getitem__
)占位符(取自"Format String Syntax"):使用Python 3.6,您可以使用f字符串轻松完成此操作,甚至不必传入
locals
:相关问题 更多 >
编程相关推荐