【问题标题】:Replacing a character within a print function without using .replace在不使用 .replace 的情况下替换打印函数中的字符
【发布时间】:2020-06-05 02:55:18
【问题描述】:

我是编程新手,有一个关于在 Python 中替换打印函数中的文本的问题。

在我当前的代码中,为了倒计时,如果你输入 5,它会打印“5431GO”,我怎样才能让它替换前一个字符?我以前做过,但我忘记了,我认为这与“\r”有关?

import time

countdown_time = int(input("Enter amount of seconds to count down from: "))
while countdown_time >= 0:
    if countdown_time == 0:
        print("GO")
        break
    else:
        print(countdown_time, end="")
        countdown_time -= 1
        time.sleep(.5)

【问题讨论】:

  • 是的,\r 是回车。它转到行首而不转到下一行。

标签: python python-3.x string replace character


【解决方案1】:

正如您所说,\r 意味着它将指针移动到行首,只需在您的 print 语句中使用它,如下所示:

import time

countdown_time = int(input("Enter amount of seconds to count down from: "))
while countdown_time >= 0:
    if countdown_time == 0:
        print("GO")
        break
    else:
        print(countdown_time, end="\r")
        countdown_time -= 1
        time.sleep(.5)

【讨论】:

  • 谢谢我的想法,但是当我这样做时,直到时间结束才打印任何文本,然后打印出来,你知道为什么会这样吗?
  • @KevinNisbet 嗯,不知道是什么问题,也许尝试在没有 IDE 的情况下运行它。他们有时会弄乱终端。
  • 可能希望打印语句为 print(f"{countdown_time}......", end="\r"),以便完全覆盖以前的数字,否则计数将从 10 变为 90。print(str(countdown_time) + "......", end="\r") 也可以。
  • 啊,是的,我用记事本运行它,它有点工作,我的新问题是现在如果输入是“10”,它会用“10”的“1”替换“9” " 我得到 "90" :(
  • @KevinNisbet,如果它解决了您的问题,请考虑选择它作为接受的答案。
【解决方案2】:

我使用这个函数来更新内联百分比文本。只需调用update_percentage 而不是print

def update_percentage(row_string):
    row_string = str(row_string)

    # clear previous text
    sys.stdout.write("\r")
    sys.stdout.write(" " * len(row_string))

    # reposition at the start of the row
    sys.stdout.write("\r")
    sys.stdout.write(row_string)
    sys.stdout.flush()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    • 2013-11-19
    • 2015-07-18
    • 2021-12-03
    • 2015-02-12
    • 1970-01-01
    • 2019-04-07
    相关资源
    最近更新 更多