Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode Python list to UTF-8

I have a python list that looks like that:

list = [u'a', u'b', u'c']

Now I want to encode it in UTF-8. Therefore I though I should use:

list = list[0].encode("utf-8")

But print list gives only

a

meaning the first element of the list. Not even a list anymore. What am I doing wrong?

like image 345
Tom Avatar asked Jun 06 '13 08:06

Tom


People also ask

What does encoding =' UTF-8 do in Python?

UTF-8 is a byte oriented encoding. The encoding specifies that each character is represented by a specific sequence of one or more bytes.

What does encode () do in Python?

The encode() method encodes the string, using the specified encoding. If no encoding is specified, UTF-8 will be used.

How do you encode an array in Python?

To encode string array values, use the numpy. char. encode() method in Python Numpy. The arr is the input array to be encoded.


2 Answers

>>> items =  [u'a', u'b', u'c']
>>> [x.encode('utf-8') for x in items]
['a', 'b', 'c']
like image 126
jamylak Avatar answered Oct 05 '22 22:10

jamylak


list[0] is the first element, not a list. you are reassigning your list var to a new value, the utf-8 encoding of the first element.

Also, don't name your variables list, as it masks the list() function.

like image 31
njzk2 Avatar answered Oct 05 '22 23:10

njzk2