python bytes和str之间的转换

Python 3最重要的新特性大概要算是对文本和二进制数据作了更为清晰的区分。文本总是Unicode,由str类型表示,二进制数据则由bytes类型表示。Python 3不会以任意隐式的方式混用str和bytes,正是这使得两者的区分特别清晰。你不能拼接字符串和字节包,也无法在字节包里搜索字符串(反之亦然),也不能将字符串传入参数为字节包的函数(反之亦然). 

bytes字节

str字符串

# bytes object
  b = b"example"
 
  # str object
  s = "example"
 
  # str to bytes
  bytes(s, encoding = "utf8")
 
  # bytes to str
  str(b, encoding = "utf-8")
 
  # an alternative method
  # str to bytes
  str.encode(s)
 
  # bytes to str
  bytes.decode(b)

bytes解码成str,str编码成bytes

b1=b'sdf'
s1='sag'
print(type(b1),type(s1))#<class 'bytes'> <class 'str'>
b2=b1.decode('utf8')#bytes按utf8的方式解码成str 
print(type(b2))#<class 'str'>
s2=s1.encode('utf8')#str按utf8的方式编码成bytes
print(type(s2))#<class 'bytes'>

猜你喜欢

转载自www.cnblogs.com/z-x-y/p/10260576.html