Explain Codes LogoExplain Codes Logo

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

python
prompt-engineering
functions
best-practices
Alex KataevbyAlex Kataev·Jan 20, 2025
TLDR

Python 3.0 and above: Use print(…, end=''). This end='' argument replaces the default newline character.

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

This will print: Hello World on a single line. Narwhals rejoice! 🐳

Printing without a newline in Python 3

In Python 3, the print() function has a parameter called end. By default, end is \n, representing a newline. This means after each print() call, it goes to the next line. But what if we want it all in a single line? We set end to an empty string ('').

print("First print call", end='') print(" Second print call")

Using flush in print function in Python 3

In Python, the print() function buffers its output. This may result in incomplete chunks of data when you're outputting iteratively. Using flush=True forces the buffer to get flushed.

print("Processing...", end="", flush=True)

You have the power now. Buffering won't keep you waiting anymore! 💪

Printing without a newline in Python 2

Backward at we are, hmm? Well, for Python 2, just add a comma at the end of your print statement.

print "Processing...",

Do keep in mind this approach drops a newline but adds a trailing space. It's like Python 2 saying "Take that" for not upgrading.

Making use of sys.stdout.write()

If you want more control over the printing process or want to dodge the trailing space in Python 2, use sys.stdout.write(). Use sys.stdout.flush() to force the output to appear immediately.

import sys sys.stdout.write("Processing...") sys.stdout.flush()

Carriage return for overwriting

Bamboozle Python into overwriting previous output with the carriage return character ("\r"). Perfect for progress bars or a ticking clock.

print("3...2...1... Wait, let's start again!", end="\r")

This is like a "Get out of jail free" card when you make a mistake. (Monopoly fans, anyone?)

Clever backspacing

When printing character by character, use '\x08' to move a step back. It's like the Ctrl + Z of programming.

import time print("Loading", end='') for _ in range(10): print('.', end='', flush=True) time.sleep(0.5) # Just chilling for half a second print('\x08', end='', flush=True) #Oops! Backspace

Crafting custom printing sequences

Sometimes, the simple print() function just doesn't cut it. You need more control. So, why not combine sys.stdout.write() and '\r'?

import sys sys.stdout.write("Loading...\r")