下面的代码def output(land, oak_count, willow_count):
l_0 = "Investigation of Trees Completed:"
l_1 = "Land Surveyed: " + str(land)
l_2 = "Oaks: " + str(oak_count)
l_3 = "Willows: " + str(willow_count)
text = []
for i in range(0, 4):
text.append(vars()["l_"+str(i)])
return text
text = output("Green Forest", 5, 10)
for i in text:
print(i)
给出以下输出:Investigation of Trees Completed:
Land Surveyed: Green Forest
Oaks: 5
Willows: 10
然而,对于大型输出文件来说,这似乎是令人难以置信的繁琐。它还使得在将来的更新中编辑输出变得困难,行可能会被遗忘或需要重新排序(特别是当报告包含许多行时)。
还需要能够将输出文本返回到另一个模块,以便它可以与其他信息位进行排序。为此,我将文本存储为变量。
我正在寻找一种一次性返回输出的方法。大致如下(尽管这不起作用):text = """
Investigation of Trees Completed:\n
Land Surveyed:""" + str(Green Forest) + """\n
Oaks: """ + str(oak_count) + """\n
Willows: """ + str(willow_count) + """\n
"""
并且代码也根据样式指南跨越多行。不幸的是,上面给出了(当使用print(text)):'\nInvestigation of Trees Completed:\nLand Surveyed:Green Forest\nOaks: 5\nWillows: 10\n'
注意:通过以下方式将文本保存到文件:text_file = open("output.txt", "w")
text_file.write(text)
text.close
以所需格式给出上面的输出。