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进行解码得到的结果,将无法还原原来的字符串内容
     
  • 相关阅读:
    POJ3764 The xorlongest Path
    POJ1733 Parity game
    POJ3301 Texas Trip
    POJ2135 Farm Tour
    POJ2516 Minimum Cost
    Mem478
    PROJECTEULER48
    POJ1201 Intervals
    CSS 伪元素 (Pseudoelements)
    JQuery显示隐藏层
  • 原文地址:https://www.cnblogs.com/yinsjun/p/6951588.html
Copyright © 2011-2022 走看看