如何修复错误“索引超出范围”

时间:2019-04-20 11:57:44

标签: python-3.x

我必须用字符串中的一些“”来分割字符串 我是python的初学者,请帮助我QQ 第3行显示“索引超出范围”的问题

windows

data = input().split(',')
for i in range(len(data)):
    for j in range(len(data[i])):
        if data[i][j] == '"':
            data[i] += "," + data[i + 1]
            data.pop(i + 1)
            if data[i + 1][j] == '"':
                data[i] += "," + data[i + 1]
                data.pop(i + 1)

    print(data[i])

样本输入:

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

示例输出:

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

1 个答案:

答案 0 :(得分:1)

如果您在其数据后面添加列表/字符串,则会发生错误。您正在删除内容并访问

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

如果i的范围从0len(data)-1,并且您访问了data[i+1],那么您在最后i的数据之外!


永远不要修改您迭代过的东西,否则会导致灾难。通过根据字符进行迭代来自己分割字符串,并记住当前是否在" ... "内:

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

输出:

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

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

在连接行中添加.strip(),以消除前导/后跟空格:

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