How to convert a list of longs into a comma separated string in python

Question:

I’m new to python, and have a list of longs which I want to join together into a comma separated string.

In PHP I’d do something like this:

$output = implode(",", $array)

In Python, I’m not sure how to do this. I’ve tried using join, but this doesn’t work since the elements are the wrong type (i.e., not strings). Do I need to create a copy of the list and convert each element in the copy from a long into a string? Or is there a simpler way to do it?

Asked By: Ben

||

Answers:

You have to convert the ints to strings and then you can join them:

','.join([str(i) for i in list_of_ints])
Answered By: unbeknown

You can use map to transform a list, then join them up.

",".join( map( str, list_of_things ) )

BTW, this works for any objects (not just longs).

Answered By: S.Lott

You can omit the square brackets from heikogerlach’s answer since Python 2.5, I think:

','.join(str(i) for i in list_of_ints)

This is extremely similar, but instead of building a (potentially large) temporary list of all the strings, it will generate them one at a time, as needed by the join function.

Answered By: Weeble

Just for the sake of it, you can also use string formatting:

",".join("{0}".format(i) for i in list_of_things)
Answered By: Tom Dunham

and yet another version more (pretty cool, eh?)

str(list_of_numbers)[1:-1]
Answered By: fortran
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.