How to print progress on the same line in Python?

How can I print on the same line in Python?

I want to create a script that outputs progress on the same line, like this:

Installing XXX...               [DONE]

Currently, I print Installing XXX... first, followed by [DONE] on the next line. How can I adjust the script to print both messages on the same line, one at a time, without overwriting or breaking the formatting?

Hey, if you want to avoid line breaks in Python’s print() function, you can use the end parameter. By default, it adds a newline, but you can change that. For example, you can make a message print on the same line like this:

print("Installing XXX...", end=" ")  
# Later in the script  
print("[DONE]")

This will print: Installing XXX... [DONE] It’s super handy when you want to continue printing on the same line.

That’s a good start! But if you need even more control over the output, consider using sys.stdout.write(). Unlike print(), it doesn’t automatically add a newline, so you have full control over what gets printed and when. Here’s an example:

import sys  
sys.stdout.write("Installing XXX...")  
sys.stdout.flush()  
# After completing the task  
sys.stdout.write(" [DONE]\n")

Make sure to call flush() if you want the text to appear right away. This method gives you more flexibility than print() for dynamic updates.

Nice, I like that approach! But if you really want to update the same line repeatedly, like in a progress bar, you should use the carriage return \r. It allows you to overwrite the line entirely, making it perfect for dynamic updates. For instance:

import time  
print("Installing XXX...", end="\r")  
time.sleep(2)  # Simulate installation time  
print("Installing XXX... [DONE]")

The \r moves the cursor back to the beginning of the line, and the new text will overwrite the old one, so you get a smooth update on the same line without any extra characters.