Python 'int' object is not subscriptable

4k views Asked by At

Im trying to read a file and make sure that each value is in order. I dont think im converting the string into the integer correctly. Here is some of my code. I am also trying to use flags.

fileName = input("What file name? ")
infile = open(fileName,'r')
correct_order_flag = False
i = 0
line = infile.readline()
while line !="": 
    for xStr in line.split(" "):
        if eval(xStr) [i] < i:
            correct_order_flag = True
        else:
            correct_order_flag = False
    i = i+1
if correct_order_flag:
    print("Yes, the numbers were in order")
else:
    print("No, the numbers were not in order")
count = i - 1
print("There were", count, "numbers.")
4

There are 4 answers

0
Chris Bunch On

You are correct - you are indicating with eval(xStr)[i] that eval(xStr) is an array, and thus can be subscripted. What it looks like you may want (since you say you want to convert the string to an int) is just int(xStr), to make that whole line:

if int(xStr) < i:
0
Zaur Nasibov On

For starters, you don't read the whole file at all. Try this:

with open(fileName) as f:
    for line in f:
        # here goes your code

Not sure though, what do you mean by "each value is in order", but using eval() is a VERY bad idea for any purpose.

0
HuntR2 On

I would like to add that because you are comparing xstr[i] to i that unless your first number is less than zero the flag will change, meaning that the sequence 1 2 3 4 5 would print out saying "NO, the numbers were not in order"

0
Raymond Hettinger On

As Chris indicated, int(s) is the preferred way to convert a string to an integer. eval(s) is too broad and can be a security risk when evaluating data from an untrusted source.

In addition, there is another error in the script. The *correct_order_flag* is being set on every iteration, so one entry with incorrect order can be masked by a subsequent entry in the correct order. Accordingly, you should break out of the loop when incorrect ordering is found.