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

标签 python string-formatting

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

相关文章:

python - 将 PNG 形状转换为 KML 或 GeoJson

Python:使用 locals() 打印字典值

python - 带有分组依据的尾随或移动平均线

python:列表分配索引超出范围

javascript - 将字符串数字格式化为货币

iphone - iPhone 中的整数到字符串格式化程序问题

WPF XAML StringFormat : Culture Workaround broken in C# 4. 0?

python - python2.6中将整数转换为格式化的二进制字符串

python - 多进程的 Spawn.Process 在 Python 中未正确填充队列

java - 为什么我们会收到 HTTP 503 服务不可用的信息?