格式化基本表

时间:2015-11-05 18:25:09

标签: python format

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('\n')
        student[index]=student[index].rstrip('\n')
        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])

main()的

所以这是我正在执行的整个程序。它读取我在本地检查的两个文件,检查是否有足够的正确答案通过测试。程序执行良好,它产生 恭喜你通过了考试。

#    Correct   Student 
-----------------------
3       A      B
7       C      A
11       A      C
13       C      D
17       B      D

问题是看起来很草率,请注意数字从单个数字到两位数的变化如何将字母移动一个空格。有没有一种特定的方式,因为我知道我将来会遇到这个问题

1 个答案:

答案 0 :(得分:1)

查看string formatting上的文档,它可以让您控制它:

>>> 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         f    bar
10        fo   bar
100       foo  bar

...保持列宽。

所以在你的例子中,而不是

   for item in incorrectindex:
        print(item+1,"     ",correctanswers[item],"    ",studentanswers[item])

类似的东西:

for item in incorrect index:
    print("{:<5}{:<10}{}".format(item+1, correctanswers[item], studentanswers[item])