Python3有兩種表示字符序列的類型: bytes 和 str. 前者的實(shí)例包含原始的字節(jié);后者的實(shí)例包含Unicode字符.
Python2也有兩種表示字符序列的類型: str 和 unicode. 與Python3不同的是,str 的實(shí)例包含原始的字節(jié); 而unicode的實(shí)例,則包含Unicode字符.
把Unicode字符表示為二進(jìn)制數(shù)據(jù)(也就是原始的字節(jié))有很多方法,實(shí)際上就是編碼. 最常見(jiàn)的編碼方式就是UTF8. 但是要切記, Python3中的 str實(shí)例和Python2中的unicode實(shí)例都沒(méi)有和具體的二進(jìn)制編碼形式相關(guān)聯(lián). 要想把Unicode字符轉(zhuǎn)換成二進(jìn)制數(shù)據(jù),就必須使用encode
方法.要是想把二進(jìn)制數(shù)據(jù)轉(zhuǎn)換成Unicode字符,則必須使用decode
方法.
在編寫Python程序的時(shí)候,一定要把編碼和解碼操作放在界面最外圍來(lái)做.程序的核心部分應(yīng)該使用Unicode字符類型,而且不要對(duì)字符編碼做任何假設(shè).這種方法可以使程序既能接受多種類型的文件編碼,同事又可以保證輸出的文本信息只采用一中編碼形式(最好是UTF8).
在通常的開發(fā)環(huán)境時(shí),我們經(jīng)常會(huì)碰到以下兩種情景:
- 開發(fā)者需要原始的字節(jié),這些字節(jié)是以UTF-8來(lái)編碼的.
- 開發(fā)者需要操作沒(méi)有特定編碼形式的Unicode字符.
下面給出兩種輔助函數(shù),以便在這兩種情況之間轉(zhuǎn)換,使得轉(zhuǎn)換后的輸入數(shù)據(jù)能夠符合開發(fā)者的預(yù)期.
Python3
接受str
或者bytes
, 返回str
def to_str(bytes_or_str):
if isinstance(bytes_or_str, bytes):
value = bytes_or_str.decode('utf8')
else:
value = bytes_or_str
return value
接受 str
或者bytes
, 返回bytes
def to_bytes(bytes_or_str):
if isinstance(bytes_or_str, str):
value = bytes_or_str.encode('utf8')
else:
value = bytes_or_str
return value
Python2
接受str
或者unicode
, 返回str
def to_py2_str(unicode_or_str):
if isinstance(unicode_or_str, unicode):
value = unicode_or_str.encode('utf8')
else:
value = unicode_or_str
return value
接受str
或者unicode
, 返回unicode
def to_unicode(unicode_or_str):
if isinstance(unicode_or_str, str):
value = unicode_or_str.decode('utf8')
else:
value = unicode_or_str
return value