Change unicode string to list?

I get 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 a list e.g.

 [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?

thanks

+4
source share
2 answers

Just:

 >>> 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() . In addition, casting in float works the way it works for str .

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

+8
source

From the head and untested:

 data = u'your string with braces removed' aslist = [float(x) for x in data.split(',')] 
+4
source

Source: https://habr.com/ru/post/1382580/


All Articles