I am pulling out a row from a file. Row looks like this:
['(27.0, 168.0)', '(32.0, 550.0)', '(88.0, 835.0)', '(46.0, 660.0)', '(38.0, 430.0)', '(34.0, 285.0)', '(72.0, 701.0)', '(29.0, 434.0)', '(0, 2)']
Is there a way to convert those strings into tuples? I tried x.strip() for x in row but it didn`t help.
Thanks in advance.
Would this work for you ?
import ast
string = "['(27.0, 168.0)', '(32.0, 550.0)', '(88.0, 835.0)', '(46.0, 660.0)', '(38.0, 430.0)', '(34.0, 285.0)', '(72.0, 701.0)', '(29.0, 434.0)', '(0, 2)']"
string = string.replace("'", "")
string = ast.literal_eval(string)
The output is :
In : string
Out:
[(27.0, 168.0),
(32.0, 550.0),
(88.0, 835.0),
(46.0, 660.0),
(38.0, 430.0),
(34.0, 285.0),
(72.0, 701.0),
(29.0, 434.0),
(0, 2)]
In : type(string)
Out: list
In : [type(x) for x in string]
Out: [tuple, tuple, tuple, tuple, tuple, tuple, tuple, tuple, tuple]
The ast module evaluates strings which I think is what you're looking for if I understand correctly.
This should do the trick.
from ast import literal_eval as make_tuple
a = ['(27.0, 168.0)', '(32.0, 550.0)', '(88.0, 835.0)', '(46.0, 660.0)', '(38.0, 430.0)', '(34.0, 285.0)', '(72.0, 701.0)', '(29.0, 434.0)', '(0, 2)']
b = [make_tuple(x.strip()) for x in a]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With