Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unicode to python object conversion

Tags:

python

Given a unicode object:

u'[obj1,obj2,ob3]' 

How do you convert it to a normal list of objects?

like image 261
mossplix Avatar asked Dec 21 '22 17:12

mossplix


2 Answers

import ast
s = u'[obj1,obj2,ob3]'
n = ast.literal_eval(s)
n
[obj1, obj2, ob3]
like image 58
Eklavya Avatar answered Jan 11 '23 05:01

Eklavya


Did you mean this? Converting a unicode string to a list of strings. BTW, you need to know the encoding when dealing with unicode. Here I have used utf-8

>>> s = u'[obj1,obj2,ob3]'
>>> n = [e.encode('utf-8') for e in s.strip('[]').split(',')]
>>> n
['obj1', 'obj2', 'ob3']
like image 27
Senthil Kumaran Avatar answered Jan 11 '23 05:01

Senthil Kumaran