print function and unwanted trailing space

Oscar Benjamin oscar.j.benjamin at gmail.com
Sat Aug 31 08:37:58 EDT 2013


On 31 August 2013 12:16, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> 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

The space is added by the final print statement, not the last one in
the loop. Here's a demo that shows this:

$ cat print.py
for i in range(5):
    print i,
print
$ cat print3.py
for i in range(5):
    print(i, end=' ')
print()
$ py -2.7 print.py | cat -A
0 1 2 3 4^M$
$ py -3.3 print3.py | cat -A
0 1 2 3 4 ^M$

(Notice the space between the 4 and ^M (which is cat's way of saying '\r').

[snip]
>
>> hence the following Python 3 code isn't strictly equivalent:
>>
>>
>> # -----------------------------
>> for i in range(5):
>>      print(i, end=' ')   # <- The last ' ' is unwanted
>> print()
>
> The last space is exactly the same as you get in Python 2. But really,
> who cares about an extra invisible space? In non-interactive mode, the
> two are exactly the same (ignoring the extra print() call outside the
> loop), but even at the interactive interpreter, I'd like to see the code
> where an extra space makes a real difference.

I seem to remember it breaking some unit test or doc test something
when I first tried to port something using 2to3 (this is the
replacement that 2to3 uses for print with a trailing comma). It's not
so important for interactive terminal output but when you do 'python
script.py > output.dat' the unwanted space shouldn't be there. The
soft-space feature is useful but stateful as Peter says and defies the
normal concept of what happens when calling a function so it was
removed when print became a function.


Oscar



More information about the Python-list mailing list