如何使用\r替换上一行的字符串(Python) [英] How to replace string from previous line using \r (Python)

查看:212
本文介绍了如何使用\r替换上一行的字符串(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试使倒数计时器从60秒开始。我唯一的问题是,当我运行该函数时,程序将按以下方式打印代码:

I'm attempting to make a countdown timer starting from 60 seconds. My only problem is that when I run the function, the program prints the code like so:

60

59

58

...等等

我该如何从第一行替换60行并将59放到原处而不打印60行?

How would I go about replacing the 60 from that first line and put the 59 in it's place without printing 60 lines?

这是我的代码:

from __future__ import division
import sys, time 

def countdown():
    seconds = 60
    while seconds >= 0:
        print seconds
        sys.stdout.flush()
        time.sleep(1)
        seconds -= 1


推荐答案

的开头打印空行倒计时功能。这将创建 \r 工作所需的行。现在,将 print seconds 部分替换为

Print an empty line at the beginning of your countdown function. This will create the line needed for \r to work. Now, replace the print seconds part with

sys.stdout.write('\r  \r')
sys.stdout.write(str(seconds))

第一行清除函数开头打印的前一个空行。第二个输出秒。

The first line clears the previous, empty line printed at the beginning of the function. The second one outputs the seconds.

代码:

def countdown():
    seconds = 60
    print ''
    while seconds >= 0:
        sys.stdout.write('\r  \r')
        sys.stdout.write(str(seconds))
        sys.stdout.flush()
        time.sleep(1)
        seconds -= 1

这篇关于如何使用\r替换上一行的字符串(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆