[Tutor] Why does print add spaces ?

Jeff Shannon jeff@ccvcorp.com
Mon Mar 17 15:33:01 2003


Don Arnold wrote:

>----- Original Message -----
>From: "Tony Cappellini" <tony@tcapp.com>
>  
>
>>I should have asked "How are we supposed to know when print will add a
>>space or not" ?
>>I've used it many times, when it does not add the extra space.
>>    
>>
>
>I'm pretty sure that without messing around with stdout's softspace
>attribute, print always puts a space between comma-separated arguments. 
>

That's my understanding as well.  Using a single argument to print 
implies that a newline should be added to the end, using a comma (after 
a single argument or to separate multiple arguments) implies a space.

However, it's complicated a bit by the use of softspace -- basically, 
this is a mechanism to prevent print from adding a space to something 
that already ends with a space.  If you type 'print "spaced ",' you 
won't end up with two trailing spaces, you'll only have one -- exactly 
the same as if you typed 'print "unspaced",'.

The print keyword does a moderate amount of fiddling to try to make 
things look pretty.  If you want direct control over your output, you 
can use (as was suggested elsewhere) sys.stdout.write().

By the way, the code as originally posted:

mystr="abcdefghi"
for x in range(1,len(mystr)):
    print "%s," % mystr[x],

a, b, c, d, e, f, g, h, i,


Is not accurate, and will not have that result.  Here's a cut-and-paste 
from actually running it:

 >>> mystr = "abcdefghi"
 >>> for i in range(1,len(mystr)):
...     print "%s," % mystr[i],
...    
b, c, d, e, f, g, h, i,
 >>>

Where'd "a" go?  The problem is that almost everything in Python uses 
zero-based indexing.  The first character of mystr isn't mystr[1], it's 
mystr[0].  This is *why* range() defaults to starting at 0.  And while 
you may think that 1-based indexing is more "intuitive", it results in a 
lot more need to adjust things by one, which in turn results in a lot 
more off-by-one errors.

Besides, there's an easier way to get each character of a string (or 
each element of a list or tuple):

 >>> mystr = "abcdefghi"
 >>> for char in mystr:
...     print "%s," % char,
...    
 a, b, c, d, e, f, g, h, i,
 >>>

Jeff Shannon
Technician/Programmer
Credit International