[英]How to fix the error "index out of range"
I have to split the string with some "" in the string I am a beginner in python, plz help me QQ With the problem that line3 shows "index out of range"我必须在字符串中用一些“”分割字符串我是python的初学者,请帮我QQ解决line3显示“索引超出范围”的问题
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])
sample input:样本输入:
'str10, "str12, str13", str14, "str888,999", str56, ",123,", 5'
sample output:示例输出:
str10
"str12, str13"
str14
"str888,999"
str56
",123,"
5
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
!如果
i
范围从0
到len(data)-1
并且您访问data[i+1]
,则您在最后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:将
.strip()
添加到连接线以去除前导/尾随空格:
result[-1] = ''.join(result[-1]).strip()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.