Stagg Stagg - 6 months ago 10
Python Question

Convert a list of string into tuples

I have this list of strings :

['(39.2947500000, -76.6565600000)', '(39.3423900000, -76.5698300000)', '(39.3199500000, -76.6222000000)', '(39.2533200000, -76.6263600000)', '(39.3068100000, -76.6549700000)', '(39.2937500000, -76.6233700000)', '(39.3146700000, -76.6425300000)', '(39.3073300000, -76.6015900000)', '(39.2451900000, -76.6336400000)', '(39.3283000000, -76.5893200000)', '(39.3215400000, -76.6736800000)', '(39.3010000000, -76.5977400000)', '(39.3122600000, -76.6194200000)', '(39.3161400000, -76.5663900000)', '(39.3573500000, -76.6005300000)', '(39.3311200000, -76.6315100000)', '(39.3311200000, -76.6315100000)', '(39.2832900000, -76.5996300000)', '(39.2868200000, -76.6063900000)', '(39.3031200000, -76.6461100000)']


I need to convert this strings to tuples, so that the output is:

[(39.2947500000, -76.6565600000),(39.3423900000, -76.5698300000)......]


I tried to use float method but it gives the this error:

ValueError: could not convert string to float: (39.2947500000, -76.6565600000)

Thanks in advance

Answer
my_list = ['(39.2947500000, -76.6565600000)', '(39.3423900000, -76.5698300000)']
print [(float(x.split(',')[0][1:]), float(x.split(',')[1][1:-1])) for x in my_list]

This solution does not use eval (which I dislike using), it iterates over the strings, splits them on the ',', substrings them to remove the '(', ' ' and ')' and then casts them to a float