在文本文件的特定行中写入时,字符串索引超出范围

时间:2019-02-25 20:30:52

标签: python text-files

为什么它总是给我这个错误?我在第一种方法中遇到了这个问题,但它没有给我一个错误,但是当我在第二种方法中使用代码时,它继续给我这个错误

这是我的第一种方法,效果很好

    def btn_English(self):
    answerKey = open("answerkeyEnglish", 'r')
    studentExam = open("studentExam", 'r')
    index = 0
    numCorrect = 0

    for answerLine, studentLine in zip(answerKey, studentExam):
        answer = answerLine.split()
        studentAnswer = studentLine.split()
        if studentAnswer != answer:
            print("You got question number", index + 1, "wrong\nThe correct answer was", answer, "but you answered",
                  studentAnswer)
            index += 1
        else:
            numCorrect += 1
            index += 1
    gradeAverage = int((numCorrect / 2) * 100)
    grade = numCorrect
    english = open('examResult','w')
    english.write(str(grade))

,这是第二种方法,它给出了错误。用english.write(str(grade)[2])。

    def btn_Math(self):
    answerKey = open("answerkeyEnglish", 'r')
    studentExam = open("studentExam", 'r')
    index = 0
    numCorrect = 0

    for answerLine, studentLine in zip(answerKey, studentExam):
        answer = answerLine.split()
        studentAnswer = studentLine.split()
        if studentAnswer != answer:
            print("You got question number", index + 1, "wrong\nThe correct answer was", answer, "but you answered",
                  studentAnswer)
            index += 1
        else:
            numCorrect += 1
            index += 1
    gradeAverage = int((numCorrect / 2) * 100)
    grade = numCorrect
    english = open('examResult','r')
    english.write(str(grade)[2])

有人可以告诉我为什么会出现此错误,因为在第一种方法中它运行良好,但是在第二种方法中却出现错误?

1 个答案:

答案 0 :(得分:0)

str(grade)[2]给出str(grade)的第三个字符,仅当grade是具有3个或更多数字的数字时才存在。