Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change unicode string into list?

Tags:

python

I get the data as type <type 'unicode'>

u'{0.128,0.128,0.133,0.137,0.141,0.146,0.15,0.155,0.159,0.164,0.169,0.174,0.179,0.185,0.19,0.196,0.202,0.208,0.214,0.22}'  

I want to convert this to list like

[0.128,0.128,0.133,0.137,0.141,0.146,0.15,0.155,0.159,0.164,0.169,0.174,0.179,0.185,0.19,0.196,0.202,0.208,0.214,0.22]

How can I do this with python?

Thank you

like image 831
daydreamer Avatar asked Dec 17 '22 07:12

daydreamer


1 Answers

Just like that:

>>> a = u'{0.128,0.128,0.133,0.137,0.141,0.146,0.15,0.155,0.159,0.164,0.169,0.174,0.179,0.185,0.19,0.196,0.202,0.208,0.214,0.22}'
>>> [float(i) for i in a.strip('{}').split(',')]
[0.128, 0.128, 0.133, 0.137, 0.141, 0.146, 0.15, 0.155, 0.159, 0.164, 0.169, 0.174, 0.179, 0.185, 0.19, 0.196, 0.202, 0.208, 0.214, 0.22]

Unicode is very similar to str and you can use .split(), as well as strip(). Furthermore, casting to float works the way it works for str.

So, first strip your string of the unnecessary curly braces ({ and }) by using .strip('{}'), then split the resulting string by commas (,) using .split(','). After that you can just use list comprehension, converting each item to float, as in the example above.

like image 179
Tadeck Avatar answered Dec 29 '22 23:12

Tadeck