Home > Back-end >  I am new to python and am having trouble printing an element of a list
I am new to python and am having trouble printing an element of a list

Time:07-12

the result looks like this:

[([[17, 11], [57, 11], [57, 61], [17, 61]], '2', 1.0)]

I just want the 2 printed (second element of the list?) but keep getting "list index out of range" error.

Here is the code I am trying to use to print the list element:

print (result[1][0])

full code snippit:

number = 1
sresult = ''
reader = easyocr.Reader(['en'])
for number in range (1,82):
    result = reader.readtext(datadrop  str(number) '.png')
    print (result[1][0])
    sresult = str(result)  sresult
print (sresult)

CodePudding user response:

The list has only one tuple in it ([(...)]) so accessing result[1][0] will give an IndexError. You can solve by changing your code to this -

number = 1
sresult = ''
reader = easyocr.Reader(['en'])
for number in range (1,82):
    result = reader.readtext(datadrop  str(number) '.png')
    print (result[0][1][0])
    sresult = str(result)  sresult
print (sresult)

I assume you want to access the second item in the tuple.

CodePudding user response:

this worked:

number = 1
sresult = ''
reader = easyocr.Reader(['en'])
for number in range (1,82):
    result = reader.readtext(datadrop  str(number) '.png')
    if len(result) != 0:
        print (result[0][1][0])
    sresult = str(result)  sresult
print (sresult)

I had to add a way to handle empty results and used the [0][1][0] solution from sr0812

  • Related