zoukankan      html  css  js  c++  java
  • python 3使用binascii方法的报错解决

    环境是python 3

    问题:

    使用binascii方法一直出现报错TypeError: a bytes-like object is required, not 'str'

    #coding: utf-8
    
    import binascii
    
     a = 'worker'
     b = binascii.b2a_hex(a)
     print(b)
    
    #b = binascii.b2a_hex(a)
    #TypeError: a bytes-like object is required, not 'str'

    解决方法:

    后来修改如下代码才会不报错

    b = binascii.b2a_hex(a.encode())

    原理:

    在新版本的python3中,取消了unicode类型,代替它的是使用unicode字符的字符串类型(str),字符串类型(str)成为基础类型如下所示,而编码后的变为了字节类型(bytes)但是两个函数的使用方法不变:

         decode              encode

    bytes ------> str(unicode)------>bytes

    u = '中文' #指定字符串类型对象u
    str = u.encode('gb2312') #以gb2312编码对u进行编码,获得bytes类型对象str
    u1 = str.decode('gb2312')#以gb2312编码对字符串str进行解码,获得字符串类型对象u1
    u2 = str.decode('utf-8')#如果以utf-8的编码对str进行解码得到的结果,将无法还原原来的字符串内容
     
  • 相关阅读:
    智能汽车无人驾驶资料调研(一)
    Python 学习
    关于中英文排版的学习
    UI Testing
    项目管理:第一次参与项目管理
    自动化测试用什么语言好
    什么是自动化测试
    睡眠的重要性
    python的pip和cmd常用命令
    矩阵的切片计算(截取)
  • 原文地址:https://www.cnblogs.com/yinsjun/p/6951588.html
Copyright © 2011-2022 走看看