Remove and Replace Printed items

PythonPython 3.xPrintingPython 3.2

Python Problem Overview


I was wondering if it was possible to remove items you have printed in Python - not from the Python GUI, but from the command prompt. e.g.

a = 0  
for x in range (0,3):  
    a = a + 1  
    b = ("Loading" + "." * a)
print (a)

so it prints

>>>Loading   
>>>Loading. 
>>>Loading.. 
>>>Loading...

But, my problem is I want this all on one line, and for it it remove it self when something else comes along. So instead of printing "Loading", "Loading.", "Loading... I want it to print "Loading.", then it removes what is on the line and replaces it with "Loading.." and then removes "Loading.." and replaces it (on the same line) with "Loading...". It's kind of hard to describe.

p.s I have tried to use the Backspace character but it doesn't seem to work ("\b")

Python Solutions


Solution 1 - Python

Just use CR to go to beginning of the line.

import time
for x in range (0,5):  
    b = "Loading" + "." * x
    print (b, end="\r")
    time.sleep(1)

Solution 2 - Python

One way is to use ANSI escape sequences:

import sys
import time
for i in range(10):
    print("Loading" + "." * i)
    sys.stdout.write("\033[F") # Cursor up one line
    time.sleep(1)

Also sometimes useful (for example if you print something shorter than before):

sys.stdout.write("\033[K") # Clear to the end of line

Solution 3 - Python

import sys
import time

a = 0  
for x in range (0,3):  
    a = a + 1  
    b = ("Loading" + "." * a)
    # \r prints a carriage return first, so `b` is printed on top of the previous line.
    sys.stdout.write('\r'+b)
    time.sleep(0.5)
print (a)

Note that you might have to run sys.stdout.flush() right after sys.stdout.write('\r'+b) depending on which console you are doing the printing to have the results printed when requested without any buffering.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlex View Question on Stackoverflow
Solution 1 - PythonKeithView Answer on Stackoverflow
Solution 2 - PythonSven MarnachView Answer on Stackoverflow
Solution 3 - PythonunutbuView Answer on Stackoverflow