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?
Answers:
You have to convert the ints to strings and then you can join them:
','.join([str(i) for i in list_of_ints])
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).
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.
Just for the sake of it, you can also use string formatting:
",".join("{0}".format(i) for i in list_of_things)
and yet another version more (pretty cool, eh?)
str(list_of_numbers)[1:-1]
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?
You have to convert the ints to strings and then you can join them:
','.join([str(i) for i in list_of_ints])
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).
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.
Just for the sake of it, you can also use string formatting:
",".join("{0}".format(i) for i in list_of_things)
and yet another version more (pretty cool, eh?)
str(list_of_numbers)[1:-1]