print function and unwanted trailing space

Ned Batchelder ned at nedbatchelder.com
Sat Aug 31 07:24:54 EDT 2013


On 8/31/13 4:17 AM, 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, hence the following Python 3 code isn't 
> strictly equivalent:
>
>
> # -----------------------------
> for i in range(5):
>     print(i, end=' ')   # <- The last ' ' is unwanted
> print()
> # -----------------------------

For a beginner course, the trailing space is fine, use this code. 
They'll never notice the trailing space (I wouldn't have!) and to 
explain why the comma leaves off the last one takes a really advanced 
understanding of obscure details anyway.

--Ned.



More information about the Python-list mailing list