gpt4 book ai didi

python - 如何在 python str.format 中转义点

转载 作者:太空狗 更新时间:2023-10-29 21:01:02 25 4
gpt4 key购买 nike

我希望能够访问字典中带有 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]

其中 identifierdefined 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com