1. 程式人生 > >Effective Python 讀書筆記——第 3 條

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 3Python 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 只包含 7ASCII 字元,那麼 unicodestr 就成了同一種類型。但是在 Python 3 中這兩者絕對不等價,空字串也不行。

    • 可以用 + 連線 strunicode
    • 可用等價於不等價操作符進行比較
    • 格式字串中可以用 '%s' 等形式代表 unicode 例項
    • 可以用 strunicode 給函式傳參
  • Python 3open 函式預設使用 UTF-8 編碼格式 系統本地的編碼格式來操作檔案,不能直接往裡面寫二進位制資料 f.write(os.urandom(10)),會報錯。在 Python 2 中檔案操作的預設編碼格式是二進位制形式。同時適配 Python 2Python 3 的寫法是:

with open('/tmp/random.bin', 'wb') as f:
    f.write(os.urandom(10))

讀二進位制檔案也是一樣,要用 rb,可以適配 Python 3Python 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 (whatever locale.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 其實是一種識別符號或指標。