How to print without a newline or space
To avoid newline or space in Python's print()
function, use end=''
like so:
Output: Part1Part2
, and yep, no newline or space.
Want your output flushed out straight away? Add a pinch of flush=True
:
Advanced printing techniques
Newline? Not in Python 2!
In Python 2, stifling newlines might seem challenging but it's really not. Just add a sneaky comma after your print statement. Alternatively, bring in sys.stdout.write()
for some extra muscle:
Buffer? What buffer?
Print and forget buffered outputs with this charming trio:
No spaces? Easy peasy!
To marry multiple strings with no spaces in between, use sep=''
, like Romeo and Juliet without the space of that annoying wall:
Printing nuances: Tricks up your print
The tale of the changing print
The story of Python's print
function is one of constant evolution. From Python 3.3 onwards, you can control output buffering using flush
. For those stuck in Python 2.7 or the early 3.x versions, you need to manually roll out sys.stdout.flush()
. Yeah, we feel you!
Concatenating strings: All joined at the hip
When concatenating strings without spaces, use the +
operator, and for repeating sequences, 'string' * n
will do the trick. It's really as simple as 1 + 1 = 11. Yup, you read it right!
Loops, formatting, and the works
Looping efficiently is the lifeblood of printing. Use looping with the magic of string formatting, and your printing jobs are sorted for life:
Printf-style formatting with %
is handy for string interpolation. Alternatively, str.format() or f-strings in Python 3.6+ give you more readable code:
Printing in loops: Continue the flow
When you use print()
without any arguments, it adds a single newline—perfect for halting the loop party for a moment:
Was this article helpful?