在同一行上打印新的输出

114
我想在同一行上将循环输出打印到屏幕上,如何以最简单的方式实现Python 3.x?我知道这个问题已经在Python 2.7中使用在行末加逗号即"print I,"的方式进行了解决,但我找不到一个适用于Python 3.x的方法。
i = 0 
while i <10:
     i += 1 
     ## print (i) # python 2.7 would be print i,
     print (i) # python 2.7 would be 'print i,'

屏幕输出。

1
2
3
4
5
6
7
8
9
10
我想要打印的内容是:
12345678910

新读者也可以访问这个链接 http://docs.python.org/release/3.0.1/whatsnew/3.0.html


3
如何在 Python 中动态地一行打印输出?你可以使用逗号 , 将多个字符串连接在一起,并使用 end 参数指定末尾字符为空格而不是新行符。这样,后续的输出就会在同一行上。例如,以下代码将打印数字 0 到 9,每隔一秒钟输出一个数字,并保持所有数字都在同一行上:import time for i in range(10): print(i, end=' ') time.sleep(1)输出结果如下:0 1 2 3 4 5 6 7 8 9 - Nanhe Kumar
7个回答

213

来自help(print)

Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file: a file-like object (stream); defaults to the current sys.stdout.
    sep:  string inserted between values, default a space.
    end:  string appended after the last value, default a newline.
你可以使用 end 关键字:
>>> for i in range(1, 11):
...     print(i, end='')
... 
12345678910>>> 
请注意,你需要自己使用print()打印最后的换行符。顺便提一下,在Python 2中,如果使用了结尾逗号,你将不会得到"12345678910",而是会得到1 2 3 4 5 6 7 8 9 10

谢谢。非常正确,print i,会有一个插入的空格。如果要它像Python 2一样使用逗号,代码应该是什么? - onxx
2
同样的事情,但是使用 end = ' '。你不再以空白结束每个打印“行”,而是以一个空格结束它。 - DSM
感谢您的快速回复和更新。现在我理解多了。我读了几十遍帮助函数,但显然没有仔细注意。 :) - onxx
谢谢,快速简单。 - Chandan Kumar

38

* 适用于 Python 2.x *

使用尾部逗号可以避免换行。

print "Hey Guys!",
print "This is how we print on the same line."
以上代码片段的输出结果为,
Hey Guys! This is how we print on the same line.

* 适用于 Python 3.x *

for i in range(10):
    print(i, end="<separator>") # <separator> = \n, <space> etc.

<separator> = " "时,上述代码片段的输出将是:

0 1 2 3 4 5 6 7 8 9

4
这仅适用于Python 2.x,在Python 3.x中不起作用。本篇文章介绍的是Python 3.x 的print用法。 - onxx
"...大家好!<空格>这是..."。有什么解决方法吗? - Sanket Patel
1
如何抑制第一个打印语句中逗号插入的空格? - BTR Naidu

14

与之前建议的类似,您可以执行:

print(i, end=',')

输出:0,1,2,3,


2
最后三个怎么样? - soheshdoshi

7
print("single",end=" ")
print("line")

这将产生输出

single line

针对所提出的问题,请使用以下方法

i = 0 
while i <10:
     i += 1 
     print (i,end="")

5

您可以做以下事情:

>>> print(''.join(map(str,range(1,11))))
12345678910

阅读该问题。print i 只在 Python 2 中有效,而不适用于 Python 3。 - onxx
2
好的,我错过了。我会编辑答案。 - Avichal Badaya

2
>>> for i in range(1, 11):
...     print(i, end=' ')
...     if i==len(range(1, 11)): print()
... 
1 2 3 4 5 6 7 8 9 10 
>>> 

这是如何做到打印不会在下一行提示后面运行的方法。

1

假设你想要在同一行打印从0到n的数字,你可以通过以下代码实现。

n=int(raw_input())
i=0
while(i<n):
    print i,
    i = i+1

在输入时,n = 5。
Output : 0 1 2 3 4 

3
这个答案被放入“低质量审核队列”,可能是因为您没有为代码提供任何解释。如果这段代码确实回答了问题,请考虑在您的答案中添加一些解释性文字来解释代码。这样一来,您很可能会获得更多的赞数,并帮助提问者学到新的知识。 - lmo
@imo 实际上他的代码没有回答问题,因为问题明确要求 Python 3.x。提供的代码..print i..只适用于Python 2。 - onxx

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接