Python string.join(列表)对象数组而不是string数组

在Python中,我可以这样做:

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

有一个对象列表时,有没有简单的方法来做同样的事情?

 >>> 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 

还是我不得不求助于循环?

您可以使用列表理解或生成器expression式来代替:

 ', '.join([str(x) for x in list]) # list comprehension ', '.join(str(x) for x in list) # generator expression 

内置的string构造函数将自动调用obj.__str__

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