简体   繁体   中英

AttributeError: 'list' object has no attribute 'encode'

I have a list of unicode objects and want to encode them to utf-8, but encoding doesn't seem to work.

the code is here :

>>> tmp = [u' test context']
>>> tmp.encode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'encode'
>>>

I can't understand why there is no attribute encode

You need to do encode on tmp[0] , not on tmp .

tmp is not a string. It contains a (Unicode) string.

Try running type(tmp) and print dir(tmp) to see it for yourself.

您需要单独解码列表中的每个元素

[x.encode('utf-8') for x in tmp]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM