[英]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.