string - __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)
解决方案
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]))
推荐阅读
- javascript - 如何使用liveScroll取消选择primefaces dataTable中的所有内容
- php - 在magento的客户发票中的送货地址中添加公司名称
- raspberry-pi3 - Rasp Pi 3 将不再使用 Things 1.0 启动
- javascript - javascript中带有可选参数的函数的正确JSDoc typedef声明
- c# - Google Calender Api v3 .net 当与会者回复活动时发送电子邮件通知
- html - 以角度 2 格式化的工具提示 html
- node.js - 未调用护照身份验证
- android - TelephonyManager.iccTransmitApduBasicChannel 数据参数格式
- android - 开发时在Android手表上安装apk的最佳方法是什么?
- php - 如何在不更改 PHP 中的样式和字体的情况下将 word docx 或 doc 转换为 HTML 页面?