Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading