【问题标题】:AttributeError: 'list' object has no attribute 'encode'AttributeError:“列表”对象没有属性“编码”
【发布时间】:2018-03-20 18:21:16
【问题描述】:

我有一个 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'
>>>

我不明白为什么没有属性编码

【问题讨论】:

    标签: python encoding


    【解决方案1】:

    您需要在tmp[0] 上执行encode,而不是在tmp 上。

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

    尝试运行type(tmp)print dir(tmp) 亲自查看。

    【讨论】:

    • tmp 不是字符串。它包含一个(Unicode)字符串。 是的,你绝对正确!非常感谢!
    【解决方案2】:

    您需要单独对列表中的每个元素进行 unicode

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

    【讨论】:

      猜你喜欢
      • 2021-09-11
      • 2019-12-30
      • 2021-07-05
      • 2019-02-02
      • 1970-01-01
      • 1970-01-01
      • 2018-01-16
      • 2016-05-14
      • 2016-12-21
      相关资源
      最近更新 更多