環(huán)境: Centos7 + Python3.5.4
1.在Python中也存在字節(jié)型數(shù)據(jù)(bytes)和字符型數(shù)據(jù)(unicode),不過這兩者在Python2和Python3中卻有點(diǎn)不同。
Py2 和 Py3 都用 str 類型來表示字符串,不過在Py2中,str跟bytes是等價(jià)的;在Py3中,str跟unicode是等價(jià)的。另外,值得注意的是,在Py2中,bytes跟unicode是等價(jià)的;在Py3中則是不等的。詳情見下圖或者在Python命令行嘗試。
Python2

Python3

2.字節(jié)型轉(zhuǎn)換為字符型可以理解為解碼(decode),反之則是編碼(encode)。下面只展示Python3的情況
首先,我們可以通過 locale 來查看本機(jī)的默認(rèn)編碼方式,貌似Linux默認(rèn)是utf-8,windows默認(rèn)是gbk。
>>>import locale
>>>locale.getpreferredencoding(False)
其次,我們將嘗試 字符->字節(jié)
>>>a = '學(xué)習(xí)'
>>>ae = a.encode('utf-8')
b'\xe5\xad\xa6\xe4\xb9\xa0'
字節(jié)->字符
>>> ae.decode('utf-8')
'學(xué)習(xí)'
最后,因?yàn)樵赑y3中,字符串與unicode是等價(jià)的,所以字符串是沒有decode方法的,如果調(diào)用該方法則會(huì)報(bào)錯(cuò)
>>> a.decode('utf-8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'decode'