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

Question

Asked By – Mat

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?

Now we will see solution for issue: Python string.join(list) on object array rather than string array


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

This question is answered By – Adam Rosenfield

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0