How to overwrite the previous print to stdout in python?

后端 未结 16 1579
别那么骄傲
别那么骄傲 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:31

    @Mike DeSimone answer will probably work most of the time. But...

    for x in ['abc', 1]:
        print '{}\r'.format(x),
    
    -> 1bc
    

    This is because the '\r' only goes back to the beginning of the line but doesn't clear the output.

    EDIT: Better solution (than my old proposal below)

    If POSIX support is enough for you, the following would clear the current line and leave the cursor at its beginning:

    print '\x1b[2K\r',
    

    It uses ANSI escape code to clear the terminal line. More info can be found in wikipedia and in this great talk.

    Old answer

    The (not so good) solution I've found looks like this:

    last_x = ''
    for x in ['abc', 1]:
        print ' ' * len(str(last_x)) + '\r',
        print '{}\r'.format(x),
        last_x = x
    
    -> 1
    

    One advantage is that it will work on windows too.

提交回复
热议问题