tags:

views:

1286

answers:

5

Hi,

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?

Thanks,

Ben

+15  A: 

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

','.join([str(i) for i in list_of_ints])
unbeknown
Perfect! Thanks.
Ben
Non-beginner note: In Python 2.4+ you don't need the `[ ]` around the generator expression -- it'll be more efficient if you leave it off.
cdleary
+9  A: 

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).

S.Lott
as for the Weeble comment, maybe it's better to use itertools.imap() if list_of_things is very big
Few things are big enough or time-critical enough to justify itertools over built-in map. However, if benchmarking reveals that this is the bottleneck, you've got a way to speed things up.
S.Lott
+8  A: 

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.

Weeble
Python 2.4 added Generator Expressions, bounded by parens, generating values one at a time, unlike the square-bracketed list comprehensions which generate the entire list. Dropping the square brackets becomes a Generator Expression due to a shortcut for single-param function calls.
Andy Dent
+1  A: 

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

",".join("%s" % i for i in list_of_things)
Tom Dunham
A: 

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

str(list_of_numbers)[1:-1]
fortran