Python 什么是打印功能中的结尾逗号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18908897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's ending comma in print function for?
提问by allenhwkim
This code is from http://docs.python.org/2/tutorial/errors.html#predefined-clean-up-actions
此代码来自http://docs.python.org/2/tutorial/errors.html#predefined-clean-up-actions
with open("myfile.txt") as f:
for line in f:
print line,
What I don't understand is what's that ,
for at the end of print command.
我不明白的是,
打印命令末尾的那个是什么。
I also checked doc, http://docs.python.org/2/library/functions.html#print.
我还检查了文档,http://docs.python.org/2/library/functions.html#print。
Not understanding enough, is it a mistake?(it seems not. it's from the official tutorial).
理解不够,是不是写错了?(好像不是,来自官方教程)。
I am from ruby/javascript and it's unusual for me.
我来自 ruby/javascript,这对我来说很不寻常。
采纳答案by Serial
In python 2.7, the comma is to show that the string will be printed on the same line
在python 2.7中,逗号是表示字符串会打印在同一行
For example:
例如:
for i in xrange(10):
print i,
This will print
这将打印
1 2 3 4 5 6 7 8 9
To do this in python 3 you would do this:
要在 python 3 中执行此操作,您将执行以下操作:
for i in xrange(10):
print(i,end=" ")
You will probably find this answer helpful
你可能会发现这个答案很有帮助
Printing horizontally in python
---- Edit ---
- - 编辑 - -
The documentation, http://docs.python.org/2/reference/simple_stmts.html#the-print-statement, says
文档http://docs.python.org/2/reference/simple_stmts.html#the-print-statement说
A '\n' character is written at the end, unless the print statement ends with a comma.
'\n' 字符写在末尾,除非打印语句以逗号结尾。
回答by shanet
From Python trailing comma after print executes next instruction:
- In Python 2.x, a trailing
,
in a print statement prevents a new line to be emitted. - The standard output is line-buffered. So the "Hi" won't be printed before a new line is emitted.
- 在 Python 2.x 中,
,
打印语句中的尾随可防止发出新行。 - 标准输出是行缓冲的。因此,在发出新行之前不会打印“Hi”。
回答by Mark Ransom
It prevents the print
from ending with a newline, allowing you to append a new print
to the end of the line.
它可以防止print
以换行符结尾,允许您print
在行尾追加一个新的。
Python 3 changes this completely and the trailing comma is no longer accepted. You use the end
parameter to change the line ending, setting it to a blank string to get the same effect.
Python 3 完全改变了这一点,不再接受尾随逗号。您可以使用该end
参数更改行尾,将其设置为空字符串以获得相同的效果。
回答by user10480262
in python 2.7:
在python 2.7中:
print line,
in python 3.x:
在 python 3.x 中:
print(line, end = ' ')