簡體   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