Print without line break


Python 2.x

With Python 2.x, print is a statement. To avoid line break, just append a comma "," at the end of print statement.

while len(arr):
    print "{}".format(arr.pop()),

Another way to avoid the comma in statement is to utilize feature module.

from __future__ import print_function

print("no", end='')
print("break")

The output is nobreak .

Python 3

From Python 3, print is a method. Therefore, a keyword parameter 'end' will work.

while len(arr):
    print ("{} ".format(arr.pop()), end='')

If there are multiple normal parameters (bared parameters without keys) are provided, the keyword parameter 'sep' will take effects.

print ("Start_{}".format("space"), "padding", end='>>', sep='**')
print ("not-line2", "padding", end='')
print ("not-line3", "filling")
print ("end")

Outputs are:

Start_space**padding>>not-line2 paddingnot-line3 filling
end

To flush the iostream on each writing, keyword parameter 'flush' is introduced from Python 3.3.

References

A useful link to stackoverflow, http://stackoverflow.com/questions/11266068/python-avoid-new-line-with-print-command

results matching ""

    No results matching ""