user1021128
user1021128

Reputation: 1

Python 'int' object is not subscriptable

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.")

Upvotes: 0

Views: 4021

Answers (4)

Raymond Hettinger
Raymond Hettinger

Reputation: 226296

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.

Upvotes: 0

HuntR2
HuntR2

Reputation: 149

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"

Upvotes: 0

Zaur Nasibov
Zaur Nasibov

Reputation: 22659

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.

Upvotes: 1

Chris Bunch
Chris Bunch

Reputation: 89823

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:

Upvotes: 4

Related Questions