編碼encode:字符串str 類型 --> 字節bytes 類型 (姑且認爲是設置存儲格式的過程,如有不對請批評指正)
解碼decode: 字節類型 --> 字符串類型
>>> str1 = "a"
>>> type(str1)
<class 'str'>
>>> bytes1 = str1.encode('utf-8')
>>> type(bytes1)
<class 'bytes'>
>>> bytes1
b'a'
區分字符串前的b與u:
1.無前綴 & u前綴(str對象)
字符串默認創建即以Unicode編碼存儲,可以存儲中文。
string = 'a' 等效於 string = u'a'
Unicode中通常每個字符由2個字節表示
u'a' 即 u'\u0061' 實際內存中爲 [0000 0000] [0110 0001]
2.b前綴(bytes對象)
字符串存儲爲Ascll碼,無法存儲中文。
每個字符由1個字節表示(8位)
b'a' 即 b'\x61' 實際內存中爲 [0110 0001]
>>> a = b'hello'
>>> b = u'hello'
>>> type(a)
<class 'bytes'>
>>> type(b)
<class 'str'>
>>> h = "中國"
>>> h1 = h.encode('utf-8') # 將字符串以utf-8格式編碼
>>> h1
b'\xe4\xb8\xad\xe5\x9b\xbd'
>>> h1.decode('ascii') # 中文無法用ascii格式編碼
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
>>> h1.decode('utf-8') # 將字節對象以utf-8的方式解碼
'中國'