str和bytes的区别就是编码方式的不同:
1 str(unicode编码) ==> bytes(utf8/GBK..) ==> 存储, 传输 2 bytes = str.encode(‘utf-8‘) # 编码 3 str = bytes.decode(‘utf-8‘) # 解码
1 英文: 2 str: 表现方式==>‘a‘ 3 编码方式==>0101 unicode 4 5 bytes: 表现方式==>b‘a‘ 6 编码方式==>0101 utf8/GBK.. 7 8 9 中文: 10 str: 表现方式==>‘中‘ 11 编码方式==>0101 unicode 12 13 bytes: 表现方式==>b‘x\e9‘ 14 编码方式==>0101 utf8/GBK..
1 s = ‘a‘ 2 print (s, type(s)) # ‘a‘, <type ‘str‘> 3 4 5 s = u‘中文‘ 6 print(s, type(s)) # u‘\u4e2d\u6587‘, <type ‘unicode‘> 7 # 编码变成utf-8, 一个中文三个字节 8 s1 = s.encode(‘utf-8‘) 9 print(s1, type(s1)) # ‘\xe4\xb8\xad\xe6\x96\x87‘, <type ‘str‘> 10 11 12 # bytes和str是同一个类型 13 s1 = ‘a‘ 14 s2 = bytes(‘a‘) 15 print(s1 is s2) # True
原文:https://www.cnblogs.com/caihuajiaoshou/p/10585032.html