传递元组列表时格式说明符如何取值

2024-09-30 10:41:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一段代码如下:

tupvalue = [('html', 96), ('css', 115), ('map', 82)]

因此,在以特定索引的所需格式打印上述元组时,我发现了如下代码:

>>> '%s:%d' % tupvalue[0]
'html:96'

我想知道格式说明符如何将单个值tupvalue[0]识别为两个值的元组'%s:%d'?请用文档参考来解释这个机制。你知道吗

如何使用理解将tupvalue中的所有值格式化为所需格式,如示例所示?你知道吗


Tags: 代码文档示例maphtml格式css机制
1条回答
网友
1楼 · 发布于 2024-09-30 10:41:58

首先,简单的问题是:

How can I use a comprehension to format all the values in tupvalue in the required format as in the example shown?

这是一个列表理解:['%s:%d' % t for t in tupvalue]

现在,更难的问题!你知道吗

how the single value tupvalue[0] is recognised as a tuple of two values by the format specifier '%s:%d'?

你的直觉是有点奇怪的事情在这里发生是正确的。元组在语言中是特殊大小写,用于字符串格式。你知道吗

>>> '%s:%d' % ('css', 115)  # tuple is seen as two elements
'css:115'
>>> '%s:%d' % ['css', 115]  # list is just seen as one object!
TypeError: not enough arguments for format string

百分比样式字符串格式无法正确键入。所以,如果你真的想格式化一个元组,你必须把它包装成另一个元组,不像其他任何类型的对象:

>>> '%s' % []
'[]'
>>> '%s' % ((),)
'()'
>>> '%s' % ()
TypeError: not enough arguments for format string

文档的相关部分在第4.7.2. ^{}-style String Formatting节,其中提到:

If format requires a single argument, values may be a single non-tuple object. Otherwise, values must be a tuple with exactly the number of items specified by the format string

元组的奇怪处理是文档开头的注释中提到的怪癖之一,也是推荐使用较新的字符串格式方法str.format的原因之一。你知道吗

请注意,字符串格式的处理发生在运行时。您可以使用抽象语法树来验证这一点:

>>> import ast
>>> ast.dump(ast.parse('"%s" % val'))
"Module(body=[Expr(value=BinOp(left=Str(s='%s'), op=Mod(), right=Name(id='val', ctx=Load())))])"

'%s' % val解析为'%s'val上的一个二进制操作,在CPython中,它的处理方式类似于str.__mod__(val),这是一个BINARY_MODULO操作码。这意味着通常由str类型决定当接收到的val不正确时该怎么办,这只在表达式被计算时发生,即在解释器到达该行时发生。因此,不管val是错误的类型还是元素太少/太多,这都是运行时错误,而不是语法错误。你知道吗

除非在某些特殊情况下,CPython的窥视孔优化器能够在编译时“恒定折叠”它。

除非val的类型子类str,在这种情况下type(val).__rmod__should be能够控制结果。

相关问题 更多 >

    热门问题