【问题标题】:How can I overwrite the last printed character in Python如何覆盖 Python 中最后一个打印的字符
【发布时间】:2020-03-20 03:28:20
【问题描述】:

我看过所有这些以及更多,这不是重复的! (好吧,但我需要一个答案)。

How to overwrite multiline print in Python?

How can I remove last printed line in python?

Output to the same line overwriting previous output?

Overwrite the previous print value in python?

但其中甚至没有一个答案实际上会覆盖 Python 3.8 中的打印字符。

那么让我问一下如何在 Python 中覆盖最后打印的字符?

例如在这段代码中:

import time
print("Line one",end="\r")
time.sleep(2)
print ("Line two")

在这段代码中,我希望将“第一行”替换为“第二行”。

或许,

import time 
print("1")
time.sleep(1)
print("2")
time.sleep(1)
print("3")

这样每个数字都替换了最后一个。

【问题讨论】:

  • 为什么需要time 模块?
  • 只是在创建和替换行之间添加一个时间延迟。
  • 你的输出去哪儿了?例如,在 IDLE shell 中,您可以做的绝对 nothing 会导致覆盖先前的输出 - 它只是将字符附加到 Text 小部件。
  • 您的代码对我有用。请注意,第二行至少需要与第一行一样长,否则您仍然会看到第一行的结尾。
  • 确保您在终端模拟器中运行代码,而不是像 IDLE 这样的调试器。

标签: python


【解决方案1】:

最重要的是,我赞成你以'\r'结尾的打印方法,这种方法是正确的,但无法在代码编辑器中显示你想要的结果,例如'sublime text3'。

其实这个方法可以在Cmd中显示正确的结果。以下是三个示例,希望对您有所帮助。

import time 
print("EXAMPLE I")
print("Line one",end="\r")
time.sleep(1)
print("Line two")

如果在代码编辑器中,会显示:

EXAMPLE I
Line one
Line two

也许你会认为这个结果和'\n'一样。但事实并非如此。如果我们在Cmd中运行它会显示这些结果:

EXAMPLE I
Line two

很神奇吗?事实上,第一行已经被第二行取代,达到了你的目的。

顺便说一下,我可以告诉你上面cmets中提到的另一种方式。

print("EXAMPLE II")
print("Line one",end="\n")
time.sleep(1)
print("Line two")

在代码编辑器中

EXAMPLE II
Line one
Line two

在 Cmd 中

EXAMPLE II
Line one
Line two

代码

print("EXAMPLE III")
print("Line one",end="\b")
time.sleep(1)
print("Line two")

在代码编辑器中

Line one<0x08>Line two

在 Cmd 中

Line onLine two

多加注意:'\b' 结尾只能支持一个单词,而不是整行。 您可能会看到 CMD 和代码编辑器之间的区别。

【讨论】:

    猜你喜欢
    • 2022-11-20
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多