How to overwrite the previous print to stdout in python?

Posted on

Solving problem is about exposing yourself to as many situations as possible like How to overwrite the previous print to stdout in python? and practice these strategies over and over. With time, it becomes second nature and a natural way you approach any problems in general. Big or small, always start with a plan, use other strategies mentioned here till you are confident and ready to code the solution.
In this post, my aim is to share an overview the topic about How to overwrite the previous print to stdout in python?, which can be followed any time. Take easy to follow this discuss.

How to overwrite the previous print to stdout in python?

If I had the following code:

for x in range(10):
     print x

I would get the output of


What I would like to do is instead of printing a newline, I want to replace the previous value and overwrite it with the new value on the same line.

Asked By: ccwhite1


Answer #1:

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')

Python 2.7 forward compatible

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

Python 2.7

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

Python 2.0-2.6

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

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[1Kr')
Answered By: Mike DeSimone

Answer #2:

Since I ended up here via Google but am using Python 3, here’s how this would work in Python 3:

for x in range(10):
    print("Progress {:2.1%}".format(x / 10), end="r")

Related answer here: How can I suppress the newline after a print statement?

Answered By: Pascal

Answer #3:

@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[2Kr',

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.

Answered By: Nagasaki45

Answer #4:

I had the same question before visiting this thread. For me the sys.stdout.write worked only if I properly flush the buffer i.e.

for x in range(10):

Without flushing, the result is printed only at the end out the script

Answered By: user2793078

Answer #5:

Suppress the newline and print r.

print 1,
print 'r2'

or write to stdout:


Answer #6:

for x in range(10):
    time.sleep(0.5) # shows how its working
    print("r {}".format(x), end="")

time.sleep(0.5) is to show how previous output is erased and new output is printed
“r” when its at the start of print message , it gonna erase previous output before new output.

Answered By: Rubixred

Answer #7:

Try this:

import time
while True:
    print("Hi ", end="r")
    print("Bob", end="r")

It worked for me. The end="r" part is making it overwrite the previous line.


If you print out hi, then print out hello using r, you’ll get hillo because the output wrote over the previous two letters. If you print out hi with spaces (which don’t show up here), then it will output hi. To fix this, print out spaces using r.

Answered By: Sam Bernstein

Answer #8:

I couldn’t get any of the solutions on this page to work for IPython, but a slight variation on @Mike-Desimone’s solution did the job: instead of terminating the line with the carriage return, start the line with the carriage return:

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

Additionally, this approach doesn’t require the second print statement.

Answered By: David Marx

Leave a Reply

Your email address will not be published. Required fields are marked *