【问题标题】:Python overwrite a line with another specified linePython用另一个指定的行覆盖一行
【发布时间】:2021-06-24 00:23:45
【问题描述】:

如何用另一个特定的打印输出覆盖打印输出?例如:

print("Overwrite this line", end="\r")
print("I do not want to overwrite any line")
print("I want to overwrite the first line")

如何用third print 语句覆盖first print 语句? 我想用第三行替换第一行。第二行应保持原样。

在此代码示例中,第一行将被第二行覆盖,但我不想这样做。我希望第一行会被 third one

覆盖

【问题讨论】:

标签: python overwrite


【解决方案1】:

您必须使用条件语句。例如 if 语句:

choice = input('what do you want to display? 1 or 2')

if choice == '1' then:
    print('I want to overwrite the first line')
else:
    print('I do not want to overwrite any line')

这是否回答了您的问题?如果不是,请详细说明。

【讨论】:

  • 这没有覆盖先前打印行的元素。它没有回答问题
  • 如果条件在这里没有用,我希望它在没有任何条件的情况下以任何一种方式打印。
【解决方案2】:

你可以使用ANSI escape sequences,只要你的终端支持它们(Linux上就是这种情况,我不确定Windows)

这个问题特别有趣的是:

  • \033[<N>A - 将光标向上移动 N 行
  • \033[<N>B - 将光标向下移动 N 行

您可以正常打印前两行,然后将第三行向上移动 2 行,打印它(这将打印一个换行符并将光标移动到第二行),向下移动 1 行并继续执行您的代码。我在代码中插入了一些延迟,以便效果可见:

print("Overwrite this line")
time.sleep(1)
print("I do not want to overwrite any line")
time.sleep(1)
print("\033[2AI want to overwrite the first line\033[1B")

【讨论】:

  • 谢谢!对于那些想知道为什么它还会覆盖您要覆盖的行下方的文本的人,请确保使用\033[<N>B 使光标在它上升后下降,正如这个答案所暗示的那样。
  • 对于那些想要覆盖比要替换它的字符串更长的字符串的人,您可以使用空格,因为它们算作字符串。例如print("bla bla" + " "*N)
【解决方案3】:

为此目的使用escape sequence \r。等待使用time.sleep

import time

print("Overwrite this line", end="")
time.sleep(10)
print("\rI want to overwrite the first line")
print("I do not want to overwrite any line")

为了更精确的结果wait for key press。并查看此代码:

import msvcrt as m
def wait():
    m.getch()

print("Overwrite this line", end="")
wait()
print("\rI want to overwrite the first line")
print("I do not want to overwrite any line")

【讨论】:

  • 第三行没有覆盖第一行
  • 嗯,你改变了行的含义,让它看起来像它工作......第二行说“我不想想要覆盖任何行" 第三个说"我想要覆盖第一行"。您的代码正在做相反的事情
  • @ExplooreX 我想按顺序用第三行覆盖第一行。打印语句必须保持顺序,这意味着它们必须按顺序打印。
  • @AaravPrasad 我可以回答吗,使用逻辑first clear then reprint it
猜你喜欢
  • 2020-03-27
  • 2012-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-16
  • 1970-01-01
  • 1970-01-01
  • 2020-04-25
相关资源
最近更新 更多