简体   繁体   English

用户给定的输入产生 TypeError:列表索引必须是整数或切片,而不是 str

[英]User-given input produces TypeError: list indices must be integers or slices, not str

I'm new to Python, it appear my data when I enter student name, but I can't modify my data.我是Python的新手,输入学生姓名时会出现我的数据,但我无法修改我的数据。 The following error message appeared:出现以下错误消息:

TypeError: list indices must be integers or slices, not str.
if userChoice == '1':
    allrec = []
    with open("student.txt") as fh:
        for line in fh:
            rec = line.strip().split(":")
            allrec.append(rec)
        skey = input("Please enter Student Name: ")
        flg = -1
        for cnt in range(len(allrec)):
            if skey in allrec[cnt][1]:
                flg = cnt
                break
        if flg != -1:
                print("1 -Student ID   :" + allrec[flg][0])
                print("2 -Name     :" + allrec[flg][1])
                print("3 -S1 Marks :" + allrec[flg][2])
                print("4 -S2 Marks :" + allrec[flg][3])
                print("5 -S3 Marks :" + allrec[flg][4])
                ans = input("Enter the number to modify :")

                allrec[cnt][ans] = input("Enter a new value: ")
                with open("suppliers.txt", "w") as fh:
                    for cnt in range(len(allrec)):
                        rec = ":".join(allrec[cnt]) + "\n"

input() returns a string containing whatever the user entered; input()返回一个包含用户输入的字符串; you need to explicitly transform it into an integer:您需要明确地将其转换为 integer:

ans = input("Enter the number to modify :")

should be应该

ans = int(input("Enter the number to modify :"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 类型错误:列表索引必须是整数或切片,而不是 str - TypeError: list indices must be integers or slices, not str “TypeError:list indices必须是整数或切片,而不是str” - “TypeError: list indices must be integers or slices, not str” TypeError:列表索引必须是整数或切片,而不是 str - TypeError: List indices must be integers or slices and not str “TypeError:列表索引必须是整数或切片,而不是 str” - "TypeError: list indices must be integers or slices, not str" TypeError:列表索引必须是整数或切片而不是 str - TypeError: list indices must be integers or slices not str 类型错误:列表索引必须是整数或切片,而不是 str - TypeError: list indices must be integers or slices, not str Python3-TypeError:列表索引必须是整数或切片,而不是str-List - Python3 - TypeError: list indices must be integers or slices, not str - List Python3:TypeError:列表索引必须是整数或切片,而不是str - Python3: TypeError: list indices must be integers or slices, not str 类型错误:列表索引必须是整数或切片,而不是 str #num 设置为 int - TypeError: list indices must be integers or slices, not str #num is set as a int TypeError:列表索引必须是整数或切片,而不是解析列表时的str - TypeError: list indices must be integers or slices, not str when parsing lists
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM