'Python Join a list of integers [closed]

I am trying to get list of numbers from:

numbers= 1,2

to:

'1','2'

I tried ",".join(str(n) for n in numbers) but it wont give the targeted format.



Solution 1:[1]

How about that?

>>> numbers=1,2
>>> numbers
(1, 2)
>>> map(str, numbers)
['1', '2']
>>> ",".join(map(str, numbers))
'1,2'

Solution 2:[2]

Use this:

>>> numbers = [1, 2]
>>> ",".join(repr(str(n)) for n in numbers)
'1','2'

Solution 3:[3]

What does your answer give?

>>> print ",".join(str(n) for n in numbers) 
1,2

If you really want '1','2' then do

>>> print ",".join("'%d'" % n for n in numbers)
'1','2'

Solution 4:[4]

By me the easiest way is this... Let's say you got list of numbers:

nums = [1,2,3,4,5]

Then you just convert them to list of strings in a single line by iterating them like this:

str_nums = [str(x) for x in nums]

Now you have list of strings and you can use them as a list or join them into string:

",".join(str_nums)

Easy :-)

Solution 5:[5]

Here's a bit of a hack. Not that hacky though, it's unlikely to bit-rot because JSON is so common.

import json
numbers = [1,2,3]
json.dumps(numbers, separators=(",",":"))[1:-1]
'1,2,3'

If you are ok with some whitespace, you can shorten it to

import json
numbers = [1,2,3]
json.dumps(numbers)[1:-1]
'1, 2, 3'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aaron Digulla
Solution 2
Solution 3
Solution 4 krupaluke
Solution 5 cmc