如何在python中将以前的打印覆盖到标准输出? [英] How to overwrite the previous print to stdout in python?

查看:37
本文介绍了如何在python中将以前的打印覆盖到标准输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下代码:

for x in range(10):
     print x

我会得到

1
2
etc..

我想做的是代替打印换行符,我想替换以前的值并用同一行上的新值覆盖它.

What I would like to do is instead of printing a newline, I want to replace the previous value and overwrite it with the new value on the same line.

推荐答案

简单版

一种方法是使用回车('\r')字符返回到行首而不前进到下一行.

Simple Version

One way is to use the carriage return ('\r') character to return to the start of the line without advancing to the next line.

for x in range(10):
    print(x, end='\r')
print()

Python 2.7 向前兼容

from __future__ import print_function
for x in range(10):
    print(x, end='\r')
print()

Python 2.7

for x in range(10):
    print '{}\r'.format(x),
print

Python 2.0-2.6

for x in range(10):
    print '{0}\r'.format(x),
print

在后两种(仅限 Python 2)情况下,print 语句末尾的逗号告诉它不要转到下一行.最后一个打印语句前进到下一行,因此您的提示不会覆盖您的最终输出.

In the latter two (Python 2-only) cases, the comma at the end of the print statement tells it not to go to the next line. The last print statement advances to the next line so your prompt won't overwrite your final output.

如果你不能保证新的一行文本不比现有行短,那么你只需要添加一个清除到行尾"的转义序列,'\x1b[1K' ('\x1b' = ESC):

If you can’t guarantee that the new line of text is not shorter than the existing line, then you just need to add a "clear to end of line" escape sequence, '\x1b[1K' ('\x1b' = ESC):

for x in range(75):
    print(‘*’ * (75 - x), x, end='\x1b[1K\r')
print()

这篇关于如何在python中将以前的打印覆盖到标准输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆