1
我有一個任務,我們必須閱讀我們創建的具有測試名稱和分數的文件,並將它們打印在列中。獲取數據並將其與平均值一起顯示並不成問題,但我不明白如何將輸出列中的分數對齊到右側。在輸出示例中,分數與「SCORES」列的權限完全對齊。我可以使用格式(分數,'10d')作爲示例來格式化它們的寬度,但這總是與測試名稱的長度有關。有什麼建議?如何在python中完美對齊兩列?
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()
獲取所有行的列表;找到最長的「分數」;計算列的寬度並以格式使用它。 – DyZ
也許像[tabulate](https://pypi.python.org/pypi/tabulate)或[terminaltables](https://pypi.python.org/pypi/terminaltables)這樣的庫可以幫助你。有很多這樣的。 –
你能提供一個tests.txt的例子嗎? – ands