[Tutor] Printing without a line feed
Ming
ming at pgp.cool
Thu Mar 25 03:06:45 EDT 2021
On Thu, Mar 25, 2021 at 04:29:02PM +1100, 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.
Hello, I don’t think you need to print each number separately.
Try to use str.join() to join them into a string, and then print it all
at once.
For example:
a = list(range(6)) # a == [0, 1, 2, 3, 4, 5]
s = " ".join(map(str,a)) # s == '0 1 2 3 4 5'
print(s)
Note that join can only operate on lists where all elements are strings,
so map(str, list) is used here to convert all elements into strings.
--
OpenPGP fingerprint: 3C47 5977 4819 267E DD64 C7E4 6332 5675 A739 C74E
More information about the Tutor
mailing list