python - 需要让str方法返回字符串而不是打印
问题描述
我需要编写下面的 str 方法来返回一个字符串而不是打印一个字符串。
def __str__(self):
"""Returns the string representation of the student."""
avg = sum(self.scores) / len(self.scores)
print("Name: " + str(self.name))
print("Score 1: " + str(self.scores[0]))
print("Score 2: " + str(self.scores[1]))
print("Score 3: " + str(self.scores[2]))
print("High: " + str(int(max(self.scores))))
print("Average: %.2f\n" % avg)
解决方案
您要做的是将所有这些打印语句转换为一个字符串,同时保留您已有的换行符。
像这样的东西应该代替str
def __str__(self):
avg = sum(self.scores) / len(self.scores)
s = ""
s += "Name: " + str(self.name) + "\n"
s += "Score 1: " + str(self.scores[0]) + "\n"
s += "Score 2: " + str(self.scores[1]) + "\n"
s += "Score 3: " + str(self.scores[2]) + "\n"
s += "High: " + str(int(max(self.scores))) + "\n"
s += "Average: %.2f\n" % avg + "\n"
return s
推荐阅读
- reactjs - React 中的语义 UI 卡片组
- python - 删除数据集中的所有行 >= 一个值
- c# - 在 C# 的控制器中读取 POST 请求的请求正文
- javascript - Material UI - MultiSelect Popup Anchor 在选择上移动
- javascript - 松露事件测试:如何“伪造”事件集成测试的值
- excel - VBA中的换行符以及它是否是一个volatile函数
- c++ - "class XXXX;" 是什么意思?在cpp文件中是什么意思?
- kotlin - 为什么系统显示“No main method found in project”。
- mongodb - 创建新文档时增加 Mongoose 数字 ID
- reactjs - 如何在下拉菜单中添加按钮?