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
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
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=",")
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))
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?