【发布时间】:2018-11-16 19:28:47
【问题描述】:
我在我的程序中使用下面的 str 函数来表示 2D 表格
def __str__(self):
"""Returns a string representation of the table"""
return ('\n'.join(['|'.join([str(cell) for cell in row]) for row in self._table]))
如果我使用 str(),它会给我下面的输出
'1|2|3\n2|4|6\n3|6|9'
如何在不使用 print() 的情况下使其显示如下
1|2|3
2|4|6
3|6|9
我试图定义我的 str 如下:
def __str__(self):
"""Returns a string representation of the table"""
return print(('\n'.join(['|'.join([str(cell) for cell in row]) for row in self._table])))
使用 str() 给出以下错误的输出
1|2|3
2|4|6
3|6|9
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
str(MultiplicationTable(3))
TypeError: __str__ returned non-string (type NoneType)
【问题讨论】:
-
__str__不是这样工作的,您应该打印__str__返回的任何内容,而不是在__str__中打印出来...请阅读有关如何正确使用这些功能的文档.
标签: string python-3.x multidimensional-array