AttributeError:'list'对象没有属性'encode'

mt0*_*t0s 19 python encoding

我有一个unicode对象列表,并希望将它们编码为utf-8,但编码似乎不起作用.

代码在这里:

>>> 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'
>>>
Run Code Online (Sandbox Code Playgroud)

我无法理解为什么没有属性编码

Mik*_*kel 33

你需要做encodetmp[0],不是tmp.

tmp不是一个字符串.它包含一个(Unicode)字符串.

尝试跑步type(tmp)print dir(tmp)亲自看看.


Pra*_*wal 7

您需要分别对列表的每个元素进行统一编码

[x.encode('utf-8') for x in tmp]
Run Code Online (Sandbox Code Playgroud)