Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to convert a unicode list to a list containing python strings?

Template of the list is:

EmployeeList =  [u'<EmpId>', u'<Name>', u'<Doj>', u'<Salary>'] 

I would like to convert from this

EmployeeList =  [u'1001', u'Karick', u'14-12-2020', u'1$'] 

to this:

EmployeeList =  ['1001', 'Karick', '14-12-2020', '1$'] 

After conversion, I am actually checking if "1001" exists in EmployeeList.values().

like image 641
Karthick Avatar asked Aug 16 '13 11:08

Karthick


People also ask

How do you change a Unicode to a string in Python?

To convert Python Unicode to string, use the unicodedata. normalize() function. The Unicode standard defines various normalization forms of a Unicode string, based on canonical equivalence and compatibility equivalence.

How do you convert a string array to a list in Python?

Another way to convert a string to a list is by using the split() Python method. The split() method splits a string into a list, where each list item is each word that makes up the string. Each word will be an individual list item.


1 Answers

Encode each value in the list to a string:

[x.encode('UTF8') for x in EmployeeList] 

You need to pick a valid encoding; don't use str() as that'll use the system default (for Python 2 that's ASCII) which will not encode all possible codepoints in a Unicode value.

UTF-8 is capable of encoding all of the Unicode standard, but any codepoint outside the ASCII range will lead to multiple bytes per character.

However, if all you want to do is test for a specific string, test for a unicode string and Python won't have to auto-encode all values when testing for that:

u'1001' in EmployeeList.values() 
like image 103
Martijn Pieters Avatar answered Oct 07 '22 22:10

Martijn Pieters