Unprinting Text in Python: Clearing and Overwriting Output
1. Using \r (Carriage Return)
This moves the cursor to the start of the line, allowing you to overwrite previous output.
import time
for i in range(5, 0, -1):
print(f"\rCountdown: {i} ", end="", flush=True)
time.sleep(1)
print("\rDone! ")
Done!
2. Using ANSI Escape Sequences
Works well in terminals that support ANSI codes.
import time
print("Line 1")
print("Line 2")
time.sleep(1)
print("\033[F\033[K", end="")
Line 1
Line 2
3. Using curses (For Full Terminal Control)
Best for advanced applications like terminal-based UIs.
import curses
def main(stdscr):
stdscr.addstr(0, 0, "Hello, World!")
stdscr.refresh()
stdscr.getch() # Wait for key press
stdscr.clear() # Clears the screen
stdscr.refresh()
stdscr.getch()
curses.wrapper(main)
4. Using os.system("cls" or "clear")
Clears the entire terminal screen.
import os
import time
print("This will be cleared in 2 seconds...")
time.sleep(2)
os.system("cls" if os.name == "nt" else "clear")
This will be cleared in 2 seconds...
5⭐ Python on HackerRank | Data Analytics & Machine Learning Enthusiast
2moCan you or anyone explain what basically is above article about what does it's used for