在不使用.replace的情况下替换打印功能中的字符

问题描述 投票:1回答:1

我是编程新手,对于在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)
python python-3.x string replace character
1个回答
2
投票

完全像您所说的,\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)
© www.soinside.com 2019 - 2024. All rights reserved.