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

具体来说,假设我有:

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)

其他回答

顺便说一下......如何每次刷新它,所以它打印mi在一个地方,只是改变数字。

一般来说,这样做的方法是使用终端控制代码。这是一个特别简单的情况,你只需要一个特殊的字符:U+000D CARRIAGE RETURN,它在Python(和许多其他语言)中被写成'\r'。下面是一个基于你的代码的完整示例:

from sys import stdout
from time import sleep
for i in range(1,20):
    stdout.write("\r%d" % i)
    stdout.flush()
    sleep(1)
stdout.write("\n") # move the cursor to the next line

有些事情可能会令人惊讶:

\r位于字符串的开头,以便在程序运行时,光标始终位于数字后面。这不仅仅是表面上的:如果你反过来做,一些终端模拟器会非常混乱。 如果您不包括最后一行,那么在程序终止后,shell将在数字上方打印提示符。 stdout。在某些系统上Flush是必要的,否则将得不到任何输出。其他系统可能不需要它,但它不会造成任何损害。

如果你发现这不起作用,你应该怀疑的第一件事是你的终端模拟器有bug。vttest程序可以帮助你测试它。

可以替换stdout。写与打印语句,但我不喜欢混合打印与直接使用文件对象。

for Python 2.7

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

for python3

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

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

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

使用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()

或者更简单:

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

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