1

I've learnt from this question that it is possible to join the values in an array using ", ".join(var) in Python. This code works for strings, for example:

var = ["hello","world"]
print (", ".join(var))

Gives an output of hello, world which is what I want.

However, when I use numbers in the array:

var = [1,2,3]
print (", ".join(var))

It gives an error message:

Traceback (most recent call last):
  File "C:\path\test.py", line 2, in <module>
    print (", ".join(var))
TypeError: sequence item 0: expected str instance, int found

Whereas, I want the output to be:

1, 2, 3

Is there another way I can this so it will print all of the numbers and also have the ability to be increased so I can have any amount of numbers?

Community
  • 1
  • 1
JolonB
  • 415
  • 5
  • 25

1 Answers1

7

Just convert the numbers to strings before joining:

var = [1, 2, 3]
print(", ".join(map(str, var)))

or using a list comprehension:

print(", ".join([str(x) for x in var]))
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
  • 1
    The list comprehension is not needed, you could directly supply a generator expression: `print(",".join(str(x) for x in var))` – burnpanck Jun 03 '16 at 11:58
  • Map is (ever so slightly) faster, so that's the preferable (while less pythonic) answer if OP is looking for speed. http://stackoverflow.com/a/1247490/5388567 – Valkyrie Jun 03 '16 at 12:02
  • 1
    @burnpanck: if you need to iterate over *all* the items, building a list with a list comprehension is usually faster than using a generator (unless the resulting list is very big). – Eugene Yarmash Jun 03 '16 at 12:20
  • @eugeney: ... which sounds weird, because you will iterate over each element twice if you use list comprehension. However, it seems to be true nonetheless. A pity, I find solutions that avoid unnecessary intermediates always more elegant. – burnpanck Jun 03 '16 at 22:03