print function and unwanted trailing space

Peter Otten __peter__ at web.de
Sat Aug 31 09:59:21 EDT 2013


candide wrote:

> Le 31/08/2013 12:31, Peter Otten a écrit :
>  > softspace = False
>  > for i in range(5):
>  >      if softspace:
>  >          print(end=" ")
>  >      print(i, end="")
>  >      softspace = True
>  > print()
> 
> 
> The if instruction imposes useless testing (we know in advance the
> problem to occur at the very end of the loop) and useless writing
> (writing '').

To make it crystal clear, the above was to illustrate the algorithm used in 
Python 2, not a suggestion. Python 2 uses that "useless testing" -- which is 
cheap compared to actual I/O.

> The following is clearer
> 
> # -------------------------
> n=5
> for i in range(n-1):
>      print(i, end=' ')
> print(n-1)
> # -------------------------
> 
> 
> but doesn't solve all the cases (imagine a string or an iterator).

I still think you should live with a trailing space or go with my actual 
suggestion

print(*range(5))




More information about the Python-list mailing list