Home > database >  How I can fix this error IndexError: string index out of range
How I can fix this error IndexError: string index out of range

Time:11-11

I got IndexError: string index out of range error.

def get_int_arr(str):
    int_arr = []
    num_str = ""
    for i in range(len(str)):
        if str[i].isnumeric():
            num_str  = str[i]
            if not str[i 1].isnumeric():
                int_arr.append(num_str)
                num_str = ""
    return int_arr
print(get_int_arr("data 48 call 9 read13 blank0"))

CodePudding user response:

You should just append if the last character is numeric and not check the next one.

def get_int_arr(str):
    int_arr = []
    num_str = ""
    for i in range(len(str)):
        if str[i].isnumeric():
            num_str  = str[i]
            if i   1 == len(str) or not str[i   1].isnumeric():
                int_arr.append(num_str)
                num_str = ""
    return int_arr

Also, the snippet you posted above is not complete (it misses the first line of your function definition I guess) and using reserved keywords like str to name your variables/arguments is not a good practice.

CodePudding user response:

As far as I can tell, it seems that you want a list of all digits found in the string passed to get_int_arr. If that is the case then:

def get_int_arr(s):
    return [c for c in s if c.isdigit()]


print(get_int_arr("data 48 call 9 read13 blank0"))

...will emit:

['4', '8', '9', '1', '3', '0']

CodePudding user response:

It will work if you add a space at the end of str and change for i in range(len(str)): to for i in range(len(str)-1):

def get_int_arr(str):
    int_arr = []
    num_str = ""
    str =" " #Adding a space at the end of the string
    for i in range(len(str)-1):
        if str[i].isnumeric():
            num_str  = str[i]
            if not str[i 1].isnumeric():
                int_arr.append(num_str)
                num_str = ""
    return int_arr
print(get_int_arr("data 48 call 9 read13 blank0"))

#Output: ['48', '9', '13', '0']
  • Related