Consider these examples using 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?
In Python 3, you can use the
sep=andend=parameters of theprintfunction: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
flush=Truekeyword argument:Python 2.6 and 2.7
From Python 2.6 you can either import the
printfunction from Python 3 using the__future__module:which allows you to use the Python 3 solution above.
However, note that the
flushkeyword is not available in the version of theprintfunction 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 tosys.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()You may also need to call
to ensure
stdoutis flushed immediately.