How to reset cursor to the beginning of the same line in Python

后端 未结 6 1299
暖寄归人
暖寄归人 2020-12-05 06:48

Most of questions related to this topics here in SO is as follows:

How to print some information on the same line without introducing a new line

6条回答
  •  无人及你
    2020-12-05 07:24

    import sys, time
    
    for i in xrange(0, 101, 10):
      print '\r>> You have finished %d%%' % i,
      sys.stdout.flush()
      time.sleep(2)
    print
    

    The \r is the carriage return. You need the comma at the end of the print statement to avoid automatic newline. Finally sys.stdout.flush() is needed to flush the buffer out to stdout.

    For Python 3, you can use:

    print("\r>> You have finished {}%".format(i), end='')
    

提交回复
热议问题