'How to save these coordinates to variables in python
I have this string which is a response from 2captcha
{'captchaId': '69775358180', 'code':
'coordinates:x=100,y=285;x=147,y=299;x=226,y=316;x=262,y=131'}
how can I extract each x,y coordinate and save them to variable? I've played around with regex but cant quite figure it out.
Thanks
Solution 1:[1]
Heres a code to get the x and y coordinates and store them in their own list:
data ={'captchaId': '69775358180', 'code': 'coordinates:x=100,y=285;x=147,y=299;x=226,y=316;x=262,y=131'}
#this gets the 'x=100,y=285;x=147,y=299;x=226,y=316;x=262,y=131'
coordinates = data['code'].split(':')[1].split(';')
x_coordinates = []
y_coordinates = []
for pair in coordinates:
xy = pair.split(',')
x_coordinates.append(xy[0][2:])
y_coordinates.append(xy[1][2:])
print(x_coordinates) # ['100', '147', '226', '262']
print(y_coordinates) # ['285', '299', '316', '131']
If you need a single x or y coordinate just access them using the index of the list.
Solution 2:[2]
If you have a dictionary you could use this code to create a list of the co-ordinates as tuples.
data = {'captchaId': '69775358180', 'code':
'coordinates:x=100,y=285;x=147,y=299;x=226,y=316;x=262,y=131'}
coords =[(xy.split(',')[0][2:],xy.split(',')[1][2:] ) for xy in data['code'][12:].split(";")]
print(coords)
[('100', '285'), ('147', '299'), ('226', '316'), ('262', '131')]
If you wanted numeric co-ordinates:
coords =[(int(xy.split(',')[0][2:]),int(xy.split(',')[1][3:]) ) for xy in data['code'][12:].split(";")]
[(100, 85), (147, 99), (226, 16), (262, 31)]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | norie |
