如何解决该代码中最后一个逗号的用法是什么?
|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,# 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,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
在文本末尾打印换行符。
正如Dave所指出的,文档说:…。 \“除非打印语句以逗号结尾,否则将在末尾写入一个\'\\ n \'字符。”
, 打印语句末尾的逗号可防止将换行符附加到字符串中。 (请参阅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语句通常由换行符分隔。如果在print语句的行末添加反斜杠(\\)(Python行继续字符)并删除了注释,则将8附加到print语句。
更明确地说:
print repr(x).rjust(2),repr(x*x*x).rjust(4)
和
print repr(x).rjust(2),\\
repr(x*x*x).rjust(4)
是等效的,但是
print repr(x).rjust(2),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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。