我希望能够访问字典中带有 str.format()
点的键。我该怎么做?
例如,不带点的键格式:
>>> "{hello}".format(**{ 'hello' : '2' })
'2'
但是当键中有一个点时它不会:
>>> "{hello.world}".format(**{ 'hello.world' : '2' })
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'hello'
最佳答案
你不能。 Format String Syntax支持仅整数或有效的Python标识符作为键。来自文档:
arg_name ::= [identifier | integer]
其中 identifier
是 defined as :
Identifiers (also referred to as names) are described by the following lexical definitions:
identifier ::= (letter|"_") (letter | digit | "_")*
不允许使用点(或分号)。
您可以将字典用作二级对象:
"{v[hello.world]}".format(v={ 'hello.world' : '2' })
这里我们将字典分配给名称 v
,然后使用键名对其进行索引。这些可以是任何字符串,而不仅仅是标识符。
关于python - 如何在 python str.format 中转义点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23909449/