Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove quotes from a list of strings (that are supposed to be tuples) [duplicate]

Tags:

python

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.

like image 957
Timofey Goritsky Avatar asked Jan 22 '26 05:01

Timofey Goritsky


2 Answers

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.

like image 156
Luci Avatar answered Jan 24 '26 19:01

Luci


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]
like image 43
Will Da Silva Avatar answered Jan 24 '26 17:01

Will Da Silva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!