0

My input1:

 values = ['1','2']

Expected output to print

   print 1, 2

my input2:

  values = ['1']

Expected output to print

   print 1

my input3:

  values = ['1','2','3']

Expected output to print

    print 1,2,3

Below is what i tried:

  for x in values:
      print x  
Bittu
  • 31
  • 2
  • 9
  • you may convert list to string [stackoverflow](https://stackoverflow.com/a/5618944/5589166) – Sovary Jun 24 '17 at 03:52

3 Answers3

5

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])))
idjaw
  • 25,487
  • 7
  • 64
  • 83
  • You would need to use a comma and a space to get the output as you currently have it – Robb Jun 24 '17 at 03:54
  • Thanks for pointing that out. Actually the code is fine, it is my output that needed to be changed to indicate what my code would actually output. It now matches the OP expectation. – idjaw Jun 24 '17 at 03:56
  • in case list contain integers then join might not work right? – Bittu Jun 24 '17 at 03:58
  • @Bittu Yes that is correct. I updated the answer to reflect that detail. – idjaw Jun 24 '17 at 04:01
0

Just simple as:

print(','.join(myList))
developer_hatch
  • 15,898
  • 3
  • 42
  • 75
0

What you type in the command for print isn't exactly what comes out. Basically the commas in the print command just separate out each item you asked it to print but don't tell it to print commas itself. i.e.

>>> print 1, 2, 3
1 2 3 

The key is to create the text or string how you want it to look and then print that.

>>> text = ','.join(str(x) for x in [1, 2, 3])
>>> print text
1,2,3
Robb
  • 433
  • 2
  • 9