使用的原因:基于URL解析报文的时候,要使用str类型,但是提供的确实bytes类型,报错:
TypeError: must be str, not bytes
所以就把bytes类型转换为str类型汇总下,以便日后查看bytes1 = b'Hello my world' str1 = 'Hello my world' print(type(bytes1)) print(type(s1)) # bytes类型转换为str类型 # 方法1: str()函数 str2 = str(bytes1, encoding="utf-8") print(str2) print(type(str2)) # 方法2: bytes.decode()函数 str3 = bytes.decode(bytes1) print(str3) print(type(str3))
结论,通过两种发杠均可将bytes转换为str:
<class 'bytes'> <class 'str'> Hello my world <class 'str'> Hello my world <class 'str'>