Python:TypeError:“int”对象不可下标,IndexError:string索引超出范围

2024-04-25 02:21:17 发布

您现在位置:Python中文网/ 问答频道 /正文

如何标记/分离函数中传递的输入? 例如,如果12356作为输入传递,我想访问第三个符号,也就是3,我该怎么办? 我在函数中尝试了以下代码,但出现了错误:

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

代码:

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

s_test(12356)

在另一个程序中,当我执行同样的操作时,我得到一个错误:

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

谢谢


Tags: 函数代码标记testinputobjectisdef
1条回答
网友
1楼 · 发布于 2024-04-25 02:21:17

主要问题有以下几点。你知道吗

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

您正在这种类型的列表["", "0", "1", "9", "10", "11", "12", "13"]上执行for循环,该列表在first元素中包含1空字符串。因此在第一次迭代中,一个空值被传递给NDRecognize(input, dates))函数到每个for循环中。这就是NDRecognize(input, dates))函数出错的原因。你知道吗

我希望你明白我在说什么。非常感谢。你知道吗

相关问题 更多 >