print ending with comma

Duncan Booth duncan.booth at invalid.invalid
Tue Jul 19 17:50:01 CEST 2005


> I recently ran into the issue with 'print' were, as it says on the web
> page called "Python Gotchas"
> (
> The Python Language Reference Manual says, about the print statement,
> A "\n" character is written at the end, unless the print statement ends
> with a comma.
> What it doesn't say is that if the print statement does end with a
> comma, a trailing space is printed.
> --
> But this isn't exactly correct either. If you run this program:
> import sys
> print '+',
> print '-',
> sys.stdout.write('=')
> print
> --
> the output is:
> + -=
> Note that there is no space after the '-'. (Tested on Win 2000 python
> 2.3.4, OS X 10.3.9 python 2.3 & 2.4)
> I know that this is not a massively important issue, but can someone
> explain what's going on?
The space isn't appended to the value printed, it is output before the next 
value is printed.

The file object has an attribute softspace (initially 0). If this is 0 then 
printing a value simply writes the value to the file. If it is 1 then 
printing a value writes a space followed by the value.

After any value which ends with a newline character is printed the 
softspace attribute is reset to 0 otherwise it is set to 1. Also when a 
print statement ends without a trailing comma it outputs a newline and 
resets softspace.

Change your print test a little to see this:

>>> print "+",;print "-",;sys.stdout.write("=");print "X"
+ -= X

Or try this to suppress unwanted spaces in your output:

>>> def nospace(s):
	sys.stdout.softspace = 0
	return s

>>> print "a",nospace("b"),"c"
ab c

More information about the Python-list mailing list