这段代码中最后一个逗号的用法是什么?

时间:2011-06-22 02:39:52

标签: python

for x in range(1, 11):
     print repr(x).rjust(2), repr(x*x).rjust(3),
     # Note trailing comma on previous line
     print repr(x*x*x).rjust(4)

结果:

 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000

如果是连续符号,为什么作者可以再次写Print语句?

如果我删除了打印:

for x in range(1, 11):
     print repr(x).rjust(2), repr(x*x).rjust(3),
     # Note trailing comma on previous line
     repr(x*x*x).rjust(4)

结果:

 1   1  2   4  3   9  4  16  5  25  6  36  7  49  8  64  9  81 10 100

显然最后一行是忽略。为什么?是因为它不是声明吗?

如果我把最后一个表达式放回第二行:

for x in range(1, 11):
     print repr(x).rjust(2), repr(x*x).rjust(3), repr(x*x*x).rjust(4)

结果:

 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000

2 个答案:

答案 0 :(得分:19)

它会阻止print在文本末尾打印换行符。

正如戴夫所指出的,documentation说:...... “除非print语句以逗号结尾,否则最后会写一个'\ n'字符。”

答案 1 :(得分:3)

print语句末尾的逗号可防止将换行符附加到字符串。 (见http://docs.python.org/reference/simple_stmts.html#the-print-statement

在你的调整代码中:

for x in range(1, 11):
    print repr(x).rjust(2), repr(x*x).rjust(3),
    # Note trailing comma on previous line
    repr(x*x*x).rjust(4)

最后一行只是成为一个未使用的表达式,因为Python语句通常用换行符分隔。如果你将反斜杠(\) - Python行继续符 - 添加到print语句行的末尾并删除了注释,那么repr(x*x*x).rjust(4)将被附加到print语句。

更明确:

print repr(x).rjust(2), repr(x*x).rjust(3), repr(x*x*x).rjust(4)

print repr(x).rjust(2), repr(x*x).rjust(3), \
repr(x*x*x).rjust(4)

是等价的,但是

print repr(x).rjust(2), repr(x*x).rjust(3),
repr(x*x*x).rjust(4)

不是。 print语句的这种奇怪之处是它们在Python 3中修复的一个功能,它是一个函数。 (见http://docs.python.org/release/3.0.1/whatsnew/3.0.html#print-is-a-function