ccwhite1 ccwhite1 - 1 year ago 285
Python Question

python: how to overwrite the previous print to stdout

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.

Answer Source

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

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download