简体   繁体   English

print() 中的结束参数 function

[英]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' .在打印调用中(第 6 行)是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. \r是一个回车符,因此不是以换行符 ( \n ) 结尾(这将导致每个打印语句在新行上发出),每个打印语句都会覆盖前一个。

In python, \r in a string stands for the carriage return character.在 python 中,字符串中的\r代表回车符。 It does reset the position of the cursor to the start of the current line.它确实将 cursor 的 position 重置为当前行的开头。 The end argument in the print function is the string that is printed after the given text.打印 function 中的结束参数是在给定文本之后打印的字符串。 By default, this is \n , a newline character.默认情况下,这是\n ,一个换行符。

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.因此,打印 function 的 end 参数设置为\r ,这样 cursor 就会移动到行尾。 This makes thet the new time is printed over the new one.这使得新时间打印在新时间上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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