multiple prints on the same line in Python

前端 未结 17 2482
独厮守ぢ
独厮守ぢ 2020-11-22 06:06

I want to run a script, which basically shows an output like this:

Installing XXX...               [DONE]

Currently, I print Installi

17条回答
  •  天涯浪人
    2020-11-22 06:25

    Here a 2.7-compatible version derived from the 3.0 version by @Vadim-Zin4uk:

    Python 2

    import time
    
    for i in range(101):                        # for 0 to 100
        s = str(i) + '%'                        # string for output
        print '{0}\r'.format(s),                # just print and flush
    
        time.sleep(0.2)
    

    For that matter, the 3.0 solution provided looks a little bloated. For example, the backspace method doesn't make use of the integer argument and could probably be done away with altogether.

    Python 3

    import time
    
    for i in range(101):                        # for 0 to 100
        s = str(i) + '%'                        # string for output
        print('{0}\r'.format(s), end='')        # just print and flush
    
        time.sleep(0.2)                         # sleep for 200ms
    

    Both have been tested and work.

提交回复
热议问题