在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
或者我必须使用for循环吗?
内置的字符串构造函数将自动调用
obj.__str__
:您可以使用列表理解或生成器表达式代替:
另一个解决方案是重写str类的join运算符。
让我们定义一个新的类my_string如下
那你就可以了
你就会得到
顺便说一句,使用list作为变量名,就可以重新定义list类(关键字)!最好使用另一个标识符名称。
希望你会发现我的答案有用。
相关问题 更多 >
编程相关推荐