mossplix
mossplix

Reputation: 3865

unicode to python object conversion

Given a unicode object:

u'[obj1,obj2,ob3]' 

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

Upvotes: 4

Views: 8882

Answers (4)

Matt Allan
Matt Allan

Reputation: 33

When unicode data doesn't show unicode u...

On exporting data from an excel table using openpyxl, my unicode was invisible. Use print repr(s) to see it

>>>print(data)
>>>print(type(data))
["Independent", "Primary/Secondary Combined", "Coed", "Anglican", "Boarding"]
<type 'unicode>
>>>print repr(data)
u'["Independent", "Primary/Secondary Combined", "Coed", "Anglican", "Boarding"]'

The fix:

>>>import ast    
>>>data = ast.literal_eval(entry)
>>>print(data)
>>>print(type(data))
["Independent", "Primary/Secondary Combined", "Coed", "Anglican", "Boarding"]
<type 'list'>

Upvotes: 0

Eklavya
Eklavya

Reputation: 86

import ast
s = u'[obj1,obj2,ob3]'
n = ast.literal_eval(s)
n
[obj1, obj2, ob3]

Upvotes: 7

Senthil Kumaran
Senthil Kumaran

Reputation: 56931

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']

Upvotes: 4

ThiefMaster
ThiefMaster

Reputation: 318568

What you posted is a unicode string. To encode it e.g. as UTF-8 use yourutf8str = yourunicodestr.encode('utf-8')

Upvotes: 0

Related Questions