Fetch separate coordinates from array list


s = [‘(2,-1)’, ‘(2,2)’]

these are 2 cordinates how can i convert them in this form so that variable x1,x2,y1,y2 contain there value (without using external library)

x1,y1 = 2,-1

x2,y2 = 2,2

I was trying in this way

for i in range(len(s)-1):
    p1 = s[i]
    p2  = s[i+1]
    print p1 ,p2
Asked By: amit



You could use ast.literal_eval to create a tuple from the string.

from ast import literal_eval
# ...
x1, y1 = literal_eval(s[i])
x2, y2  = literal_eval(s[i+1])
print(x1, y1, x2, y2)

Alternatively, remove the first and last character, split on comma, and convert each part to an int.

def parts(s):
    return map(int, s[1:-1].split(','))
# ...
x1, y1 = parts(s[i])
x2, y2  = parts(s[i+1])
Answered By: Unmitigated

You can use a comprehension to parse your list of strings

# You can replace int by float if needed
x1, y1, x2, y2 = [int(j) for i in s for j in i[1:-1].split(',')]
print(x1, y1)
print(x2, y2)

# Output
2 -1
2 2
Answered By: Corralien
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.