Print \r correctly in console

后端 未结 2 1830
無奈伤痛
無奈伤痛 2021-01-22 10:09

When I write a script that updates a printed line, for example like this:

for i in range(101):
    print(str(i) + \"% \\r\", end=\"\")

and run

2条回答
  •  忘掉有多难
    2021-01-22 10:31

    This is because 'print' always generates a new line whenever you use \r or not, try sys.stdout instead:

    import time, sys
    
    for i in range(101):
        sys.stdout.write(str(i) + "% \r")
        sys.stdout.flush()
        time.sleep(.3)
    

提交回复
热议问题