how to convert coordinate string list to tuple type in python

Question:

I want to convert list of coordinates in string to tuple without using external library

type list

a = ['(1,4)', '(5,8)']

Output

type tuple

a = [(1,4), (5,8)]

what i did

a = tuple(a)

OUTPUT GETTING (‘(1,4)’, ‘(5,8)’)

OUTPUT EXPECTED ((1,4), (5,8))

Asked By: amit

||

Answers:

There isn’t a super clean way to do this in general. However, you can use ast.literal_eval to convert individual elements to a tuple such as:

from ast import literal_eval
a = ['(1,2)', '(3,4)']
output_tuple = tuple(literal_eval(x) for x in a)

You can find the documentation for literal_eval here.

Answered By: BTables

There you go

a = ['(1,4)', '(5,8)']
a = tuple([tuple(map(int, x[1:-1].split(','))) for x in a])

print(a)
Answered By: Rodrigo Mangueiras

if you want to make it list like that and output with type tuple
you have 2 method

method 1:

a = ['(1,4)', '(5,8)']
a = tuple([eval(x) for x in a])

print(a)

method 2: (using internal library)

from ast import literal_eval

a = ['(1,4)', '(5,8)']
a = tuple([literal_eval(x) for x in a])
print(a)
Answered By: Indra Dwi Aryadi
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.