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

8
我希望能够使用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'

变量名中不能包含句点或分号。 - devnull
1
你的变量名没有分号,它有一个句号。 - Martijn Pieters
可能是如何在Python格式字符串中使用点号?的重复问题。 - Amir Ali Akbari
1个回答

8
您无法实现该功能。根据文档,格式化字符串语法仅支持整数或有效的Python标识符作为键。以下是文档内容:
arg_name          ::=  [identifier | integer]

在IT技术中,identifier是一个特定的识别符号,其定义如下:

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,然后使用键名索引它。这些可以是任何字符串,不仅仅是标识符。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接