[python] 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?

This question is related to python list

The answer is


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

''.join(map(str,list))

another solution is to override the join operator of the str class.

Let us define a new class my_string as follows

class my_string(str):
    def join(self, l):
        l_tmp = [str(x) for x in l]
        return super(my_string, self).join(l_tmp)

Then you can do

class Obj:
    def __str__(self):
        return 'name'

list = [Obj(), Obj(), Obj()]
comma = my_string(',')

print comma.join(list)

and you get

name,name,name

BTW, by using list as variable name you are redefining the list class (keyword) ! Preferably use another identifier name.

Hope you'll find my answer useful.


another solution is to override the join operator of the str class.

Let us define a new class my_string as follows

class my_string(str):
    def join(self, l):
        l_tmp = [str(x) for x in l]
        return super(my_string, self).join(l_tmp)

Then you can do

class Obj:
    def __str__(self):
        return 'name'

list = [Obj(), Obj(), Obj()]
comma = my_string(',')

print comma.join(list)

and you get

name,name,name

BTW, by using list as variable name you are redefining the list class (keyword) ! Preferably use another identifier name.

Hope you'll find my answer useful.


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

''.join(map(str,list))

I know this is a super old post, but I think what is missed is overriding __repr__, so that __repr__ = __str__, which is the accepted answer of this question marked duplicate.


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

''.join(map(str,list))

I know this is a super old post, but I think what is missed is overriding __repr__, so that __repr__ = __str__, which is the accepted answer of this question marked duplicate.