1.相关异常
我们在处理交换的数据时经常遇到这样的异常:
TypeError: can't use a string pattern on a bytes-like object
TypeError: a bytes-like object is required, not 'str'
...
很显然,我们要处理的数据是一个字节对象,即Python中的bytes或bytearray类型,但是我们却使用了处理字符串的方法。
2.相关方法
在字符串与字节对象之间进行转换,Python提供了字符串的encode()方法和字节对象的decode()方法。
1) encode(encoding="utf-8", errors="strict")方法该方法将字符串(str)转换为某种编码的字节对象。
- 参数encoding默认为utf-8(亦即utf_8或utf8),表示默认转换为utf-8编码的字节对象
https://docs.python.org/3/library/codecs.html#standard-encodings
- errors默认'strict',表示编码过程中出现错误将抛出UnicodeError
2) decode(encoding="utf-8", errors="strict")方法
该方法将字节对象解码为原始的字符串。
该方法的参数与encode()方法完全一致,此处不再赘述。
在网络传输过程中,客户端要发送的字符串首先要经过encode()编码转换为字节对象,才能在网络中传输。在服务端,首先要decode()解码,将接收到的字节对象转换为字符串,然后才能进行后续处理。
3. str()中的编解码
我们通常使用str()将一个对象转换为字符串,事实上这是在调用str类的构造函数。
str类的构造函数定义如下:
class str(object=b'', encoding='utf-8', errors='strict')
可见,在使用str()将一个对象转换为字符串时,就是使用了decode()方法的默认参数。
参考链接:
https://docs.python.org/3/library/stdtypes.html#str.encode
https://docs.python.org/3/library/stdtypes.html#bytes.decode
https://docs.python.org/3/library/codecs.html#standard-encodings
https://docs.python.org/3/library/stdtypes.html#str