Python string.join(list) on object array rather than string array


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?

1/31/2009 12:06:07 AM

Accepted Answer

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
1/31/2009 12:10:58 AM

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow