zoukankan      html  css  js  c++  java
  • 解决编码问题:AttributeError: 'str' object has no attribute 'decode'

    1. 问题发现:

    出现:读取文件,对其进行解码,出现错误,AttributeError: 'str' object has no attribute 'decode'

    解释:属性错误,str对象不包含‘decode’属性。

    2.原因解释:

    出现问题原因:str与bytes表示的是两种数据类型,str为字符串型,bytes为字节型。对str编码encode得到bytes,
    对bytes解码得到str,两者互为转换。而上面出现问题的原因是对str字符串使用了解码,显然是猪头不对马尾。

    3.解决方法:

    解决办法:删除decode(‘utf-8’)

    4.代码演示:

    txt = '你好,shiyi,很感谢你陪伴我的日子'
    #str->bytes encode
    txt = txt.encode('utf-8')
    print(type(txt))
    #bytes->str decode
    txt = txt.decode('utf-8')
    print(type(txt))

    5.结果展示:

    <class 'bytes'>
    <class 'str'>
    Process finished with exit code 0



  • 相关阅读:
    U盘支持启动windows和Linux
    emacs安装
    npm 安装指定的第三方包
    npm安装第三方包
    npm 安装淘宝镜像
    ssm 环境搭建
    gitBook安装简介
    git 博客搭建
    git 多人开发
    git ssh提交
  • 原文地址:https://www.cnblogs.com/maxxu11/p/12785872.html
Copyright © 2011-2022 走看看