The environment is python 3
Problem:
Keep getting errors using the binascii method 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'
Solution:
Later, the following code will be modified to avoid error reporting
b = binascii.b2a_hex(a.encode())
Principle:
In the new version of Python 3, the Unicode type is cancelled and replaced by the string type (STR) using Unicode characters. The string type (STR) becomes the basic type as shown below, and the encoded becomes the byte type (bytes), but the use methods of the two functions remain the same:
decode encode
bytes ——> str(unicode)——> bytes
u = 'Chinese' # specify the string type object u str = u.encode('gb2312') # encode u with gb2312 encoding to get bytes type object str u1 = str.decode('gb2312') # decode the string str in gb2312 encoding to get the string type object u1 u2 = str.decode('utf-8')# If the result obtained by decoding str with the encoding of utf-8, the original content of the string will not be restored