Python:如何在同一行打印,清除以前的文本? [英] Python: How to print on same line, clearing previous text?

查看:160
本文介绍了Python:如何在同一行打印,清除以前的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,您可以使用 \r 在同一行上打印以移回行首.

In Python you can print on the same line using \r to move back to the start of the line.

这适用于进度条或增加百分比计数器,例如:Python 打印在同一行

This works well for progress bars or increasing precentage counters, eg: Python print on same line

然而,当打印长度可能减少的行时,这会将前一行文本留在那里,例如:

However when printing lines that may decrease in length, this leaves the previous lines text there, eg:

import sys
for t in ['long line', '%']:
    sys.stdout.write(t + '\r')
sys.stdout.write('\n')

保留终端文本为:%ong line.

在打印到同一行时,在较长的一行之后写一条较短的行的最佳方法是什么?

Whats the best way to write a shorter line after a longer one, when printing to the same line?

推荐答案

\r 一起,需要 ansi-sequence \033[K - 擦除到行尾.

Along with \r, the ansi-sequence \033[K is needed - erase to end of line.

此代码按预期工作.

import sys
for t in ['long line', '%']:
    sys.stdout.write('\033[K' + t + '\r')
sys.stdout.write('\n')


注意,当字符串包含制表符时,这不起作用,您可能需要替换:


Note, this doesn't work when the string includes tabs, you may want to replace:

sys.stdout.write('\033[K' + t + '\r') with ...

sys.stdout.write('\033[K' + t.expandtabs(2) + '\r')

这篇关于Python:如何在同一行打印,清除以前的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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