[Solved] How to fix the error “index out of range”


Your error occurs if you acces a list/string behind its data. You are removing things and access

for i in range(len(data)):
     ...
     data[i] += "," + data[i + 1]

If i ranges from 0 to len(data)-1 and you access data[i+1] you are outside of your data on your last i!


Do not ever modify something you iterate over, that leads to desaster. Split the string yourself, by iterating it character wise and keep in mind if you are currently inside " ... " or not:

data="str10, "str12, str13", str14, "str888,999", str56, ",123,", 5" 

inside = False
result = [[]]
for c in data:
    if c == ',' and not inside:
        result[-1] = ''.join(result[-1]) # add .strip() to get rid of spaces on begin/end
        result.append([])
    else:
        if c == '"':
            inside = not inside
        result[-1].append(c)

result[-1] = ''.join(result[-1]) # add .strip() to get rid of spaces on begin/end
print(result) 
print(*result, sep = "\n")

Output:

['str10', ' "str12, str13"', ' str14', ' "str888,999"', ' str56', ' ",123,"', ' 5']

str10
 "str12, str13"
 str14
 "str888,999"
 str56
 ",123,"
 5

Add .strip() to the join-lines to get rid of leading/trailing spaces:

result[-1] = ''.join(result[-1]).strip()

solved How to fix the error “index out of range”