参考:
- https://www.jb51.net/article/111864.htm
- https://blog.csdn.net/weixin_34910922/article/details/117536280
字符编码
字符串 -> [字符,] -> [字节组,] -> [字节,]
字符串由字符列表组成,字符经过编码为1或多个字节,字符串最终以字节序列的形式进行存储。
字节序列解码时,会根据编码方式,分隔得到字节组,转换为对应字符,再拼接为字符串。
默认编码方式
Python2中字符串默认使用ascii编码,Python3转为使用utf-8编码,通过sys.getdefaultencoding()可以查看。
Python2 str与unicode类型
Python2中没有专门的bytes数据类型,str与bytes功能相同,广义字符串则使用unicode类型表示。
- str: 字节序列,只能表示ascii字符,或其他十六进制数
- unicode: 可以表示字符集中所有字符
Python3 bytes与str类型
Python3新增加了bytes类型,
- bytes: 字节序列或字节串,8bits字节列表,能表示ascii字符,或其他十六进制数
- str: 字符串,可以表示字符集中所有字符
Python3 bytes与str转换
1. str -> bytes
字符串经过编码(encode)可以转换为字节序列。
my_str = "hello"
my_bytes = str.encode(my_str)
#my_bytes = bytes(my_str, encoding='utf-8')
print("my_str:", type(my_str))
print("my_bytes:", type(my_bytes))
2. bytes -> str
字节序列通过decode()方法,可以转换为字符串类型。
my_bytes = b"hello"
my_str = my_bytes.decode()
print("my_str:", type(my_str))
print("my_bytes:", type(my_bytes))