簡體   English   中英

如何修復錯誤“索引超出范圍”

[英]How to fix the error "index out of range"

我必須在字符串中用一些“”分割字符串我是python的初學者,請幫我QQ解決line3顯示“索引超出范圍”的問題

視窗

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

如果您訪問其數據后面的列表/字符串,則會發生您的錯誤。 您正在刪除內容和訪問權限

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM