Effective Python 讀書筆記——第 3 條
Effective Python 讀書筆記——第 3 條
轉載請註明出處:https://blog.csdn.net/jpch89/article/details/84679777
第 3 條:瞭解 bytes、str 與 unicode 的區別
Python 3
中有兩種字串:
str
型別:它的例項包含Unicode
字元bytes
型別:它的例項包含原始的位元組
Python 2
中也有兩種字串:
unicode
型別:它的例項包含Unicode
字元str
型別:它的例項包含原始的位元組
二進位制資料 --> Unicode
encode
方法編碼Unicode
字元 --> 二進位制資料:decode
解碼
編碼和解碼的工作要放在介面最外圍,核心部分用 Unicode
字串。
並且讓程式可以接受多種文字編碼,而保證輸出一種編碼形式(最好是 UTF-8
)。
要針對 Python 3
和 Python 2
編寫兩個輔助 helper
函式
Python 3
- 總是返回
str
- 總是返回
bytes
def to_str(bytes_or_str):
if isinstance(bytes_or_str, bytes):
value = bytes_or_str. decode('utf-8')
else:
value = bytes_or_str
return value # Instance of str
def to_bytes(bytes_or_str):
if isinstance(bytes_or_str, str):
value = bytes_or_str.encode('utf-8')
else:
value = bytes_or_str
return value # Instance of bytes
Python 2
- 總是返回
unicode
- 總是返回
str
def to_unicode(unicode_or_str):
if isinstance(unicode_or_str, str):
value = unicode_or_str.decode('utf-8')
else:
value = unicode_or_str
return value # Instance of unicode
def to_str(unicode_or_str):
if isinstance(unicode_or_str, unicode):
value = unicode_or_str.encode('utf-8')
else:
value = unicode_or_str
return value # Instance of str
ASCII
碼相關知識補充
ASCII第一次以規範標準的型態發表是在1967年,最後一次更新則是在1986年,至今為止共定義了128個字元,其中33個字元無法顯示(這是以現今作業系統為依歸,但在DOS模式下可顯示出一些諸如笑臉、撲克牌花式等8-bit符號),且這33個字元多數都已是陳廢的控制字元,控制字元的用途主要是用來操控已經處理過的文字,在33個字元之外的是95個可顯示的字元,包含用鍵盤敲下空白鍵所產生的空白字元也算1個可顯示字元(顯示為空白)。
注意點:
-
在
Python 2
中,如果str
只包含7
位ASCII
字元,那麼unicode
和str
就成了同一種類型。但是在Python 3
中這兩者絕對不等價,空字串也不行。- 可以用
+
連線str
與unicode
- 可用等價於不等價操作符進行比較
- 格式字串中可以用
'%s'
等形式代表unicode
例項 - 可以用
str
與unicode
給函式傳參
- 可以用
-
在
Python 3
中open
函式預設使用系統本地的編碼格式來操作檔案,不能直接往裡面寫二進位制資料UTF-8
編碼格式f.write(os.urandom(10))
,會報錯。在Python 2
中檔案操作的預設編碼格式是二進位制形式。同時適配Python 2
和Python 3
的寫法是:
with open('/tmp/random.bin', 'wb') as f:
f.write(os.urandom(10))
讀二進位制檔案也是一樣,要用 rb
,可以適配 Python 3
和 Python 2
。
【注】
原書這句話有誤,在Python 3
中,open
函式以文字模式操作檔案時,如果不指定編碼,該編碼是依賴於平臺的。
以下內容來自官網:https://docs.python.org/3/library/functions.html#open
encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whateverlocale.getpreferredencoding()
returns), but any text encoding supported by Python can be used. See the codecs module for the list of supported encodings.
os.urandom(size)
隨機生成 size
個位元組的二進位制資料。
檔案控制代碼 file handle
其實是一種識別符號或指標。