首页 > 解决方案 > AttributeError:“str”对象没有属性“decode”。Python 3 和 Python 2.7 兼容性

问题描述

我正在尝试比较两个字符串列表:

text_line = [u'\u2502 id               \u2502 na \u2502 email   \u2502', u'\u2502                  \u2502 me \u2502         \u2502']  
print( text_line == [
             "│ id               │ na │ email   │",
             "│                  │ me │         │",
])

它给出警告:UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode and prints False

如果我在列表中每个字符串的末尾添加.decode('utf-8')它在 Python 2.7 中可以正常工作并打印True

print( text_line == [
       "│ id               │ na │ email   │".decode('utf-8'),
       "│                  │ me │         │".decode('utf-8'),
])

但它在 Python 3.X 中不起作用,出现以下错误:

AttributeError:“str”对象没有属性“decode”

有没有一种适用于 Python 2.7 和 Python 3.X 的方法?

标签: pythonunicode

解决方案


推荐阅读