2

I want to erase character or line from terminal in Python.

For example, I printed "Hello World" using print("Hello World"). And then I used time.sleep(3) to wait 3 seconds. Then I want to delete one character in terminal, so terminal will be Hello Worl.

So, what I want for result is:

  1. When I start my program, Hello World prints.
  2. And program sleeps 3 seconds.
  3. Then text in terminal changes to Hello Worl.

And also, I found some solutions from SO, and write = sys.stdout.write, write("\b") but this prints <0x08>.

Is there any way to delete character or line in terminal?

I'm using Python 3.8 and Windows 10. Thanks!

Superjay
  • 317
  • 2
  • 13

2 Answers2

2

You can do this by using end='\r' for your print statement. \r makes the cursor stay on the same row, so you can overwrite it.

from time import sleep

print("Hello world", end='\r')
sleep(3)
print("Hello worl ")
M Z
  • 4,192
  • 1
  • 11
  • 24
  • This works fine, but what if I want to print several lines and erase it at once? In your code, I can overwrite only very last line. – Superjay Feb 02 '21 at 11:24
2

You should note that the print function ends with a newline by default. To keep the cursor at the end of the line you printed, you should use the end parameter inside the print function:

print("Hello World", end="", flush=True)    # Edited

The reason for using end = '' is to make the print function end with no new character rather than using the default newline.

For the next step, you can use write = sys.stdout.write as you mentioned from the other question, and to avoid any problems in printing spare characters, you can make sure to use write("\b \b").

The complete code can be written as follows:

import sys, time 

print("Hello World", end="")

time.sleep(3)
write = sys.stdout.write
write('\b \b')

You could also use sys.stdout.write instead of print function. As far as I know, one of the main differences between these two is that print forces you to start from a new line by default. However, with the above solution and using end = '' there are no concerns anymore.

Mahdi
  • 131
  • 3
  • Thank you for answering, but when I run your code, it just print "Hello Worl" after 3 seconds. What I want is print "Hello World" on start and after 3sec, text should be change to "Hello Worl". – Superjay Feb 02 '21 at 11:22
  • @JayLee Oops! That's right! You should use `print("Hello World", end="", flush=True)` so that the buffered string gets printed on the terminal, and then you're good to go, and the code will work as you expect. – Mahdi Feb 02 '21 at 15:11