打印函数中逗号的结尾是什么?

2024-04-29 13:17:43 发布

您现在位置:Python中文网/ 问答频道 /正文

这段代码来自http://docs.python.org/2/tutorial/errors.html#predefined-clean-up-actions

with open("myfile.txt") as f:
    for line in f:
        print line,

我不明白的是,print命令末尾的,是什么。

我还查了医生,http://docs.python.org/2/library/functions.html#print

不够理解,是不是错了?(似乎不是。它来自官方教程)。

我来自ruby/javascript,这对我来说很不寻常。


Tags: 代码orgcleanactionshttpdocshtmlwith
3条回答

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

Python 3完全改变了这一点,后面的逗号不再被接受。使用end参数更改行尾,将其设置为空字符串以获得相同的效果。

来自Python trailing comma after print executes next instruction

  1. 在Python2.x中,print语句中的尾随,防止发出新行。
  2. 标准输出是行缓冲的。所以在发出新行之前不会打印“Hi”。

在Python2.7中,逗号表示字符串将打印在同一行上

例如:

for i in xrange(10):
     print i,

这将打印

1 2 3 4 5 6 7 8 9 

要在Python3中执行此操作,请执行以下操作:

 for i in xrange(10):
      print(i,end=" ")

你可能会发现这个答案很有用

Printing horizontally in python

----编辑---

文档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.

相关问题 更多 >