首页 > 解决方案 > 需要让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)

标签: pythonstringreturn

解决方案


您要做的是将所有这些打印语句转换为一个字符串,同时保留您已有的换行符。

像这样的东西应该代替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

推荐阅读