-3

So I am wondering what the best way to knock off that last comma printed.

for i in range(1, 21):
    print(i, end=",")

The output should be:

1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
Eduardo Morales
  • 764
  • 7
  • 29
CameronT0101
  • 111
  • 5
  • 4
    `print(*range(1, 21), sep=",")` – Aran-Fey Nov 04 '18 at 19:29
  • 1
    Hey, please accept the answer if it was useful. Ask for further clarification otherwise. – Aykhan Hagverdili Nov 05 '18 at 13:47
  • Aren-Fey I am just curious about this: print(*range(1, 21), sep=",") # what exactly is the (*) doing to this ? – CameronT0101 Nov 09 '18 at 02:09
  • `print(*range(1, 21), sep=",")` here `*` operator unpacks the sequence, as if you wrote `print(1, 2, 3, 4, 5 ... 21, sep=",")`. More on `*` [here](https://stackoverflow.com/questions/2921847/what-does-the-star-operator-mean) . `sep` is the separator used between multiple values when printing. The default is a space (sep=' '), here we alter `sep` to put `,` between values. More one `sep` [here](https://stackoverflow.com/questions/22116482/what-does-print-sep-t-mean) – Aykhan Hagverdili Nov 09 '18 at 04:07

3 Answers3

1

If you want to do it your way:

for i in range(1, 21):
    print(i, end="," if i!=20 else "" )

Output:

1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20

But a better way of doing this would be:

print(*range(1, 21), sep=",")
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
1

This would be the most convenient way to do it in Python. Given any list, it will join the list together with whatever character you give it. This only works with list of strings so we have to convert the lsit of interegers to strings using map(str, your_list).

your_list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
converted_list_to_string = map(str, your_list)

print(",".join(your_list))

If you want a space after the comma, simply add it to the ", ":

print(", ".join(your_list))
Eduardo Morales
  • 764
  • 7
  • 29
  • 1
    You need to convert the list to a list of strings before calling join on it `", ".join(map(str, your_list))` – lakshayg Nov 05 '18 at 07:46
0

Here is a probably bit better way to accomplish your problem:

N = 20
# get a generator object with numbers in range 1 to & including N
to_print = range(1, N+1)
# convert all numbers to a string
to_print = map(str, to_print)
# join all numbers with a , in-between
to_print = ','.join(to_print)
# print string!
print(to_print)

What is happening here?

Ethan Koch
  • 267
  • 1
  • 6