如何在Python str.format中转义点号

8 投票
1 回答
3286 浏览
提问于 2025-04-18 07:48

我想用 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'

1 个回答

8

你不能这样做。格式字符串语法只支持整数或者有效的Python标识符作为键。从文档中可以看到:

arg_name          ::=  [identifier | integer]

这里的identifier这样定义的

标识符(也叫名字)是根据以下的词法定义来描述的:

identifier ::=  (letter|"_") (letter | digit | "_")*

不允许有点(.)或者分号(;)。

你可以把字典作为一个二级对象来使用:

"{v[hello.world]}".format(v={ 'hello.world' : '2' })

在这里,我们把字典赋值给了名字v,然后用一个键名来索引它。这些键名可以是任何字符串,而不仅仅是标识符。

撰写回答