Re: simple question on print

Guido.van.Rossum@cwi.nl
Tue, 15 Feb 1994 16:34:35 +0100

Python must be one of the few languages where you can implement
Pascal's write() and writeln() :-)

Mark's solution reminded me of an undocumented feature of Python:
"softspace". If you implement your own writing object, the object
receives an integer attribute (which is mostly manipulated by the
system) called softspace, and the space between items is only written
(just before the next item is written) if its softspace attribute is
nonzero.

Here is a class which forces the softspace attribute to zero on each
write operation, and a test routine:

======================================================================
class Writer:
def __init__(self, fp):
self.fp = fp
def write(self, str):
self.fp.write(str)
self.softspace = 0

def test():
import sys
sys.stdout = Writer(sys.stdout)
print 1, 2, 3, 4, 5
print 6, 7, 8, 9, 10

test()
======================================================================

Output from this script is:

======================================================================
12345
678910
======================================================================

If you don't want *every* soft space to be suppressed, you can remove
the assignment to self.softspace from the write() method and set it to
0 explicitly each time you have done a "print value," after which you
don't want a space.

(This *should* also work for 'real' file objects, but because I never
realized this was a desirable feature I never supported 'softspace' as
an actual attribute of file objects -- its internal representation is
not accessible. If people think it's a good idea I might change this
in the next patch.)

--Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl>
URL: <http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>