python3 bytes与str数据类型相互转换

bytes主要是给在计算机看的,string主要是给人看的

中间有个桥梁就是编码规则,现在大趋势是utf8

bytes对象是二进制,很容易转换成16进制,例如x64

string就是我们看到的内容,例如'abc'

string经过编码encode,转化成二进制对象,给计算机识别

bytes经过反编码decode,转化成string,让我们看,但是注意反编码的编码规则是有范围,xc8就不是utf8识别的范围

# bytes object  
 2  b = b"example"  
 3   
 4  # str object  
 5  s = "example"   
 6   
 7  # str to bytes  
 8  bytes(s, encoding = "utf8")  
 9   
10  # bytes to str  
11  str(b, encoding = "utf-8")  
12   
13  # an alternative method  
14  # str to bytes  
15  str.encode(s)   # 字符串转bytes
16   
17  # bytes to str   # bytes转字符串
18  bytes.decode(b)  

  

原文地址:https://www.cnblogs.com/zhangshijiezsj/p/14157049.html