Python3--TypeError:a bytes-like object is required, not‘str’

这是 python3 的异常,python2 中并无该异常

出现此类问题的场景如下:

1. 文件读取或写入,是否以 'b’ 二进制方式操作,显然这种方式为 byte

2. 网络编程,是否传输 二进制 字节

解决思路

str 通过 encode 方法编码为 byte

encode(self, encoding='utf-8', errors='strict')

或者通过 b'' 方法

byte 通过 decode 方法解码为 str

decode(self, *args, **kwargs)

示例

s1 = 'abc'
print(type(s1))      # <class 'str'>

s2 = s1.encode()
print(type(s2))     # <class 'bytes'>

s3 = s2.decode()
print(type(s3))     # <class 'str'>

s4 = b'123'
print(type(s4))     # <class 'bytes'>

参考资料:

原文地址:https://www.cnblogs.com/yanshw/p/12356484.html