我想做几个语句,给出标准输出,而不看到换行之间的语句。

具体来说,假设我有:

for item in range(1,100):
    print item

结果是:

1
2
3
4
.
.
.

如何让它看起来像:

1 2 3 4 5 ...

更好的是,是否可以将单个数字打印在最后一个数字之上,这样一次只有一个数字出现在屏幕上?


当前回答

实现这一点的最佳方法是使用\r字符

试试下面的代码:

import time
for n in range(500):
  print(n, end='\r')
  time.sleep(0.01)
print()  # start new line so most recently printed number stays

其他回答

In [9]: print?
Type:           builtin_function_or_method
Base Class:     <type 'builtin_function_or_method'>
String Form:    <built-in function print>
Namespace:      Python builtin
Docstring:
    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.

for Python 2.7

for x in range(0, 3):
    print x,

for python3

for x in range(0, 3):
    print(x, end=" ")

打印语句末尾的逗号省略了新行。

for i in xrange(1,100):
  print i,

但这不会覆盖。

我认为一个简单的连接应该工作:

nl = []
for x in range(1,10):nl.append(str(x))
print ' '.join(nl)

或者更简单:

import time
a = 0
while True:
    print (a, end="\r")
    a += 1
    time.sleep(0.1)

End ="\r"将覆盖第一次打印的开头[0:]。