[Tutor] Printing without a line feed

Peter Otten __peter__ at web.de
Thu Mar 25 05:19:44 EDT 2021


On 25/03/2021 06:29, Phil wrote:
> Thank you for reading this.
> 
> I want to print a range of numbers with a space between them but without 
> a space at the end. For instance:
> 
>      for i in range(6):
>          print(i, end=' ')
> 
> How do I do this without the end space? I've spent hours on this even 
> though I've managed to do what I want not long ago but I cannot remember 
> how I did it. It's very frustrating.

You can convert the numbers to a single string with

 >>> print(" ".join(str(i) for i in range(6)))
0 1 2 3 4 5

The argument of "".join() is called "generator expression".

Or you can use the star operator:

>>> print(*range(6))
0 1 2 3 4 5

This passes the elements of the range() iterable as individual arguments 
to print(), i. e. it's equivalent to

print(0, 1, 2, 3, 4, 5)





More information about the Tutor mailing list