15
votes

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?

4
do you want output as list or joined string? - jamylak
you are reassigning the list variable to the first encoded letter - MikeL

4 Answers

49
votes
>>> items =  [u'a', u'b', u'c']
>>> [x.encode('utf-8') for x in items]
['a', 'b', 'c']
10
votes

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.

0
votes

You need encode your string not decode. You are provided list consists of a unicode sting. To represent unicode string as a string of bytes is known as encoding, use u'...'.encode. Then by using string.split() you can break encoded string down into smaller chunks ( strings )

0
votes

If you are looking for the output as a clean list without the unicodes:

import unicodedata

list = [u'a', u'b', u'c']
clean_list1 = [unicodedata.normalize("NFKD", x) for x in list1]
print(clean_list1)

Output:

['a', 'b', 'c']