Formatting a basic table
本问题已经有最佳答案,请猛点这里访问。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | def main(): infile = open ('correctAnswers.txt','r') correct = infile.readlines() infile.close infile1 = open ('studentAnswers.txt','r') student = infile.readlines() infile1.close index=0 correctanswer=0 wronganswer=[] while index<len(correct): correct[index]=correct[index].rstrip(' ') student[index]=student[index].rstrip(' ') if correct[index]==student[index]: correctanswer=correctanswer+1 print(index) index=index+1 else: wronganswer.append(index) print(index) index=index+1 if correctanswer>0: print("Congratulations you passed the test.") else: print("I'm sorry but you did not pass the test") print("") print("") print("# Correct Student") print("-----------------------") for item in incorrectindex: print(item+1," ",correctanswers[item]," ",studentanswers[item]) |
主体()
这就是我正在执行的整个程序。它读取了我在本地的两个文件,检查学生是否有足够的正确答案通过考试。程序执行良好,它产生恭喜你通过了考试。
1 2 3 4 5 6 7 | # Correct Student ----------------------- 3 A B 7 C A 11 A C 13 C D 17 B D |
问题是,看起来非常草率,注意数字从单位数到双位数的变化如何将字母移动一个空格。你这样做有什么特别的方法吗?因为我知道我将来会遇到这个问题。
查看有关字符串格式的文档,通过这些文档可以控制:
1 2 3 4 5 6 7 8 9 | >>> def formatted(x, y, z): # column 1 is 10 chars wide, left justified # column 2 is 5 chars wide # column3 is whatever is left. ... print"{:<10}{:<5}{}".format(x, y, z) >>> formatted(1,"f","bar") >>> formatted(10,"fo","bar") >>> formatted(100,"foo","bar") |
输出
1 2 3 | 1 f bar 10 fo bar 100 foo bar |
…保持列宽。
所以在您的示例中,而不是
1 2 | for item in incorrectindex: print(item+1," ",correctanswers[item]," ",studentanswers[item]) |
类似:
1 2 | for item in incorrect index: print("{:<5}{:<10}{}".format(item+1, correctanswers[item], studentanswers[item]) |