python - while 循环覆盖结果

标签 python python-3.x loops while-loop python-3.7

我正在编写简单的倒计时代码,但无法覆盖时间。 结果以一行形式出现(如 00:00:0200:00:01),我希望将其堆叠起来,看起来像一个实际的时钟

print(time_left,end="")

这是我所做的,我将 \r 设为

print("time_left + "\r", end="")

没有成功

import time
while True:
    uin = input(">> ")
    try:
            when_to_stop = abs(int(uin))
    except KeyboardInterrupt:
            break
    except:
            print("Not a number!")

while when_to_stop > 0:
        m, s = divmod(when_to_stop, 60)
        h, m = divmod(m, 60)

           #.zfill(2) to make 00:00:00 form
        time_left = str(h).zfill(2) + ":" + str(m).zfill(2) + ":" + str(s).zfill(2)
        print(time_left + '\r', + end="")
        time.sleep(1)
        when_to_stop -= 1 

print()

最佳答案

您需要使用

print(time_left,end='\r')

end='\r' 将光标返回到行的开头。因此,当您再次打印相同的内容时,它会被覆盖。

关于python - while 循环覆盖结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57471971/

相关文章:

python - 从 Dict 继承子类违反了 python 中面向对象编程的基本规则

python - 在 Anaconda 中,如何在非 ROOT 环境下安装软件包?

Python文件操作

python - Heroku & Django : "OSError: No such file or directory: '/app/{myappname}/static'"

python - 调试python3中无效的utf-8字符

python-3.x - 将 aiohttp 请求与其响应相关联

python - 如何更改 matplotlib - spyder 中的默认绘图颜色?

python - 如何遍历python中的矩阵列

javascript - 等待循环结束然后在 Javascript 中执行操作的最优雅的方法是什么?

java - 使用线程循环更新 JFrame