Skip to content
Advertisement

How to overwrite previous text in center of screen

I want to print to the center of the terminal and am using:

import shutil

columns = shutil.get_terminal_size().columns
print("hello world".center(columns))

Later on I want to overwrite the text with:

print("hell world".center(columns))

That is the new text should completely replace the old text.

How can you do that?

Advertisement

Answer

You can use print with end and flush parameters

print("hello world".center(columns), end="r", flush=True)

Here is a quick example

import shutil
from time import sleep

columns = shutil.get_terminal_size().columns
print("hello world".center(columns), end="r", flush=True)
sleep(1)
print("This is a test run".center(columns))
print("The previous line was overwritten")
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement