我想做几个语句,给出标准输出,而不看到换行之间的语句。
具体来说,假设我有:
for item in range(1,100):
print item
结果是:
1
2
3
4
.
.
.
如何让它看起来像:
1 2 3 4 5 ...
更好的是,是否可以将单个数字打印在最后一个数字之上,这样一次只有一个数字出现在屏幕上?
我想做几个语句,给出标准输出,而不看到换行之间的语句。
具体来说,假设我有:
for item in range(1,100):
print item
结果是:
1
2
3
4
.
.
.
如何让它看起来像:
1 2 3 4 5 ...
更好的是,是否可以将单个数字打印在最后一个数字之上,这样一次只有一个数字出现在屏幕上?
当前回答
为了让数字相互覆盖,你可以这样做:
for i in range(1,100):
print "\r",i,
只要把数字打印在第一列,这就可以工作。
编辑: 这里有一个版本,即使没有打印在第一列,也可以工作。
prev_digits = -1
for i in range(0,1000):
print("%s%d" % ("\b"*(prev_digits + 1), i)),
prev_digits = len(str(i))
我应该指出,这段代码经过测试,在Windows上的Python 2.5中,在Windows控制台中工作得很好。根据其他一些方法,可能需要刷新stdout才能查看结果。YMMV。
其他回答
使用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()
注意:我之所以指出这个解决方案,是因为如果下一次打印的长度小于前一次打印的长度,我所见过的大多数其他解决方案都不起作用。
如果您知道要删除什么,并且可以使用全局变量,那么只需用空格覆盖最后一行。
在打印之前,将字符串的长度存储为' n '。 打印它,但以' \r '结尾(它返回行首)。 下次,在打印信息之前,在该行上打印“n”个空格。
_last_print_len = 0
def reprint(msg, finish=False):
global _last_print_len
# Ovewrites line with spaces.
print(' '*_last_print_len, end='\r')
if finish:
end = '\n'
# If we're finishing the line, we won't need to overwrite it in the next print.
_last_print_len = 0
else:
end = '\r'
# Store len for the next print.
_last_print_len = len(msg)
# Printing message.
print(msg, end=end)
例子:
for i in range(10):
reprint('Loading.')
time.sleep(1)
reprint('Loading..')
time.sleep(1)
reprint('Loading...')
time.sleep(1)
for i in range(10):
reprint('Loading.')
time.sleep(1)
reprint('Loading..')
time.sleep(1)
reprint('Loading...', finish=True)
time.sleep(1)
将打印项更改为:
在Python 2.7中,打印项 print(item, end=" "
如果你想动态打印数据,请使用以下语法:
打印(item, sep=' ', end= ", flush=True
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.
你可以在你的print语句中添加一个尾随逗号,在每次迭代中打印一个空格而不是换行符:
print item,
或者,如果你使用的是Python 2.6或更高版本,你可以使用新的print函数,它允许你指定甚至不应该在打印的每一项的结尾出现空格(或者允许你指定任何你想要的结尾):
from __future__ import print_function
...
print(item, end="")
最后,你可以通过从sys模块导入标准输出直接写入标准输出,它会返回一个类文件对象:
from sys import stdout
...
stdout.write( str(item) )