Python Bytes和String相互转换
发现Python的在bytes数据转string的时候直接用str(xx)会多一个b'xxx'。然后就很麻烦,后来查了下发现bytes和String相互转换,要用encode和decode来转。才不会有问题
字节对象b
b = b"example"
字符串对象s
s = "example"
print(b)
print("example")
-----------------------
b'example'
example
将字符串转换为字节对象
b2 = bytes(s,encoding='utf8') #必须制定编码格式
print(b2)
-------------------
b'example'
字符串encode将获得一个bytes对象
b3 = str.encode(s)
b4 = s.encode()
print(b3)
print(type(b3))
print(b4)
----------------------
b'example'
<class 'bytes'>
b'example'
将字节对象decode将获得一个str对象
s2 = bytes.decode(b)
s3 = b.decode()
print(s2)
print(s3)
--------------------
example
example