【问题标题】:Need to make str method return string instead of printing需要让str方法返回字符串而不是打印
【发布时间】:2021-06-12 19:22:00
【问题描述】:

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

【问题讨论】:

  • 您应该尝试通过替换多个打印,通过返回 (str1 +'\n' +str2+'\n' +...) ...尝试告诉我们您是否设法做到了。

标签: python string return


【解决方案1】:

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

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

【讨论】:

  • 因为现在返回的是一个字符串,你需要在之后打印字符串,所以在 for s in students: print(s.__str__())
猜你喜欢
  • 2015-07-22
  • 1970-01-01
  • 2013-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-28
  • 2019-03-07
相关资源
最近更新 更多