Summary: The most straightforward way to overwrite the previous print to stdout is to set the carriage return (
'\r') character within the print statement as
print(string, end = "\r"). This returns the next stdout line to the beginning of the line without proceeding to the next line.
Problem Definition: How will you overwrite the previous print/output to stdout in Python?
Example: Let’s say you have the following snippet, which prints the output as shown below:
import time for i in range(10): if i % 2 == 0: print(i) time.sleep(2)
Challenge: What we want to do is instead of printing each output in a newline, we want to replace the previous output value and overwrite it with the new output value on the same line, as shown below.
📍Recommended Read: [FIXED] Carriage return Not Working with Print in VS Code
Method 1: Using Carriage Return (‘\r’) Character
Approach: The simplest solution to the given problem is to use the carriage return (‘
\r‘) character within your print statement to return the stdout to the start of the same print line without advancing to the next line. This leads to the next print statement overwriting the previous print statement.
📌Note: Read here to learn more about the carriage return escape character.
import time for i in range(10): if i % 2 == 0: print(i, end="\r") time.sleep(2)
That’s easy! Isn’t it? Unfortunately, this approach is not completely foolproof. Let’s see what happens when we execute the following snippet:
import time li = ['start', 'Processing result'] for i in range(len(li)): print(li[i], end='\r') time.sleep(2) print('Terminate')
print('Terminate') is unable to completely wipe out the previous output. Hence, the final output is erroneous.
Since we are executing each output generated by a print statement on top of the previous output, it is not possible to display an output properly on the same line if the following output has a shorter length than the output before.
FIX: To fix the above problem, instead of simply overwriting the output, we must clear the previous output before displaying the next output. This can be done with the help of the following ANSI sequence: “\x1b[2K“.
import time li = ['start', 'Processing result'] for i in range(len(li)): print(li[i], end='\r') time.sleep(2) print(end='\x1b[2K') # ANSI sequence to clear the line where the cursor is located print('Terminate')
Method 2: Clear Line and Print Using ANSI Escape Sequence
Approach: The idea here is to use an extra print statement instead of altering the
end parameter of the print statement that is used to display the output. The extra print statement is used to move the cursor back to the previous line where the output was printed and then clear it out with the help of ANSI escape sequences.
- Print a line that ends with a new line initially.
- Just before printing the next output on the new line, perform a couple of operations with the help of ANSI escape sequences:
- Move the cursor up, i.e., to the previous output line using the escape sequence: ‘\033[1A‘.
- Clear the line using the escape sequence: ‘\x1b[2K‘
- Print the next output.
import time UP = '\033[1A' CLEAR = '\x1b[2K' for i in range(10): if i % 2 == 0: print(i) time.sleep(2) print(UP, end=CLEAR)
Discussion: Though this code might look a little more complex than the previous approach, it comes with a major advantage of the neatness of output. You don’t have to worry about the length of the previous output. Also, the cursor does not visually hinder the output being displayed.
Here’s a handy guide to escape sequences with respect to cursor movements:
|ESCAPE SEQUENCE||CURSOR MOVEMENT|
|\033[<L>;<C>H||Positions the cursor. Puts the cursor at line L and column C.|
|\033[<N>A||Move the cursor up by N lines.|
|\033[<N>B||Move the cursor down by N lines.|
|\033[<N>C||Move the cursor forward by N columns.|
|\033[<N>D||Move the cursor backward by N columns.|
|\033[2J||Clear the screen, move to (0,0)|
|\033[K||Erase the end of line.|
Method 3: Using “\b” Character
Another way to overwrite the previous output line is to use the backspace character(“\b“) and write to the standard output.
import time import sys for i in range(10): if i % 2 == 0: sys.stdout.write(str(i)) time.sleep(1) sys.stdout.write('\b') sys.stdout.flush()
Caution: Ensure that you properly flush the buffer as done in the above snippet. Otherwise, you might see that only the last result is displayed at the end of the script.
Bonus Read Ahead 👇
What is Carriage Return (\r) in Python?
Simply put, carriage return is an escape character just like
\n. Carriage return is denoted as
\r and it is basically used to shift the cursor to the beginning of a line or string instead of allowing it to move on to the next line.
Whenever you use the carriage return escape character ‘\r’, the content that comes after the \r will appear on top of your line and will keep replacing the characters of the previous string one by one until it occupies all the contents left after the
\r in that string.
li = ['One', 'Two', 'Three'] for i in range(len(li)): print(li[i], end='\r') # OUTPUT-->Three
To sum things up, the easiest way to overwrite the previous print is to use the carriage return
\r character within your print statement using the end parameter. To ensure that the previous output is completely erased before printing the new output, you can use the
\x1b[2K ANSI escape sequence.
I hope this tutorial helped you. Here’s another interesting read that you may find useful: Python Print One Line List
- One of the most sought-after skills on Fiverr and Upwork is web scraping. Make no mistake: extracting data programmatically from websites is a critical life skill in today’s world that’s shaped by the web and remote work.
- So, do you want to master the art of web scraping using Python’s BeautifulSoup?
- If the answer is yes – this course will take you from beginner to expert in Web Scraping.