tags:

views:

4312

answers:

2

In Python, I can do:

>>> list = ['a', 'b', 'c']
>>> ', '.join(list)
'a, b, c'

Is there any easy way to do the same when I have a list of objects?

>>> class Obj:
...     def __str__(self):
...         return 'name'
...
>>> list = [Obj(), Obj(), Obj()]
>>> ', '.join(list)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, instance found

Or do I have to resort to a for loop?

+13  A: 

You could use a list comprehension or a generator expression instead:

', '.join([str(x) for x in list])  # list comprehension
', '.join(str(x) for x in list)    # generator expression
Adam Rosenfield
or a generator expression: ', '.join(str(x) for x in list)
dF
+8  A: 

The built-in string constructor will automatically call obj.__str__:

''.join(map(str,list))
Triptych
map() doesn't change the list, it's equivalent to [str(o) for o in list]
dF
+1: Map is a good approach; "changing the list" isn't an accurate comment.
S.Lott
Thx guys. Sadly, I'd been programming in Python all evening. Time for a break maybe.
Triptych