-2
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()

So this is the entire program that I am executing. It reads two files that I have locally that check is a student has enough of the correct answers to pass the test. The program executes well, it produces Congratulations you passed the test.

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

The problem is that is looks very sloppy, notice how the change of numbers from single digits to double digits shifts the letters across by one space. Is there a specific way you do this because I know I will come across this issue in the future

1 Answers1

1

Look at the docs on string formatting, which lets you control this:

>>> 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")

outputs

1         f    bar
10        fo   bar
100       foo  bar

...maintaining the column widths.

So in your example, instead of

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

something like:

for item in incorrect index:
    print("{:<5}{:<10}{}".format(item+1, correctanswers[item], studentanswers[item])
bgporter
  • 35,114
  • 8
  • 59
  • 65
  • right but how could I incorporate that within the for loop? – John OConnor Nov 05 '15 at 18:42
  • instead of printing with manual spaces inserted like `print(item+1," ",correctanswers[item]," ",studentanswers[item])`, use a format string and the `format()` method like I show in the `formatted()` function above. – bgporter Nov 05 '15 at 18:43