简体   繁体   中英

End parameter in print() function

I'm looking at this code:

import time   
def countdown(t):
    while t:
        mins, secs = divmod(t,60)
        timer = '{:02d}:{:02d}'.format(mins,secs)
        print(timer, end='\r')
        time.sleep(1)
        t-=1
    print("Timer is completed")
t=input('Enter the time in seconds: ')
countdown(int(t))

In the print call (on line 6) is end='\r' . What does this indicate or do in the program?

The \r is a carriage return character, so instead of ending with a newline ( \n ) (which would cause each print statement to issue on a new line), each print statement overwrites the previous one.

In python, \r in a string stands for the carriage return character. It does reset the position of the cursor to the start of the current line. The end argument in the print function is the string that is printed after the given text. By default, this is \n , a newline character.

In the timer we do want that the new time overwrites the previous one, not that the new time is printed after the previous one. Thus, the end argument of the print function is set to \r , such that the cursor is moved to the back of the line. This makes thet the new time is printed over the new one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM