In my programm I take some data (variable raw) out of a database and have to use it.
When using print(raw)
this gets displayed: ('x1 y1 z1 nx2 y2 z2 nx3 y3 z3 nx4 y4 z4',)
(raw has over 450 elements so I shortened it)
Now I have to get x1
and y1
and forward them to another module. To do this I first split up raw
pass_str = str(raw).split(f'\n') print(pass_str)
The printed result was the following: ["('x1 y1 z1 ", 'x2 y2 z2', 'x3 y3 z3', 'x4 y4 z4',)"]
To get the single parameters I used a for-loop so I can first get x1, y1
and then x2, y2
and so on:
for i in range(len(pass_str)): pass_data = pass_str[i].split() el = pass_data[0].split("'", 1)[1] az = pass_data[1] task = 'P' + ' ' + az + ' ' + el client.send_request(task)
The first iteration of the for-loop works without any problems. In the second iteration the for-loop stops after pass_data = pass_str[i].split()
The problem seems to occure in the line for “el = …”, where I get the error
Error: list index out of range
Advertisement
Answer
You’re trying to use the string representation of a list, then parse that to extract some meaningful data. The string representation of a list is not a very useful data structure to try and work with! Whereas a list itself is.
raw = [('x1 y1 z1 \nx3 y2 z1',)] pass_str = str(raw).split(f'\n') # ["[('x1 y1 z1 \", "x3 y2 z1',)]"]
You should be converting the string into a list, and accessing it properly.
raw = [('x1 y1 z1 \nx3 y2 z1',)] pass_strings = raw[0][0].split('\n') #["x1 y1 z1","x3 y2 z1"] for pass_string in pass_strings: pass_data = pass_string.split() #['x1','y1','z1'] el = pass_data[0] az = pass_data[1] task = 'P' + ' ' + az + ' ' + el print(task) #> P x1 y1