首页 > 解决方案 > __str__ 在 python 中给出二维表的可视化表示

问题描述

我在我的程序中使用下面的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)

标签: stringpython-3.xmultidimensional-array

解决方案


return print(('\n'.join(['|'.join([str(cell) for cell in row]) for row in self._table])))

您的__str__函数实际上是返回函数的结果print(这是NoneType因为 没有返回任何内容print),而不是二维表的字符串。导致你得到这个错误,因为__str__应该返回一个字符串。它应该是:

return ('\n'.join(['|'.join([str(cell) for cell in row]) for row in self._table]))

推荐阅读