Encode Python list to UTF-8

2019-01-14 17:21发布

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?

2条回答
孤傲高冷的网名
2楼-- · 2019-01-14 18:02
>>> items =  [u'a', u'b', u'c']
>>> [x.encode('utf-8') for x in items]
['a', 'b', 'c']
查看更多
太酷不给撩
3楼-- · 2019-01-14 18:21

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.

查看更多
登录 后发表回答