How can I print multiple things on the same line, one at a time?
Python 3.0 and above: Use print(…, end='')
. This end=''
argument replaces the default newline character.
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 (''
).
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.
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.
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.
Carriage return for overwriting
Bamboozle Python into overwriting previous output with the carriage return character ("\r"
). Perfect for progress bars or a ticking clock.
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.
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'
?
Was this article helpful?