繁体   English   中英

需要让str方法返回字符串而不是打印

[英]Need to make str method return string instead of printing

我需要编写下面的 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM