Just call join passing in your list and if it is only one element, it won't add the "comma":
print(','.join(['1']))
output:
1
print(','.join(['1', '2']))
output:
1,2
print(','.join(['1', '2', '3']))
output:
1,2,3
If you have a list of integers, or a mix of strings and integers, then you would have to call str
on the integer parts in your list. However, the easiest way to go about doing this would be to either call map on your list (map will apply a callable to each item in your list) to cast to the appropriate str
, or perform a generator comprehension to cast to int:
comprehension:
print(",".join(str(i) for i in [1,2,3]))
map:
print(",".join(map(str, [1,2,3])))