How to Overwrite the Previous Print to Stdout in Python?

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 Formulation

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)

Output:

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.

Expected Output

Video Walkthrough

πŸ“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.

Code:

import time

for i in range(10):
    if i % 2 == 0:
        print(i, end="\r")
        time.sleep(2)  

Output:

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

Output:

⚠️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“.

Code:

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

Output:

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.

Explanation:

  • 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:
    1. Move the cursor up, i.e., to the previous output line using the escape sequence: ‘\033[1A‘.
    2. Clear the line using the escape sequence: ‘\x1b[2K
  • Print the next output.

Code:

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)

Output:

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 SEQUENCECURSOR MOVEMENT
\033[<L>;<C>HPositions the cursor. Puts the cursor at line L and column C.
\033[<N>AMove the cursor up by N lines.
\033[<N>BMove the cursor down by N lines.
\033[<N>CMove the cursor forward by N columns.
\033[<N>DMove the cursor backward by N columns.
\033[2JClear the screen, move to (0,0)
\033[KErase 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.

Code:

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

Output:

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.

Example:

li = ['One', 'Two', 'Three']
for i in range(len(li)):
    print(li[i], end='\r')

# OUTPUT-->Three

Conclusion

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.