我正在研究一个开源项目的代码。它的代码是用 python 编写的,不幸的是我对此没有那么丰富的经验。 我发现代码中有很多这样的语句:
print "the string is %s" % (name_of_variable, )
我知道,与c语言类似,这是一种正确格式化输出的方法,但我真的不明白括号内“name_of_variable”后面的逗号是什么意思。
我搜索了python文档,但没有找到任何关于这种说法的信息。有谁知道它的含义是什么?
尾随逗号是创建单元素元组的一种方法。通常,您通过在括号中列出一组值或变量来创建元组,并用逗号分隔:
my_tuple = (1, 2, 3)
但是,括号实际上并不是必需的。您可以创建一个像这样的元组:
my_tuple = 1, 2, 3
当然,这会引发单元素元组的问题。如果省略括号,您只是将一个变量分配给单个变量:
my_tuple = 1 # my_tuple is the integer 1, not a one-element tuple!
但是使用括号是不明确的,因为将值括在括号中是完全合法的:
my_tuple = (1) # my_tuple is still the integer 1, not a one-element tuple
因此,您可以通过添加尾随逗号来指示单元素元组:
my_tuple = 1,
# or, with parentheses
my_tuple = (1,)
字符串格式化采用元组作为参数,因此如果您使用单元素元组,则需要使用尾随逗号。 (当然,对于仅传递一个要格式化的变量的情况,字符串格式化有特殊处理 - 在这些情况下您可以只使用一个值,而不是元组。)
如果
name_of_variable
是一个元组,那么
print "the string is %s" % (name_of_variable)
会抛出一个
TypeError
。
因此,您必须使用
print "the string is %s" % (name_of_variable, )
来打印它。
当有多个变量时使用逗号。例如
print "the string is %s %s" % (name_of_variable1, name_of_variable2)
当你只使用一个变量时,有没有逗号并不重要,也不需要括号。
这里使用元组(括号和逗号)只是为了与多变量情况保持一致。
而且,如果单元素元组中没有逗号,它就不再是元组。
例如,
a = (1)
type(a) # <type 'int'>
人们还喜欢在元组中的最后一个元素后面附加一个逗号,即使他们有多个元素以保持一致性。
这是创建单元素元组的语法。例如,请参阅此链接。这里并不是必需的,因为
print
也接受一个变量,但一般来说 (x)
相当于 x
,所以强制将其解释为 tuple
语法的唯一方法就是这种看起来很奇怪的形式。注意区别:
>>> x = 0
>>> (x)
0
>>> (x,)
(0,)
>>> type((x))
<type 'int'>
>>> type((x,))
<type 'tuple'>
>>>
此外,不需要括号:
>>>x,
>>>(0,)
您可能还想阅读有关 %-formatting 语法。
(x,)
中的逗号是告诉Python括号括住一个元组,而不是单值子表达式的括号形式(最常用于更改运算符优先级,例如(a+b) * 2
与不同) a + b*2
)。字符串格式化运算符非常擅长猜测单个值何时不应该是序列,但如果您要传递元组而不是字符串,它将被解开:
>>> mytup=("Hello world!",)
>>> print "%s"%(mytup)
Hello world!
>>> print "%s"%(mytup,)
('Hello world!',)
>>> mytup=("Hello world!","Yoo-hoo, big summer blow-out!")
>>> print "%s"%(mytup)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
该运算符尝试类似于函数调用,其中参数列表始终作为元组(可能还有命名参数的字典)传递。当改为调用 str.format 时,这种差异就会消失,因为形成元组的括号是方法调用语法的一部分。
这里
,
并不具体,因为您仅使用单个变量。
In [96]: print "the string is %s" % (name_of_variable, )
the string is assdf
In [97]: print "the string is %s" % name_of_variable
the string is assdf
输出相同。
但是如果
name_of_variable
是tuple
那么有必要在打印语句中使用,
In [4]: tup = (1,2,)
In [6]: print ("the string is %s" % (tup))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-fb9ef4de3ac3> in <module>()
----> 1 print ("the string is %s" % (tup))
TypeError: not all arguments converted during string formatting
In [7]: print ("the string is %s" % (tup,))
the string is (1, 2)