如何在python str.format中转义点

use*_*238 8 python string-formatting

我希望能够访问带有点的字典中的密钥str.format().我怎样才能做到这一点?

例如,没有点的键的格式有效:

>>> "{hello}".format(**{ 'hello' : '2' })
'2'
Run Code Online (Sandbox Code Playgroud)

但是当密钥中有一个点时它不会出现:

>>> "{hello.world}".format(**{ 'hello.world' : '2' })
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'hello'
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 7

你不能.该格式字符串语法支持整数或有效的Python标识符作为键.从文档:

arg_name          ::=  [identifier | integer]
Run Code Online (Sandbox Code Playgroud)

其中identifier定义为:

标识符(也称为名称)由以下词法定义描述:

identifier ::=  (letter|"_") (letter | digit | "_")*
Run Code Online (Sandbox Code Playgroud)

不允许使用点(或分号).

您可以将字典用作二级对象:

"{v[hello.world]}".format(v={ 'hello.world' : '2' })
Run Code Online (Sandbox Code Playgroud)

在这里,我们将字典分配给名称v,然后使用键名称将其编入索引.这些可以是任何字符串,而不仅仅是标识符.