A trivial question about print

Alex Martelli aleax at aleax.it
Thu Apr 11 07:39:55 EDT 2002


Ante Bagaric wrote:

> Is there a way to prevent the print statement to automatically add a space
> between two objects?
> 
>>>>print "a=",a
> a= 1
> 
> how to make that cursed blank character dissappear?
> Other than print "a=%d" % a because it wouldnt work for iteration of
> prints..
> 
> for i in range(5):
>     print i,
> 
> gives 0, 1, 2, 3, 4 and I want 0,1,2,3,4

Actually this gives 0 1 2 3 4 -- I don't know where you got the commas
in the output that you seem to have observed, maybe your print statement
was not quite as you show it here.


> Yes, I know it's possible to circumvent this behaviour, but I'm curiuous
> whether it can be done within the print statement alone.

The print statement sets the softspace attribute on sys.stdout when it
has just printed with a trailing comma, resets it when it emits a line
break.  If it finds the attribute set when about to continue emitting,
it outputs a space first.  The following superdirty trick works as
expected:

>>> import sys
>>> for i in range(5):
...   print setattr(sys.stdout,'softspace',0) or ("%s,"%i),
...
0,1,2,3,4,
>>>

because the expressions are evaluated BEFORE the print statement's
opcode occurs, thus before it checks sys.stdout.softspace.


Apart from showing off that you really know how print works, it
would of course be absurd to use such tricks in order to abuse yet
further the vastly-overused print.  A vastly superior way is
to use sys.stdout.write("%s,"%i) -- you just need some care to
show it off interactively because you need a '\n' at the end,
so, for example:

>>> if 1:
...   for i in range(5): sys.stdout.write("%s,"%i)
...   sys.stdout.write('\n')
...
0,1,2,3,4,
>>>

or, back to trick-land,

>>> for i in range(5):
...   sys.stdout.write("%s,%s"%(i,'\n'[i!=4:]))
...
0,1,2,3,4,
>>>

but you need no trick at all to use the write method in the
perfectly normal way within a script or module.


Alex




More information about the Python-list mailing list