补充:发现廖雪峰老师这个讲的很好,大家可以看廖雪峰老师字符编码讲解
python3与python2不同,python使用utf-8的编码格式,而python使用Unicode格式。
以下是python编码解码的示意图。
python中字符串的编码格式默认是Unicode的。详见下面代码
>>> s = "你好"
>>> s.decode("编码格式")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'decode'
这里unicode不提供解码,因为在python3默认就是Unicode,所以可以看作无编码,没有decode方法。
>>> s1 = s.encode("utf-8")
Unicode格式的字符串可以转化为utf-8和gbk等其他编码,返回的结果是<class 'bytes'>
>>> s1
b'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> a = s1.decode("utf-8")
>>> a
'你好'
>>> type(a)
<class 'str'>
经过编码后的得到的bytes(好像是字节串吧,错误的话请指证),可以解码成对应的Unicode类型(无编码)的字符串,直接显示。
>>> s1
b'\xe4\xbd\xa0\xe5\xa5\xbd'
解码后s1的自身编码不变
>>> s1.encode("编码类型")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'bytes' object has no attribute 'encode'
其他的编码类型不能转换编码,如果要转换编码,要先解码为Unicode在编码为需要的编码