在同一lin上打印新输出

2024-04-18 11:55:00 发布

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

我想把循环输出打印到同一行的屏幕上。

对于Python3.x,如何以最简单的方式实现这一点

我知道Python2.7在行尾使用逗号(即print I)提出了这个问题,但我找不到Python3.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


Tags: orghttpdocs屏幕链接方式be解决方案
3条回答

类似的建议,您可以:

print(i,end=',')

Output: 0, 1, 2, 3,

*对于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

来自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

相关问题 更多 >