print function and unwanted trailing space

Chris Angelico rosuav at gmail.com
Sat Aug 31 11:30:48 EDT 2013


On Sat, Aug 31, 2013 at 11:33 PM, candide <candide at free.invalid> wrote:
> 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 '').
>
> 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).

Similar but maybe simpler, and copes with more arbitrary iterables:

it=iter(range(5))
print(next(it), end='')
for i in it:
    print('',i, end='')

Also guarantees to use 'sep' between the elements, fwiw.

ChrisA



More information about the Python-list mailing list