user6867490 user6867490 - 2 months ago 8
Python Question

Python: TypeError: 'int' object is not subscriptable and IndexError: string index out of range

What's the way to tokenize/separate the input passed in the function?
For example, if

12356
is passed as an input, and I want to access, let's say 3rd symbol, which is
3
, what will I do?
I have tried the below code in my function, but it's giving error:

print(s[2]) IndexError: 'int' object is not subscriptable


Code:

def s_test(input):
s=input
print(s)
print(s[2])

s_test(12356)


In one other program, when I am doing the same, I am getting an error:

"IndexError: string index out of range" for the instruction print(s[2])


Thanks

Answer

The main problems are into the following function.

def TestComponents(months, days, years, seps):
    print("\nTest Months FSA")
    # print(months.m[0][1])
    for input in ["", "0", "1", "9", "10", "11", "12", "13"]:
        print("'%s'\t%s" % (input, NDRecognize(input, months)))
    print("\nTest Days FSA")
    for input in ["", "0", "1", "9", "10", "11", "21", "31", "32"]:
        print("'%s'\t%s" % (input, NDRecognize(input, days)))
    print("\nTest Years FSA")
    for input in ["", "1899", "1900", "1901", "1999", "2000", "2001", "2099", "2100"]:
        print("'%s'\t%s" % (input, NDRecognize(input, years)))
    print("\nTest Separators FSA")
    for input in ["", ",", " ", "-", "/", "//", ":"]:
        print("'%s'\t%s" % (input, NDRecognize(input, seps)))


def TestDates(dates):
    print("\nTest Date Expressions FSA")
    for input in ["", "12 31 2000", "12/31/2000", "12-31-2000", "12:31:2000",
                  "1 2 2000", "1/2/2000", "1-2-2000", "1:2:2000",
                  "00-31-2000", "12-00-2000", "12-31-0000",
                  "12-32-1987", "13-31-1987", "12-31-2150"]:
        print("'%s'\t%s" % (input, NDRecognize(input, dates)))

You are executing a for loop over this type of list ["", "0", "1", "9", "10", "11", "12", "13"] which contain 1 empty string in the first element. So in the first iteration an empty value is passed to the NDRecognize(input, dates)) function into every for loop. That's why an error occurred into the NDRecognize(input, dates)) function.

I hope you understand what I'm telling. Thank you.

Comments