AttributeError:“str”对象没有属性“decode”。Python 3和Python 2.7的兼容性

2024-10-02 18:16:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图比较两个字符串列表:

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相等比较无法将两个参数转换为Unicode并打印False

如果我在列表中每个字符串的末尾添加.decode('utf-8'),它在Python 2.7中运行良好,并打印True

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

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

AttributeError: 'str' object has no attribute 'decode'

有没有一种方法可以同时适用于Python2.7和Python3.X


Tags: 字符串textid警告列表emaillineunicode