Python3 ‘str‘ object has no attribute ‘decode‘. Did you mean: ‘encode‘?

  • AttributeError: 'str' object has no attribute 'decode'. Did you mean: 'encode'?

    原因:一般是因为 str 的类型本身不是 bytes,所以不能解码。

  • 这是由于 py2py3 字符串 编码上的区别 导致的。

    # 这是 py2 的写法
    name = "中国"
    name_utf8 = name.decode('utf-8')
    print(name, name_utf8)
    # 输出:中国 中国
    
    # 这是 py3 的写法
    name = "中国"
    name_bytes = name.encode('utf-8')
    name_utf8 = name_bytes.decode('utf-8')
    print(name, name_bytes, name_utf8)
    # 输出:中国 b'\xe4\xb8\xad\xe5\x9b\xbd' 中国
    
    # 不填使用默认编码格式
    name = "中国"
    name_bytes = name.encode()
    name_utf8 = name_bytes.decode()
    print(name, name_bytes, name_utf8)
    
    ## 概念:
    1、普通 str:可理解的语义。
    2、字节流 str(bytes):0101010101,字节类型其实就是 2 进制格式,
       不过为了易于理解和计算,通常用 16 进制来表示,
       也就是 b'\xe4\xb8\...,b 开头代表是 bytes 类型。
    
    ## 语法
    1、Encode(编码):把普通字符串 转为 机器可识别的 bytes。
    2、Decode(解码):把bytes转为字符串。
    
    ## 语法记忆小技巧
    1、编码 encode,就是把你认识的转为机器认识的。
    2、解码 decode,就是把机器认识的解释为人能读懂的。
    
    ## 差异
    1、py3 的 str 默认不是 bytes,所以不能 decode,只能先 encode 转为 bytes,再 decode。
    2、py2 的 str 默认是 bytes,所以能 decode。
    
    ## 结论
    所以 str.decode 本质是 bytes 类型的 str 的 decode
    py3 经常出现 AttributeError: ‘str’ object has no attribute ‘decode’
    

你可能感兴趣的:(Python,python)