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
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
首先,简单的问题是:
这是一个列表理解:
['%s:%d' % t for t in tupvalue]
现在,更难的问题!你知道吗
你的直觉是有点奇怪的事情在这里发生是正确的。元组在语言中是特殊大小写,用于字符串格式。你知道吗
百分比样式字符串格式无法正确键入。所以,如果你真的想格式化一个元组,你必须把它包装成另一个元组,不像其他任何类型的对象:
文档的相关部分在第4.7.2. ^{}-style String Formatting 节,其中提到:
元组的奇怪处理是文档开头的注释中提到的怪癖之一,也是推荐使用较新的字符串格式方法
str.format
的原因之一。你知道吗请注意,字符串格式的处理发生在运行时。您可以使用抽象语法树来验证这一点:
'%s' % val
解析为'%s'
和val
上的一个二进制操作,在CPython中,它的处理方式类似于str.__mod__(val)
,这是一个BINARY_MODULO
操作码。这意味着通常由str
类型决定当接收到的val
不正确时该怎么办,这只在表达式被计算时发生,即在解释器到达该行时发生。因此,不管val
是错误的类型还是元素太少/太多,这都是运行时错误,而不是语法错误。你知道吗†除非在某些特殊情况下,CPython的窥视孔优化器能够在编译时“恒定折叠”它。
除非
val
的类型子类str
,在这种情况下type(val).__rmod__
should be能够控制结果。相关问题 更多 >
编程相关推荐