print function and unwanted trailing space

Peter Otten __peter__ at web.de
Sat Aug 31 08:27:39 EDT 2013


Steven D'Aprano wrote:

> On Sat, 31 Aug 2013 10:17:23 +0200, candide wrote:
> 
>> What is the equivalent in Python 3 to the following Python 2 code:
>> 
>> # -----------------------------
>> for i in range(5):
>>      print i,
>> # -----------------------------
>> 
>> ?
>> 
>> Be careful that the above code doesn't add a trailing space after the
>> last number in the list,
> 
> Of course it does. Have you actually tried it? The interactive
> interpreter is tricky, because you cannot directly follow a for-loop with
> another statement. If you try, the interactive interpreter gives you an
> indentation error. But we can work around it by sticking everything
> inside an if block, like so:
> 
> py> if True:
> ...     for i in range(5):
> ...             print i,
> ...     # could be pages of code here
> ...     print "FINISHED"
> ...
> 0 1 2 3 4 FINISHED
> 
> 
> Or you could stick the code inside an exec, which doesn't have the same
> limitation as the interactive interpreter. This mimics the behaviour of
> code in a file:
> 
> py> exec """for i in range(5):
> ...     print i,
> ... print "FINISHED"
> ... """
> 0 1 2 3 4 FINISHED
> 
> 
> The same results occur with any other Python 2.x, and indeed all the way
> back to Python 1.5 and older.

Your test is flawed. The softspace mechanism ensures that there is a space 
*between* all printed items, but not *after* the last printed item.

print "FINISHED"

will add a space while

print

will not. Compare:

>>> with open("tmp.txt", "w") as f:
...     for i in range(3): print >> f, i,
...     print >> f
... 
>>> open("tmp.txt").read()
'0 1 2\n'
>>> with open("tmp.txt", "w") as f:
...     for i in range(3): print >> f, i,
...     print >> f, "FINISHED"
... 
>>> open("tmp.txt").read()
'0 1 2 FINISHED\n'







More information about the Python-list mailing list