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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:14:09  来源:igfitidea点击:

What's ending comma in print function for?

python

提问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

在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:

Python 尾随逗号打印后执行下一条指令

  1. In Python 2.x, a trailing ,in a print statement prevents a new line to be emitted.
  2. The standard output is line-buffered. So the "Hi" won't be printed before a new line is emitted.
  1. 在 Python 2.x 中,,打印语句中的尾随可防止发出新行。
  2. 标准输出是行缓冲的。因此,在发出新行之前不会打印“Hi”。

回答by Mark Ransom

It prevents the printfrom ending with a newline, allowing you to append a new printto the end of the line.

它可以防止print以换行符结尾,允许您print在行尾追加一个新的。

Python 3 changes this completely and the trailing comma is no longer accepted. You use the endparameter 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 = ' ')