天天看點

Python3中的bytes和str

Python 3最重要的新特性之一是對字元串和二進制資料流做了明确的區分。Python 3不會以任意隐式的方式混用str和bytes,你不能拼接字元串和位元組流,也無法在位元組流裡搜尋字元串(反之亦然),也不能将字元串傳入參數為位元組流的函數(反之亦然)。

unicode、str、bytes的關系

硬碟中一般編碼都是uft-8,而在記憶體中采用unicode編碼方式。

python中的str其實顯示的就是讀取unicode,str的記憶體格式就是unicode,是以了解為str就是unicode,unicode就是str。

bytes是對Unicode的encode, 如字元串的encode方法就可以将str轉為bytes類型;

在bytes和str的互相轉換過程中,實際就是編碼解碼的過程,必須顯式地指定編碼格式。

str bytes互相轉換

1. str bytes方法互相轉換

>>> s = "中文"
>>> s
'中文'
>>> type(s)
<class 'str'>
>>> b = bytes(s, encoding='utf-8')
>>> b
b'\xe4\xb8\xad\xe6\x96\x87'   #開頭的b表示這是一個bytes類型。\x 代表是十六進制
>>> type(b)
<class 'bytes'>

>>> s1 = str(b)
>>> s1
"b'\\xe4\\xb8\\xad\\xe6\\x96\\x87'"   #變成這樣子的串了。
>>> type(s1)
<class 'str'>
>>> s1 = str(b, encoding='utf-8')   #這樣是對的
>>> s1
'中文'
>>> type(s1)
<class 'str'>
           

總結:

從str到bytes,編碼;從bytes到str,解碼

從str到bytes,是編碼, 比特流=str(串,encoding=‘utf-8’)

從bytes到str,是解碼,串=bytes(比特流,encoding=‘utf-8’)

2. encode decode方法互相轉換

'''中文編碼'''
>>> a='中文'
>>> type(a)
str
>>> b=a.encode(encoding='utf-8')
>>> b
b'\xe4\xb8\xad\xe6\x96\x87'
 
'''中文解碼'''
>>> c=b.decode(encoding='utf-8')
>>> c
'中文'
 
'''可以省略解碼格式, python3預設utf-8'''
>>> d=b.decode()
>>> d
'中文'
 
'''英文編碼'''
>>> a='hello'
>>> b=a.encode(encoding='utf-8')
>>> b
b'hello'
 
'''英文解碼'''
>>> c=b.decode('utf-8')
>>> c
'hello'