Reputation: 3865
Given a unicode object:
u'[obj1,obj2,ob3]'
How do you convert it to a normal list of objects?
Upvotes: 4
Views: 8882
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
Reputation: 86
import ast
s = u'[obj1,obj2,ob3]'
n = ast.literal_eval(s)
n
[obj1, obj2, ob3]
Upvotes: 7
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
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