[Tutor] Why does print add spaces ?

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed Mar 19 01:37:01 2003


On Tue, 18 Mar 2003, Michael Barrett wrote:

> Using list comprehension you could do the following:
>
> >>> x = 'abcdefghi'
> >>> print ','.join([i for i in x])
> a,b,c,d,e,f,g,h,i
>
> As to why python prints the spaces?  It's just the way print works in
> the language.  Can't really answer why, but I'm sure the developers felt
> they had a reason.


Hello!

I think the 'print' statement is designed for simple output;  it's
definitely "special" in the sense that it really pays attention to
trailing commas.  For example:

###
>>> def print_numbers():
...     for i in range(10):
...         print i,
...
>>> print_numbers()
0 1 2 3 4 5 6 7 8 9
###


Python's print statement introduces spaces to visually keep variable
values from bleeding into each other unless we try really hard to do so...
*grin*

###
>>> x, y, z = 3, 1, 4
>>> print x, y, z
3 1 4
>>> import sys
>>> sys.stdout.write("%s%s%s" % (x, y, z))
314>>>
###

(Notice that if we use sys.stdout.write(), we're able to escape the
special newline-adding behavior of the 'print' statement.)

Newcomers to a language may get caught off guard if they print variables
without spaces in between.  Python's 'print' statement simply makes that
misake impossible.  *grin* And the design is concious, although sometimes
the designers wonder if they should have done something more uniform and
less special.  In:

    http://aspn.activestate.com/ASPN/Mail/Message/pypy-dev/1521115

the main developer of Python (Guido) admits that:

    """While punctuation is concise, and often traditional for things like
       arithmetic operations, giving punctuation too much power can lead
       to loss of readability.  (So yes, I regret significant trailing
       commas in print and tuples -- just a little bit.)"""


But I still like Python's "print" statement for it's simplicity, even
though it is slightly special.  And if we need more fine control over the
way we print things, sys.stdout() is a good tool.


Anyway, I hope this helps!