Unicode to convert python objects

For a unicode object:

u'[obj1,obj2,ob3]' 

How to convert it to a regular list of objects?

+3
source share
4 answers
import ast
s = u'[obj1,obj2,ob3]'
n = ast.literal_eval(s)
n
[obj1, obj2, ob3]
+7
source

Did you mean this? Convert Unicode string to string list. By the way, you need to know the encoding when working with unicode. I used utf-8 here

>>> s = u'[obj1,obj2,ob3]'
>>> n = [e.encode('utf-8') for e in s.strip('[]').split(',')]
>>> n
['obj1', 'obj2', 'ob3']
+3
source

What you posted is a Unicode string. To encode it, for example. since UTF-8 usesyourutf8str = yourunicodestr.encode('utf-8')

0
source

When Unicode data does not display unicode u ...

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

Correction:

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

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


All Articles