How can I print multiple things on the same line, one at a time?

ghz 6months ago ⋅ 147 views

I want to run a script, which basically shows an output like this:

Installing XXX...               [DONE]

Currently, I print Installing XXX... first and then I print [DONE].

How can I instead print Installing xxx... and [DONE] on the same line?

Answers

To print Installing XXX... and [DONE] on the same line, you can use the end parameter of the print function to avoid adding a newline character. Here's an example:

import time

# Simulate installation process
print("Installing XXX...", end='', flush=True)
time.sleep(2)  # Simulate some delay
print(" [DONE]")

In this example, end='' in the first print statement ensures that the next output will be printed on the same line. The flush=True argument forces the buffer to flush, ensuring that the text is displayed immediately. The time.sleep(2) is just to simulate a delay, representing the time taken for the installation process.

When you run this script, it will print Installing XXX..., wait for 2 seconds, and then append [DONE] on the same line.