为什么不用回车符打印\ r \ n抑制换行符?

时间:2016-10-23 21:47:51

标签: python printing newline

我对Python很新,但我正在尝试做一些我认为非常简单的事情。尽管如此,它已经困扰了我很长一段时间。

我有一个执行一定次数迭代的代码,我想在同一行上打印进度状态。

我尝试了以下

y=1000000
for x in range(y):
    if x % 100000 == 0 and x!=0 or x==y :
        print "  Iteration %d out of %d\r" % (x,y)

但我得到的不是回车而是

  Iteration 100000 out of 1000000
  Iteration 200000 out of 1000000
  Iteration 300000 out of 1000000
  Iteration 400000 out of 1000000
  Iteration 500000 out of 1000000
  ...

在视频中打印出来。

有趣的是,如果我这样做

for x in range(1000000):
    print "%d\r" % x,

它完成了这项工作。 有谁知道为什么?

3 个答案:

答案 0 :(得分:2)

如果要在Python 2.x中禁止打印换行符,请添加一个尾随逗号:

print s ,

所以在这种情况下:

print "  Iteration %d out of %d\r" % (x,y) ,

(提示:我总是在尾随逗号之前留一个空格以使其清楚)

在Python 3.x中它是:

print x,           # 2.x: Trailing comma suppresses newline
print(x, end="")   # 3.x: Appends a space instead of a newline

答案 1 :(得分:1)

您也可以使用

,而不是使用print
sys.stdout.write("  Iteration %d out of %d\r" % (x,y))

这不会为你写的内容添加任何换行符。

答案 2 :(得分:0)

这仅适用于python 3. 您可以添加end =""这将确保输出打印在同一行。 print print会在新行上将输出写入控制台。

print函数接受end参数,默认为" \ n"。将其设置为空字符串可防止它在该行的末尾发出新行。