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
Similar Posts:
- [Solved] Typeerror: incorrect padding occurred in python3 Base64 decoding
- UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 0-1:
- attributeerror: ‘str’ object has no attribute ‘decode’
- python 3.6 socket tcp Connect TypeError: a bytes-like object is required, not ‘str’
- [Solved] Python Numpy Data load error: Unicode error: unpicking a python object failed: Unicode decodeerror
- [Solved] Python Error: UnicodeDecodeError: ‘gb2312’ codec can’t decode byte 0xa4 in position… : illegal multibyte sequence
- TypeError: the JSON object must be str, not ‘bytes’
- Python Error: Socket TypeError: a bytes-like object is required, not ‘str’ [How to Solve]
- [Solved] Django Run Error: TypeError: object supporting the buffer API required
- Python Open File SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in …