how to print without blank?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sun Apr 9 03:02:28 EDT 2006


On Sat, 08 Apr 2006 22:54:17 -0700, Ju Hui wrote:

> I want to print 3 numbers without blank.
[snip]
> how to print
> 012
> ?

Method one: accumulate your numbers into a single string, then print it in
one go.

>>> L = []
>>> for x in range(3):
...     L.append(str(x))
... 
>>> print ''.join(L)
012
>>> 


Or even:

>>> print ''.join(map(str, range(3)))
012
>>> 


Or use a list comprehension:

>>> print ''.join([str(x) for x in range(3)])
012
>>> 



Method two: don't use the print statement, but write directly to standard
output.

>>> import sys
>>> for x in range(3):
...     sys.stdout.write(str(x))
...
012>>>


But notice how this does not write a newline when you are done -- you will
have to remember to do it yourself with sys.stdout.write('\n').

Also, print will work with any object, but sys.stdout.write will only work
with strings:

>>> print 6
6
>>> sys.stdout.write(6)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: argument 1 must be string or read-only character buffer, not int
>>>



-- 
Steven.




More information about the Python-list mailing list