Python Join a list of integers

Question:

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.

Asked By: Hussein Zawawi

||

Answers:

Use this:

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

How about that?

>>> numbers=1,2
>>> numbers
(1, 2)
>>> map(str, numbers)
['1', '2']
>>> ",".join(map(str, numbers))
'1,2'
Answered By: Gandi
>>> numbers = 1,2
>>> print ",".join("'{0}'".format(n) for n in numbers)
'1','2'
Answered By: jamylak

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'
Answered By: Colonel Panic

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 🙂

Answered By: krupaluke

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'
Answered By: cmc
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.