snippetpythonCritical
How to print without a newline or space
Viewed 0 times
howspacenewlineprintwithout
Problem
Consider these examples using
Either a newline or a space is added between each value. How can I avoid that, so that the output is
print in Python:>>> for i in range(4): print('.')
.
.
.
.
>>> print('.', '.', '.', '.')
. . . .
Either a newline or a space is added between each value. How can I avoid that, so that the output is
.... instead? In other words, how can I "append" strings to the standard output stream?Solution
In Python 3, you can use the
To not add a newline to the end of the string:
To not add a space between all the function arguments you want to print:
You can pass any string to either parameter, and you can use both parameters at the same time.
If you are having trouble with buffering, you can flush the output by adding
Python 2.6 and 2.7
From Python 2.6 you can either import the
which allows you to use the Python 3 solution above.
However, note that the
Or you can use
You may also need to call
to ensure
sep= and end= parameters of the print function:To not add a newline to the end of the string:
print('.', end='')To not add a space between all the function arguments you want to print:
print('a', 'b', 'c', sep='')You can pass any string to either parameter, and you can use both parameters at the same time.
If you are having trouble with buffering, you can flush the output by adding
flush=True keyword argument:print('.', end='', flush=True)Python 2.6 and 2.7
From Python 2.6 you can either import the
print function from Python 3 using the __future__ module:from __future__ import print_functionwhich allows you to use the Python 3 solution above.
However, note that the
flush keyword is not available in the version of the print function imported from __future__ in Python 2; it only works in Python 3, more specifically 3.3 and later. In earlier versions you'll still need to flush manually with a call to sys.stdout.flush(). You'll also have to rewrite all other print statements in the file where you do this import.Or you can use
sys.stdout.write()import sys
sys.stdout.write('.')You may also need to call
sys.stdout.flush()to ensure
stdout is flushed immediately.Code Snippets
print('.', end='')print('a', 'b', 'c', sep='')print('.', end='', flush=True)from __future__ import print_functionimport sys
sys.stdout.write('.')Context
Stack Overflow Q#493386, score: 3420
Revisions (0)
No revisions yet.