Reputation: 21
I have a code that print x number of numbers. Firstly, I asked for the serious length. Then print all the previous numbers (from 0 to x).
My question is that: when printing these number, I want to separate between them using comma. I used print(a,end=',') but this print a comma at the end also. E.g. print like this 1,2,3,4,5, while the last comma should not be there.
I used if statement to overcome this issue but do not know if there is an easier way to do it.
n=int(input("enter the length "))
a=0
if n>0:
for x in range(n):
if x==n-1:
print(a,end='')
else:
print(a,end=',')
a=a+1
Upvotes: 2
Views: 1529
Reputation: 9157
The most Pythonic way of doing this is to use list comprehension and join
:
n = int(input("enter the length "))
if (n > 0):
print(','.join([str(x) for x in range(n)]))
Output:
0,1,2
Explanation:
','.join(...)
joins whatever iterable is passed in using the string (in this case ','
). If you want to have spaces between your numbers, you can use ', '.join(...)
.
[str(x) for x in range(n)]
is a list comprehension. Basically, for every x
in range(n)
, str(x)
is added to the list. This essentially translates to:
data = []
for (x in range(n))
data.append(x)
Upvotes: 1
Reputation: 40801
A Pythonic way to do this is to collect the values in a list and then print them all at once.
n=int(input("enter the length "))
a=0
to_print = [] # The values to print
if n>0:
for x in range(n):
to_print.append(a)
a=a+1
print(*to_print, sep=',', end='')
The last line prints the items of to_print
(expanded with *
) seperated by ','
and not ending with a newline.
In this specific case, the code can be shortened to:
print(*range(int(input('enter the length '))), sep=',', end='')
Upvotes: 0