How to replace string from previous line using \r (Python) [duplicate]

…衆ロ難τιáo~ 提交于 2019-12-11 12:22:51

问题


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

... etc

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

Here's my code:

from __future__ import division
import sys, time 

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

回答1:


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.

The code:

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


来源:https://stackoverflow.com/questions/25752932/how-to-replace-string-from-previous-line-using-r-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!