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

具体来说,假设我有:

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

结果是:

1
2
3
4
.
.
.

如何让它看起来像:

1 2 3 4 5 ...

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


当前回答

对于那些像我一样挣扎的人,我提出了以下似乎在python 3.7.4和3.5.2中都可以工作的方法。

I expanded the range from 100 to 1,000,000 because it runs very fast and you may not see the output. This is because one side effect of setting end='\r' is that the final loop iteration clears all of the output. A longer number was needed to demonstrate that it works. This result may not be desirable in all cases, but was fine in mine, and OP didn't specify one way or another. You could potentially circumvent this with an if statement that evaluates the length of the array being iterated over, etc. The key to get it working in my case was to couple the brackets "{}" with .format(). Otherwise, it didn't work.

以下应按原样工作:

#!/usr/bin/env python3

for item in range(1,1000000):
    print("{}".format(item), end='\r', flush=True)

其他回答

使用print item,使print语句省略换行符。

在python3中,它是print(item, end=" ")。

如果你想让每个数字都显示在相同的位置,使用例如(Python 2.7):

to = 20
digits = len(str(to - 1))
delete = "\b" * (digits + 1)
for i in range(to):
    print "{0}{1:{2}}".format(delete, i, digits),

在Python 3中,这有点复杂;这里你需要刷新系统。Stdout或者在循环结束之前它不会打印任何东西:

import sys
to = 20
digits = len(str(to - 1))
delete = "\b" * (digits)
for i in range(to):
   print("{0}{1:{2}}".format(delete, i, digits), end="")
   sys.stdout.flush()

将打印项更改为:

在Python 2.7中,打印项 print(item, end=" "

如果你想动态打印数据,请使用以下语法:

打印(item, sep=' ', end= ", flush=True

如果您希望它作为字符串,您可以使用

number_string = ""
for i in range(1, 100):
  number_string += str(i)
print(number_string)

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

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

但这不会覆盖。

或者更简单:

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

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