How to print without a newline or space
In Python 3, you can use the
end= parameters of 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:
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
from __future__ import print_function
which allows you to use the Python 3 solution above.
However, note that the
flush keyword is not available in the version of the
__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
You may also need to call
stdout is flushed immediately.
Is it possible to print something, but not automatically have acarriage return appended to it?
Yes, append a comma after the last argument to print. For instance, this loop prints the numbers 0..9 on a line separated by spaces. Note the parameterless "print" that adds the final newline:
for i in range(10): print i,else: print...0 1 2 3 4 5 6 7 8 9>>>
Note: The title of this question used to be something like "How to printf in Python"
Since people may come here looking for it based on the title, Python also supports printf-style substitution:
"one", "two", "three" ]>>>for i in xrange(3): print "Item %d: %s" % (i, strings[i])...Item 0: oneItem 1: twoItem 2: threestrings = [
And, you can handily multiply string values:
print "." * 10..........