User-given input produces TypeError: list indices must be integers or slices, not str
User-given input produces TypeError: list indices must be integers or slices, not str
我是Python的新手,当我输入学生姓名时会出现我的数据,但我无法修改我的数据。出现以下错误消息:
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 包含用户输入内容的字符串;您需要明确地将其转换为整数:
ans = input("Enter the number to modify :")
应该是
ans = int(input("Enter the number to modify :"))
我是Python的新手,当我输入学生姓名时会出现我的数据,但我无法修改我的数据。出现以下错误消息:
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 包含用户输入内容的字符串;您需要明确地将其转换为整数:
ans = input("Enter the number to modify :")
应该是
ans = int(input("Enter the number to modify :"))