How to overwrite the previous print to stdout in python?

后端 未结 16 1685
别那么骄傲
别那么骄傲 2020-11-22 09:46

If I had the following code:

for x in range(10):
     print x

I would get the output of

1
2
etc..

What I

16条回答
  •  天命终不由人
    2020-11-22 10:19

    Simple Version

    One way is to use the carriage return ('\r') character to return to the start of the line without advancing to the next line.

    Python 3

    for x in range(10):
        print(x, end='\r')
    print()
    

    Python 2.7 forward compatible

    from __future__ import print_function
    for x in range(10):
        print(x, end='\r')
    print()
    

    Python 2.7

    for x in range(10):
        print '{}\r'.format(x),
    print
    

    Python 2.0-2.6

    for x in range(10):
        print '{0}\r'.format(x),
    print
    

    In the latter two (Python 2-only) cases, the comma at the end of the print statement tells it not to go to the next line. The last print statement advances to the next line so your prompt won't overwrite your final output.

    Line Cleaning

    If you can’t guarantee that the new line of text is not shorter than the existing line, then you just need to add a “clear to end of line” escape sequence, '\x1b[1K' ('\x1b' = ESC):

    for x in range(75):
        print(‘*’ * (75 - x), x, end='\x1b[1K\r')
    print()
    

提交回复
热议问题