我想将循环输出打印到屏幕的同一行。
对于 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
最佳答案
来自帮助(打印)
:
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
。
关于python - 在同一行打印新输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12032214/