【发布时间】:2017-02-11 18:59:51
【问题描述】:
我有一个任务,我们必须读取我们创建的包含测试名称和分数的文件,并将它们打印在列中。获取数据并将其与平均值一起显示是没有问题的,但我不明白如何将分数与输出列中的右侧对齐。在输出示例中,分数在“SCORES”列的右侧完美排列。我可以使用 format(scores, '10d') 作为示例来格式化它们的宽度,但这总是与测试名称的长度有关。有什么建议吗?
def main():
testAndscores = open('tests.txt', 'r')
totalTestscoresVaule = 0
numberOfexams = 0
line = testAndscores.readline()
print("Reading tests and scores")
print("============================")
print("TEST SCORES")
while line != "":
examName = line.rstrip('\n')
testScore = float(testAndscores.readline())
totalTestscoresVaule += testScore
## here is where I am having problems
## can't seem to find info how to align into
## two columns.
print(format(examName),end="")
print(format(" "),end="")
print(repr(testScore).ljust(20))
line = testAndscores.readline()
numberOfexams += 1
averageOftheTestscores = totalTestscoresVaule / numberOfexams
print("Average is", (averageOftheTestscores))
#close the file
testAndscores.close()
main()
【问题讨论】:
-
获取所有行的列表;找到最长的“分数”;计算列宽并在格式中使用。
-
也许像 tabulate 或 terminaltables 这样的库可以帮助你。有很多这样的。
-
你能提供tests.txt的例子吗
-
@DYZ 这听起来是个好主意!你能举个例子吗?谢谢!
标签: python alignment multiple-columns