删除和替换打印的项目

新手上路,请多包涵

我想知道是否可以删除您用 Python 打印的项目——不是从 Python GUI 中,而是从命令提示符中。例如

a = 0
for x in range (0,3):
    a = a + 1
    b = ("Loading" + "." * a)
print (a)

所以它打印

>>>Loading
>>>Loading.
>>>Loading..
>>>Loading...

但是,我的问题是我希望这一切都在一条线上,并且当其他事情出现时它会自行删除它。 So instead of printing "Loading", "Loading.", "Loading... I want it to print "Loading." , then it removes what is on the line and replaces it with "Loading.." and then removes "Loading.." 并将其(在同一行)替换为 "Loading..." 。这有点难以描述。

ps 我试过使用 Backspace 字符,但它似乎不起作用( "\b"

原文由 Alex 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 284
2 个回答

只需使用 CR 即可转到行首。

 import time
for x in range (0,5):
    b = "Loading" + "." * x
    print (b, end="\r")
    time.sleep(1)

原文由 Keith 发布,翻译遵循 CC BY-SA 3.0 许可协议

一种方法是使用 ANSI 转义序列

 import sys
import time
for i in range(10):
    print("Loading" + "." * i)
    sys.stdout.write("\033[F") # Cursor up one line
    time.sleep(1)

有时也很有用(例如,如果您打印的内容比以前短):

 sys.stdout.write("\033[K") # Clear to the end of line

原文由 Sven Marnach 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题