微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python用另一条指定的行覆盖一行

如何解决Python用另一条指定的行覆盖一行

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

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

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

在此代码示例中,第一行将被第二行覆盖,但我不希望那样。我希望第一行会被 第三 行覆盖

解决方法

您可以使用 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")
,

您必须使用条件语句。 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')

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

,

为此目的使用 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")

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。