內建型別

以下章節描述了直譯器中内建的標準型別。

主要內建型別為數字、序列、對映、class(類別)、實例和例外。

有些集合類別是 mutable(可變的)。那些用於原地 (in-place) 加入、移除或重新排列其成員且不回傳特定項的 method(方法),也只會回傳 None 而非集合實例自己。

某些操作已被多種物件型別支援;特別是實務上所有物件都已經可以做相等性比較、真值檢測及被轉換為字串(使用 repr() 函式或稍有差異的 str() 函式),後者為當物件傳入 print() 函式印出時在背後被呼叫的函式。

真值檢測

任何物件都可以進行檢測以判斷是否為真值,以便在 ifwhile 條件中使用,或是作為如下所述 boolean(布林)運算之運算元所用。

預設情況下,一個物件會被視為真值,除非它的 class 定義了會回傳 False__bool__() method 或是定義了會回傳零的 __len__() method。[1] 以下列出了大部分會被視為 false 的內建物件:

  • 定義為 false 之常數:NoneFalse

  • 任何數值型別的零:00.00jDecimal(0)Fraction(0, 1)

  • 空的序列和集合:''()[]{}set()range(0)

除非另有特別說明,產生 boolean 結果的操作或內建函式都會回傳 0False 作為假值、1True 作為真值。(重要例外: boolean 運算 orand 回傳的是其中一個運算元。)

Boolean(布林)運算 --- and, or, not

下方為 Boolean 運算,按優先順序排序:

運算

結果

註解

x or y

假如 x 為真,則 x,否則 y

(1)

x and y

假如 x 為假,則 x,否則 y

(2)

not x

假如 x 為假,則 True,否則 False

(3)

註解:

  1. 這是一個短路運算子,所以他只有在第一個引數為假時,才會對第二個引數求值。

  2. 這是一個短路運算子,所以他只有在第一個引數為真時,才會對第二個引數求值。

  3. not 比非 Boolean 運算子有較低的優先權,因此 not a == b 可直譯為 not (a == b),而 a == not b 會導致語法錯誤。

比較運算

在 Python 裡共有 8 種比較運算。他們的優先順序都相同(皆優先於 Boolean 運算)。比較運算可以任意的串連;例如,x < y <= z 等同於 x < y and y <= z,差異只在於前者的 y 只有被求值一次(但在這兩個例子中,當 x < y 為假時,z 皆不會被求值)。

這個表格統整所有比較運算:

運算

含義

<

小於

<=

小於等於

>

大於

>=

大於等於

==

等於

!=

不等於

is

物件識別性

is not

否定的物件識別性

除了不同的數值型別外,不同型別的物件不能進行相等比較。運算子 == 總有定義,但在某些物件型別(例如,class 物件)時,運算子會等同於 is。其他運算子 <<=>>= 皆僅在有意義的部分有所定義;例如,當其中一個引數為複數時,將引發一個 TypeError 的例外。

一個 class 的非相同實例通常會比較為不相等,除非 class 有定義 __eq__() method。

一個 class 的實例不可以與其他相同 class 的實例或其他物件型別進行排序,除非 class 定義足夠的 method ,包含 __lt__()__le__()__gt__()__ge__()(一般來說,使用 __lt__()__eq__() 就可以滿足常規意義上的比較運算子)。

無法自定義 isis not 運算子的行為;這兩個運算子也可以運用在任意兩個物件且不會引發例外。

此外,擁有相同的語法優先序的 innot in 兩種運算皆被可疊代物件或者有實作 __contains__() method 的型別所支援。

數值型別 --- intfloatcomplex

數值型別共有三種:整數浮點數複數。此外,Boolean 為整數中的一個子型別。整數有無限的精度。浮點數通常使用 C 裡面的 double 實作。關於在你程式所運作的機器上之浮點數的精度及內部表示法可以在 sys.float_info 進行查找。複數包含實數及虛數的部分,這兩部分各自是一個浮點數。若要從一個複數 z 提取這兩部分,需使用 z.realz.imag。(標準函式庫包含額外的數值型別,像是 fractions.Fraction 表示有理數,而 decimal.Decimal 表示可由使用者制定精度的浮點數。)

數字是由字面數值或內建公式及運算子的結果所產生的。未經修飾的字面數值(含十六進位、八進位及二進位數值)會 yield 整數。包含小數點或指數符號的字面數值會 yield 浮點數。在數值後面加上 'j' 或是 'J' 會 yield 一個虛數(意即一個實數為 0 的複數)。你也可以將整數與浮點數相加以得到一個有實部與虛部的複數。

Python 完全支援混和運算:當一個二元運算子的運算元有不同數值型別時,「較窄」型別的運算元會被拓寬到另一個型別的運算元;在此處,整數窄於浮點數,浮點數又窄於複數。不同型別的數字間的比較等同於這些數字的精確值進行比較。[2]

建構函式: int()float()complex() 可以用來產生特定型別的數字。

所有數值型別(除複數外)皆支援以下的運算(有關運算的先後順序,詳見 Operator precedence):

運算

結果

註解

完整文件

x + y

xy 的加總

x - y

xy 的相減

x * y

xy 的相乘

x / y

xy 相除之商

x // y

xy 的整數除法

(1)(2)

x % y

x / y 的餘數

(2)

-x

x 的負數

+x

x 不變

abs(x)

x 的絕對值或量 (magnitude)

abs()

int(x)

x 轉為整數

(3)(6)

int()

float(x)

x 轉為浮點數

(4)(6)

float()

complex(re, im)

一個複數,其實部為 re,虛部為 imim 預設為零。

(6)

complex()

c.conjugate()

為複數 c 的共軛複數

divmod(x, y)

一對 (x // y, x % y)

(2)

divmod()

pow(x, y)

xy 次方

(5)

pow()

x ** y

xy 次方

(5)

註解:

  1. 也被稱為整數除法。對於型別為 int 的運算元來說,結果之型別會是 int。對於型別為 float 的運算元來說,結果之型別會是 float。一般來說,結果會是一個整數,但其型別不一定會是 int。結果總是會往負無窮大的方向取整數值: 1//20(-1)//2-11//(-2)-1(-1)//(-2)0

  2. 不可用於複數。在適當情形下,可使用 abs() 轉換為浮點數。

  3. float 轉換為 int 會導致截斷並排除小數部分。詳見 math.floor()math.ceil() 以了解更多轉換方式。

  4. 浮點數也接受帶有可選的前綴 "+" 及 "-" 的 "nan" 及 "inf" 字串,其分別代表非數字(NaN)及正負無窮。

  5. Python 將 pow(0, 0)0 ** 0 定義為 1 這是程式語言的普遍做法。

  6. 字面數值接受包含數字 09 或任何等效的 Unicode 字元(具有 Nd 屬性的 code points(碼位))。

    請參閱 Unicode 標準以了解具有 Nd 屬性的 code points 完整列表。

所有 numbers.Real 型別(intfloat)也適用下列運算:

運算

結果

math.trunc(x)

x 截斷為 Integral

round(x[, n])

x 進位至小數點後第 n 位,使用偶數捨入法。若省略 n ,則預設為 0。

math.floor(x)

小於等於 x 的最大 Integral

math.ceil(x)

大於等於 x 的最小 Integral

關於其他數值運算請詳見 mathcmath modules(模組)。

整數型別的位元運算

位元運算只對整數有意義。位元運算的計算結果就如同對二的補數執行無窮多個符號位元。

二元位元運算的優先順序皆低於數字運算,但高於比較運算;一元運算 ~ 與其他一元數值運算有一致的優先順序(+-)。

這個表格列出所有位元運算並以優先順序由先至後排序。

運算

結果

註解

x | y

xy 的位元

(4)

x ^ y

xy 的位元 邏輯互斥或

(4)

x & y

xy 的位元

(4)

x << n

x 往左移動 n 個位元

(1)(2)

x >> n

x 往右移動 n 個位元

(1)(3)

~x

反轉 x 的位元

註解:

  1. 負數位移是不被允許並會引發 ValueError 的錯誤。

  2. 向左移動 n 個位元等同於乘以 pow(2, n)

  3. 向右移動 n 個位元等同於向下除法除以 pow(2, n)

  4. 在有限的二的補數表示法中執行這些計算(一個有效位元寬度為 1 + max(x.bit_length(), y.bit_length()) 或以上)並至少有一個額外的符號擴展位元,便足以得到與無窮多個符號位元相同的結果。

整數型別的附加 methods

整數型別實作了 numbers.Integral 抽象基底類別。此外,它提供了一些 methods:

int.bit_length()

回傳以二進位表示一個整數所需要的位元數,不包括符號及首位的零:

>>> n = -37
>>> bin(n)
'-0b100101'
>>> n.bit_length()
6

更準確來說,若 x 非為零,則 x.bit_length() 會得出滿足 2**(k-1) <= abs(x) < 2**k 的單一正整數 k。同樣地,當 abs(x) 足夠小到能正確地取得捨入的對數,則 k = 1 + int(log(abs(x), 2))。若 x 為零,則 x.bit_length() 會回傳 0

等同於:

def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6

在 3.1 版被加入.

int.bit_count()

回傳在絕對值表示的二進位中 1 的個數。這也被稱作母體計數。舉例來說:

>>> n = 19
>>> bin(n)
'0b10011'
>>> n.bit_count()
3
>>> (-n).bit_count()
3

等同於:

def bit_count(self):
    return bin(self).count("1")

在 3.10 版被加入.

int.to_bytes(length=1, byteorder='big', *, signed=False)

回傳表示一個整數的一列位元組。

>>> (1024).to_bytes(2, byteorder='big')
b'\x04\x00'
>>> (1024).to_bytes(10, byteorder='big')
b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'
>>> (-1024).to_bytes(10, byteorder='big', signed=True)
b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
>>> x = 1000
>>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little')
b'\xe8\x03'

此整數會使用 length 位元組表示,並且預設為 1。如果該整數無法用給定的位元組數來表示,則會引發 OverflowError

byteorder 引數決定了用來表示整數的位元組順序並且預設為 "big"。如果 byteorder 是 "big",最重要的位元組位於位元組陣列的開頭。如果 byteorder 是 "little",最重要的位元組位於位元組陣列的結尾。

signed 引數決定是否使用二的補數來表示整數。如果 signedFalse 並且給定了一個負整數,則會引發 OverflowErrorsigned 的預設值是 False

預設值可以方便地將一個整數轉換為單一位元組物件:

>>> (65).to_bytes()
b'A'

然而,使用預設引數時,不要嘗試轉換大於 255 的值,否則你將會得到一個 OverflowError

等同於:

def to_bytes(n, length=1, byteorder='big', signed=False):
    if byteorder == 'little':
        order = range(length)
    elif byteorder == 'big':
        order = reversed(range(length))
    else:
        raise ValueError("byteorder must be either 'little' or 'big'")

    return bytes((n >> i*8) & 0xff for i in order)

在 3.2 版被加入.

在 3.11 版的變更: lengthbyteorder 添加了預設引數值。

classmethod int.from_bytes(bytes, byteorder='big', *, signed=False)

回傳由給定的位元組陣列表示的整數。

>>> int.from_bytes(b'\x00\x10', byteorder='big')
16
>>> int.from_bytes(b'\x00\x10', byteorder='little')
4096
>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)
-1024
>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False)
64512
>>> int.from_bytes([255, 0, 0], byteorder='big')
16711680

引數 bytes 必須是一個類位元組物件或是一個產生位元組的可疊代物件。

byteorder 引數決定了用來表示整數的位元組順序並且預設為 "big"。如果 byteorder"big",最重要的位元組位於位元組陣列的開頭。如果 byteorder"little",最重要的位元組位於位元組陣列的結尾。若要請求主機系統的本機位元組順序,請使用 sys.byteorder 作為位元組順序值。

signed 引數指示是否使用二的補數來表示整數。

等同於:

def from_bytes(bytes, byteorder='big', signed=False):
    if byteorder == 'little':
        little_ordered = list(bytes)
    elif byteorder == 'big':
        little_ordered = list(reversed(bytes))
    else:
        raise ValueError("byteorder must be either 'little' or 'big'")

    n = sum(b << i*8 for i, b in enumerate(little_ordered))
    if signed and little_ordered and (little_ordered[-1] & 0x80):
        n -= 1 << 8*len(little_ordered)

    return n

在 3.2 版被加入.

在 3.11 版的變更: byteorder 添加了預設引數值。

int.as_integer_ratio()

回傳一對整數,其比率等於原始整數並且有一個正分母。整數(整個數值)的整數比率總是整數作為分子,並且 1 作為分母。

在 3.8 版被加入.

int.is_integer()

回傳 True。為了與 float.is_integer() 的鴨子型別相容而存在。

在 3.12 版被加入.

浮點數的附加 methods

浮點數型別實作了 numbers.Real 抽象基底類別。浮點數也有下列附加 methods。

classmethod float.from_number(x)

Class method to return a floating-point number constructed from a number x.

If the argument is an integer or a floating-point number, a floating-point number with the same value (within Python's floating-point precision) is returned. If the argument is outside the range of a Python float, an OverflowError will be raised.

For a general Python object x, float.from_number(x) delegates to x.__float__(). If __float__() is not defined then it falls back to __index__().

在 3.14 版被加入.

float.as_integer_ratio()

回傳一對整數,其比率完全等於原始浮點數。比率是在最低條件下並且有一個正分母。在無窮大時引發 OverflowError,在 NaN 時引發 ValueError

float.is_integer()

如果浮點數實例是有限的並且具有整數值,則回傳 True,否則回傳 False

>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False

兩個 methods 皆支援十六進位字串之間的轉換。由於 Python 的浮點數內部以二進位數值儲存,將浮點數轉換為或從 十進位 字串通常涉及一個小的四捨五入誤差。相反地,十六進位字串允許精確表示和指定浮點數。這在除錯和數值工作中可能會有用。

float.hex()

回傳浮點數的十六進位字串表示。對於有限浮點數,此表示方式總是包含一個前導 0x 及一個尾部 p 和指數。

classmethod float.fromhex(s)

Class method 回傳由十六進位字串 s 表示的浮點數。字串 s 可能有前導及尾部的空白。

請注意 float.hex() 是一個實例 method,而 float.fromhex() 是一個 class method。

一個十六進位字串的形式如下:

[sign] ['0x'] integer ['.' fraction] ['p' exponent]

其中可選的 sign 可以是 +-integerfraction 是十六進位數字的字串,而 exponent 是一個十進位整數並且有一個可選的前導符號。大小寫不重要,並且整數或小數部分至少有一個十六進位數字。這個語法與 C99 標準的第 6.4.4.2 節指定的語法相似,也與 Java 1.5 以後的語法相似。特別是 float.hex() 的輸出可用作 C 或 Java 程式碼中的十六進位浮點數文字,並且 C 的 %a 格式字元或 Java 的 Double.toHexString 產生的十六進位字串可被 float.fromhex() 接受。

請注意指數是以十進位而非十六進位寫入,並且它給出了乘以係數的 2 的次方。例如,十六進位字串 0x3.a7p10 表示浮點數 (3 + 10./16 + 7./16**2) * 2.0**10,或 3740.0

>>> float.fromhex('0x3.a7p10')
3740.0

3740.0 應用反向轉換會給出一個不同的十六進位字串,它表示相同的數字:

>>> float.hex(3740.0)
'0x1.d380000000000p+11'

Additional Methods on Complex

The complex type implements the numbers.Complex abstract base class. complex also has the following additional methods.

classmethod complex.from_number(x)

Class method to convert a number to a complex number.

For a general Python object x, complex.from_number(x) delegates to x.__complex__(). If __complex__() is not defined then it falls back to __float__(). If __float__() is not defined then it falls back to __index__().

在 3.14 版被加入.

數值型別的雜湊

對於數字 xy,可能是不同型別,當 x == y 時,hash(x) == hash(y) 是一個要求( 詳見 __hash__() method 的文件以獲得更多細節)。為了實作的便利性和效率跨越各種數值型別(包括 intfloatdecimal.Decimalfractions.Fraction)Python 的數值型別的雜湊是基於一個數學函式,它對於任何有理數都是定義的,因此適用於所有 intfractions.Fraction 的實例,以及所有有限的 floatdecimal.Decimal 的實例。基本上,這個函式是由簡化的 modulo(模數) P 給出的一個固定的質數 PP 的值作為 sys.hash_infomodulus 屬性提供給 Python。

CPython 實作細節: 目前在具有 32 位元 C longs 的機器上所使用的質數是 P = 2**31 - 1,而在具有 64 位元 C longs 的機器上為 P = 2**61 - 1

以下是詳細的規則:

  • 如果 x = m / n 是一個非負的有理數,並且 n 不可被 P 整除,則將 hash(x) 定義為 m * invmod(n, P) % P。其中 invmod(n, P)n 對模數 P 的倒數。

  • 如果 x = m / n 是一個非負的有理數,並且 n 可被 P 整除(但 m 不行),則 n 沒有 inverse modulo(模倒數) P ,並且不適用於上述規則;在這種情況下,將 hash(x) 定義為常數值 sys.hash_info.inf

  • 如果 x = m / n 是一個負的有理數,則將 hash(x) 定義為 -hash(-x)。如果結果的雜湊是 -1,則將其替換為 -2

  • 特定值 sys.hash_info.inf-sys.hash_info.inf (分別)被用作正無窮大或負無窮大的雜湊值。

  • 對於一個 complexz,實部和虛部的雜湊值藉由 hash(z.real) + sys.hash_info.imag * hash(z.imag) 的計算進行組合,對 2**sys.hash_info.width 取模數使其介於 range(-2**(sys.hash_info.width - 1), 2**(sys.hash_info.width - 1))。同樣地,如果結果是 -1,則將其替換為 -2

為了闡明上述規則,這裡有一些 Python 程式碼範例,等同於內建的雜湊,用於計算有理數、floatcomplex 的雜湊:

import sys, math

def hash_fraction(m, n):
    """Compute the hash of a rational number m / n.

    Assumes m and n are integers, with n positive.
    Equivalent to hash(fractions.Fraction(m, n)).

    """
    P = sys.hash_info.modulus
    # Remove common factors of P.  (Unnecessary if m and n already coprime.)
    while m % P == n % P == 0:
        m, n = m // P, n // P

    if n % P == 0:
        hash_value = sys.hash_info.inf
    else:
        # Fermat's Little Theorem: pow(n, P-1, P) is 1, so
        # pow(n, P-2, P) gives the inverse of n modulo P.
        hash_value = (abs(m) % P) * pow(n, P - 2, P) % P
    if m < 0:
        hash_value = -hash_value
    if hash_value == -1:
        hash_value = -2
    return hash_value

def hash_float(x):
    """Compute the hash of a float x."""

    if math.isnan(x):
        return object.__hash__(x)
    elif math.isinf(x):
        return sys.hash_info.inf if x > 0 else -sys.hash_info.inf
    else:
        return hash_fraction(*x.as_integer_ratio())

def hash_complex(z):
    """Compute the hash of a complex number z."""

    hash_value = hash_float(z.real) + sys.hash_info.imag * hash_float(z.imag)
    # do a signed reduction modulo 2**sys.hash_info.width
    M = 2**(sys.hash_info.width - 1)
    hash_value = (hash_value & (M - 1)) - (hash_value & M)
    if hash_value == -1:
        hash_value = -2
    return hash_value

Boolean 型別 - bool

Boolean 值代表 truth values(真值)。bool 型別有兩個常數實例:TrueFalse

內建函式 bool() 將任何值轉換為 boolean 值,如果該值可以被直譯為一個 truth value(真值)(見上面的真值檢測章節)。

對於邏輯運算,使用 boolean 運算子 andornot。當將位元運算子 &|^ 應用於兩個 boolean 值時,它們會回傳一個等同於邏輯運算 "and"、"or"、"xor" 的 boolean 值。然而,應該優先使用邏輯運算子 andor!= 而不是 &|^

在 3.12 版之後被棄用: 位元反轉運算子 ~ 的使用已被棄用並且將在 Python 3.16 中引發錯誤。

boolint 的子類別(見數值型別 --- int、float、complex)。在許多數值情境中,FalseTrue 分別像整數 0 和 1 一樣。然而,不鼓勵依賴這一點;請使用 int() 進行顯式轉換。

疊代器型別

Python 支援對容器的疊代概念。這是實作兩種不同的 methods;這些方法被用於允許使用者自定義的 classes 以支援疊代。序列則總是支援這些疊代 methods,在下方有更詳細的描述。

需要為容器物件定義一個 method 來提供可疊代物件支援:

container.__iter__()

回傳一個疊代器物件。該物件需要支援下述的疊代器協定。如果一個容器支援不同型別的疊代,則可以提供額外的 methods 來專門請求這些疊代型別的疊代器。(支援多種形式疊代的物件的一個例子是支援廣度優先和深度優先遍歷的樹結構。)此 method 對應 Python/C API 中 Python 物件的型別結構的 tp_iter 插槽。

疊代器物件本身需要支援下列兩個 methods,他們一起形成了 疊代器協定

iterator.__iter__()

回傳疊代器物件本身。這是為了允許容器和疊代器都可以與 forin 在陳述式中使用。此 method 對應於 Python/C API 中 Python 物件的型別結構的 tp_iter 插槽。

iterator.__next__()

疊代器回傳下一個項目。如果沒有更多項目,則引發 StopIteration 例外。此 method 對應於 Python/C API 中Python 物件的型別結構的 tp_iternext 插槽。

Python 定義了幾個疊代器物件來支援對一般和特定序列型別、字典和其他更專門的形式的疊代。這些特定型別除了實作疊代器協定外並不重要。

一旦疊代器的 __next__() method 引發 StopIteration,則它必須在後續呼叫中繼續這樣做。不遵守此屬性的實作被認為是有問題的。

Generator Types

Python's generators provide a convenient way to implement the iterator protocol. If a container object's __iter__() method is implemented as a generator, it will automatically return an iterator object (technically, a generator object) supplying the __iter__() and __next__() methods. More information about generators can be found in the documentation for the yield expression.

Sequence Types --- list, tuple, range

There are three basic sequence types: lists, tuples, and range objects. Additional sequence types tailored for processing of binary data and text strings are described in dedicated sections.

Common Sequence Operations

The operations in the following table are supported by most sequence types, both mutable and immutable. The collections.abc.Sequence ABC is provided to make it easier to correctly implement these operations on custom sequence types.

This table lists the sequence operations sorted in ascending priority. In the table, s and t are sequences of the same type, n, i, j and k are integers and x is an arbitrary object that meets any type and value restrictions imposed by s.

The in and not in operations have the same priorities as the comparison operations. The + (concatenation) and * (repetition) operations have the same priority as the corresponding numeric operations. [3]

運算

結果

註解

x in s

True if an item of s is equal to x, else False

(1)

x not in s

False if an item of s is equal to x, else True

(1)

s + t

the concatenation of s and t

(6)(7)

s * nn * s

equivalent to adding s to itself n times

(2)(7)

s[i]

ith item of s, origin 0

(3)

s[i:j]

slice of s from i to j

(3)(4)

s[i:j:k]

slice of s from i to j with step k

(3)(5)

len(s)

s 的長度

min(s)

s 中最小的項目

max(s)

s 中最大的項目

s.index(x[, i[, j]])

index of the first occurrence of x in s (at or after index i and before index j)

(8)

s.count(x)

total number of occurrences of x in s

Sequences of the same type also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length. (For full details see Comparisons in the language reference.)

Forward and reversed iterators over mutable sequences access values using an index. That index will continue to march forward (or backward) even if the underlying sequence is mutated. The iterator terminates only when an IndexError or a StopIteration is encountered (or when the index drops below zero).

註解:

  1. While the in and not in operations are used only for simple containment testing in the general case, some specialised sequences (such as str, bytes and bytearray) also use them for subsequence testing:

    >>> "gg" in "eggs"
    True
    
  2. Values of n less than 0 are treated as 0 (which yields an empty sequence of the same type as s). Note that items in the sequence s are not copied; they are referenced multiple times. This often haunts new Python programmers; consider:

    >>> lists = [[]] * 3
    >>> lists
    [[], [], []]
    >>> lists[0].append(3)
    >>> lists
    [[3], [3], [3]]
    

    What has happened is that [[]] is a one-element list containing an empty list, so all three elements of [[]] * 3 are references to this single empty list. Modifying any of the elements of lists modifies this single list. You can create a list of different lists this way:

    >>> lists = [[] for i in range(3)]
    >>> lists[0].append(3)
    >>> lists[1].append(5)
    >>> lists[2].append(7)
    >>> lists
    [[3], [5], [7]]
    

    Further explanation is available in the FAQ entry How do I create a multidimensional list?.

  3. If i or j is negative, the index is relative to the end of sequence s: len(s) + i or len(s) + j is substituted. But note that -0 is still 0.

  4. The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j. If i or j is greater than len(s), use len(s). If i is omitted or None, use 0. If j is omitted or None, use len(s). If i is greater than or equal to j, the slice is empty.

  5. The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 <= n < (j-i)/k. In other words, the indices are i, i+k, i+2*k, i+3*k and so on, stopping when j is reached (but never including j). When k is positive, i and j are reduced to len(s) if they are greater. When k is negative, i and j are reduced to len(s) - 1 if they are greater. If i or j are omitted or None, they become "end" values (which end depends on the sign of k). Note, k cannot be zero. If k is None, it is treated like 1.

  6. Concatenating immutable sequences always results in a new object. This means that building up a sequence by repeated concatenation will have a quadratic runtime cost in the total sequence length. To get a linear runtime cost, you must switch to one of the alternatives below:

    • if concatenating str objects, you can build a list and use str.join() at the end or else write to an io.StringIO instance and retrieve its value when complete

    • if concatenating bytes objects, you can similarly use bytes.join() or io.BytesIO, or you can do in-place concatenation with a bytearray object. bytearray objects are mutable and have an efficient overallocation mechanism

    • if concatenating tuple objects, extend a list instead

    • for other types, investigate the relevant class documentation

  7. Some sequence types (such as range) only support item sequences that follow specific patterns, and hence don't support sequence concatenation or repetition.

  8. index raises ValueError when x is not found in s. Not all implementations support passing the additional arguments i and j. These arguments allow efficient searching of subsections of the sequence. Passing the extra arguments is roughly equivalent to using s[i:j].index(x), only without copying any data and with the returned index being relative to the start of the sequence rather than the start of the slice.

Immutable Sequence Types

The only operation that immutable sequence types generally implement that is not also implemented by mutable sequence types is support for the hash() built-in.

This support allows immutable sequences, such as tuple instances, to be used as dict keys and stored in set and frozenset instances.

Attempting to hash an immutable sequence that contains unhashable values will result in TypeError.

Mutable Sequence Types

The operations in the following table are defined on mutable sequence types. The collections.abc.MutableSequence ABC is provided to make it easier to correctly implement these operations on custom sequence types.

In the table s is an instance of a mutable sequence type, t is any iterable object and x is an arbitrary object that meets any type and value restrictions imposed by s (for example, bytearray only accepts integers that meet the value restriction 0 <= x <= 255).

運算

結果

註解

s[i] = x

item i of s is replaced by x

s[i:j] = t

slice of s from i to j is replaced by the contents of the iterable t

del s[i:j]

same as s[i:j] = []

s[i:j:k] = t

the elements of s[i:j:k] are replaced by those of t

(1)

del s[i:j:k]

removes the elements of s[i:j:k] from the list

s.append(x)

appends x to the end of the sequence (same as s[len(s):len(s)] = [x])

s.clear()

removes all items from s (same as del s[:])

(5)

s.copy()

creates a shallow copy of s (same as s[:])

(5)

s.extend(t)s += t

extends s with the contents of t (for the most part the same as s[len(s):len(s)] = t)

s *= n

updates s with its contents repeated n times

(6)

s.insert(i, x)

inserts x into s at the index given by i (same as s[i:i] = [x])

s.pop()s.pop(i)

retrieves the item at i and also removes it from s

(2)

s.remove(x)

removes the first item from s where s[i] is equal to x

(3)

s.reverse()

reverses the items of s in place

(4)

註解:

  1. If k is not equal to 1, t must have the same length as the slice it is replacing.

  2. The optional argument i defaults to -1, so that by default the last item is removed and returned.

  3. remove() raises ValueError when x is not found in s.

  4. The reverse() method modifies the sequence in place for economy of space when reversing a large sequence. To remind users that it operates by side effect, it does not return the reversed sequence.

  5. clear() and copy() are included for consistency with the interfaces of mutable containers that don't support slicing operations (such as dict and set). copy() is not part of the collections.abc.MutableSequence ABC, but most concrete mutable sequence classes provide it.

    在 3.3 版被加入: clear() and copy() methods.

  6. The value n is an integer, or an object implementing __index__(). Zero and negative values of n clear the sequence. Items in the sequence are not copied; they are referenced multiple times, as explained for s * n under Common Sequence Operations.

List(串列)

Lists are mutable sequences, typically used to store collections of homogeneous items (where the precise degree of similarity will vary by application).

class list([iterable])

Lists may be constructed in several ways:

  • Using a pair of square brackets to denote the empty list: []

  • Using square brackets, separating items with commas: [a], [a, b, c]

  • Using a list comprehension: [x for x in iterable]

  • Using the type constructor: list() or list(iterable)

The constructor builds a list whose items are the same and in the same order as iterable's items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a list, a copy is made and returned, similar to iterable[:]. For example, list('abc') returns ['a', 'b', 'c'] and list( (1, 2, 3) ) returns [1, 2, 3]. If no argument is given, the constructor creates a new empty list, [].

Many other operations also produce lists, including the sorted() built-in.

Lists implement all of the common and mutable sequence operations. Lists also provide the following additional method:

sort(*, key=None, reverse=False)

This method sorts the list in place, using only < comparisons between items. Exceptions are not suppressed - if any comparison operations fail, the entire sort operation will fail (and the list will likely be left in a partially modified state).

sort() accepts two arguments that can only be passed by keyword (keyword-only arguments):

key specifies a function of one argument that is used to extract a comparison key from each list element (for example, key=str.lower). The key corresponding to each item in the list is calculated once and then used for the entire sorting process. The default value of None means that list items are sorted directly without calculating a separate key value.

The functools.cmp_to_key() utility is available to convert a 2.x style cmp function to a key function.

reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

This method modifies the sequence in place for economy of space when sorting a large sequence. To remind users that it operates by side effect, it does not return the sorted sequence (use sorted() to explicitly request a new sorted list instance).

The sort() method is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal --- this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).

For sorting examples and a brief sorting tutorial, see 排序技法.

CPython 實作細節: While a list is being sorted, the effect of attempting to mutate, or even inspect, the list is undefined. The C implementation of Python makes the list appear empty for the duration, and raises ValueError if it can detect that the list has been mutated during a sort.

Tuples

Tuples are immutable sequences, typically used to store collections of heterogeneous data (such as the 2-tuples produced by the enumerate() built-in). Tuples are also used for cases where an immutable sequence of homogeneous data is needed (such as allowing storage in a set or dict instance).

class tuple([iterable])

Tuples may be constructed in a number of ways:

  • Using a pair of parentheses to denote the empty tuple: ()

  • Using a trailing comma for a singleton tuple: a, or (a,)

  • Separating items with commas: a, b, c or (a, b, c)

  • Using the tuple() built-in: tuple() or tuple(iterable)

The constructor builds a tuple whose items are the same and in the same order as iterable's items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a tuple, it is returned unchanged. For example, tuple('abc') returns ('a', 'b', 'c') and tuple( [1, 2, 3] ) returns (1, 2, 3). If no argument is given, the constructor creates a new empty tuple, ().

Note that it is actually the comma which makes a tuple, not the parentheses. The parentheses are optional, except in the empty tuple case, or when they are needed to avoid syntactic ambiguity. For example, f(a, b, c) is a function call with three arguments, while f((a, b, c)) is a function call with a 3-tuple as the sole argument.

Tuples implement all of the common sequence operations.

For heterogeneous collections of data where access by name is clearer than access by index, collections.namedtuple() may be a more appropriate choice than a simple tuple object.

Ranges

The range type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops.

class range(stop)
class range(start, stop[, step])

The arguments to the range constructor must be integers (either built-in int or any object that implements the __index__() special method). If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. If step is zero, ValueError is raised.

For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.

For a negative step, the contents of the range are still determined by the formula r[i] = start + step*i, but the constraints are i >= 0 and r[i] > stop.

A range object will be empty if r[0] does not meet the value constraint. Ranges do support negative indices, but these are interpreted as indexing from the end of the sequence determined by the positive indices.

Ranges containing absolute values larger than sys.maxsize are permitted but some features (such as len()) may raise OverflowError.

Range examples:

>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
>>> list(range(0, 10, 3))
[0, 3, 6, 9]
>>> list(range(0, -10, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> list(range(0))
[]
>>> list(range(1, 0))
[]

Ranges implement all of the common sequence operations except concatenation and repetition (due to the fact that range objects can only represent sequences that follow a strict pattern and repetition and concatenation will usually violate that pattern).

start

The value of the start parameter (or 0 if the parameter was not supplied)

stop

The value of the stop parameter

step

The value of the step parameter (or 1 if the parameter was not supplied)

The advantage of the range type over a regular list or tuple is that a range object will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores the start, stop and step values, calculating individual items and subranges as needed).

Range objects implement the collections.abc.Sequence ABC, and provide features such as containment tests, element index lookup, slicing and support for negative indices (see Sequence Types --- list, tuple, range):

>>> r = range(0, 20, 2)
>>> r
range(0, 20, 2)
>>> 11 in r
False
>>> 10 in r
True
>>> r.index(10)
5
>>> r[5]
10
>>> r[:5]
range(0, 10, 2)
>>> r[-1]
18

Testing range objects for equality with == and != compares them as sequences. That is, two range objects are considered equal if they represent the same sequence of values. (Note that two range objects that compare equal might have different start, stop and step attributes, for example range(0) == range(2, 1, 3) or range(0, 3, 2) == range(0, 4, 2).)

在 3.2 版的變更: Implement the Sequence ABC. Support slicing and negative indices. Test int objects for membership in constant time instead of iterating through all items.

在 3.3 版的變更: Define '==' and '!=' to compare range objects based on the sequence of values they define (instead of comparing based on object identity).

Added the start, stop and step attributes.

也參考

  • The linspace recipe shows how to implement a lazy version of range suitable for floating-point applications.

Text Sequence Type --- str

Textual data in Python is handled with str objects, or strings. Strings are immutable sequences of Unicode code points. String literals are written in a variety of ways:

  • Single quotes: 'allows embedded "double" quotes'

  • Double quotes: "allows embedded 'single' quotes"

  • Triple quoted: '''Three single quotes''', """Three double quotes"""

Triple quoted strings may span multiple lines - all associated whitespace will be included in the string literal.

String literals that are part of a single expression and have only whitespace between them will be implicitly converted to a single string literal. That is, ("spam " "eggs") == "spam eggs".

See String and Bytes literals for more about the various forms of string literal, including supported escape sequences, and the r ("raw") prefix that disables most escape sequence processing.

Strings may also be created from other objects using the str constructor.

Since there is no separate "character" type, indexing a string produces strings of length 1. That is, for a non-empty string s, s[0] == s[0:1].

There is also no mutable string type, but str.join() or io.StringIO can be used to efficiently construct strings from multiple fragments.

在 3.3 版的變更: For backwards compatibility with the Python 2 series, the u prefix is once again permitted on string literals. It has no effect on the meaning of string literals and cannot be combined with the r prefix.

class str(object='')
class str(object=b'', encoding='utf-8', errors='strict')

Return a string version of object. If object is not provided, returns the empty string. Otherwise, the behavior of str() depends on whether encoding or errors is given, as follows.

If neither encoding nor errors is given, str(object) returns type(object).__str__(object), which is the "informal" or nicely printable string representation of object. For string objects, this is the string itself. If object does not have a __str__() method, then str() falls back to returning repr(object).

If at least one of encoding or errors is given, object should be a bytes-like object (e.g. bytes or bytearray). In this case, if object is a bytes (or bytearray) object, then str(bytes, encoding, errors) is equivalent to bytes.decode(encoding, errors). Otherwise, the bytes object underlying the buffer object is obtained before calling bytes.decode(). See Binary Sequence Types --- bytes, bytearray, memoryview and 緩衝協定 (Buffer Protocol) for information on buffer objects.

Passing a bytes object to str() without the encoding or errors arguments falls under the first case of returning the informal string representation (see also the -b command-line option to Python). For example:

>>> str(b'Zoot!')
"b'Zoot!'"

For more information on the str class and its methods, see Text Sequence Type --- str and the String Methods section below. To output formatted strings, see the f-string(f 字串) and 格式化文字語法 sections. In addition, see the 文本處理 (Text Processing) 服務 section.

String Methods

Strings implement all of the common sequence operations, along with the additional methods described below.

Strings also support two styles of string formatting, one providing a large degree of flexibility and customization (see str.format(), 格式化文字語法 and 自訂字串格式) and the other based on C printf style formatting that handles a narrower range of types and is slightly harder to use correctly, but is often faster for the cases it can handle (printf-style String Formatting).

The 文本處理 (Text Processing) 服務 section of the standard library covers a number of other modules that provide various text related utilities (including regular expression support in the re module).

str.capitalize()

Return a copy of the string with its first character capitalized and the rest lowercased.

在 3.8 版的變更: The first character is now put into titlecase rather than uppercase. This means that characters like digraphs will only have their first letter capitalized, instead of the full character.

str.casefold()

Return a casefolded copy of the string. Casefolded strings may be used for caseless matching.

Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter 'ß' is equivalent to "ss". Since it is already lowercase, lower() would do nothing to 'ß'; casefold() converts it to "ss".

The casefolding algorithm is described in section 3.13 'Default Case Folding' of the Unicode Standard.

在 3.3 版被加入.

str.center(width[, fillchar])

Return centered in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).

str.count(sub[, start[, end]])

Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

If sub is empty, returns the number of empty strings between characters which is the length of the string plus one.

str.encode(encoding='utf-8', errors='strict')

Return the string encoded to bytes.

encoding defaults to 'utf-8'; see Standard Encodings for possible values.

errors controls how encoding errors are handled. If 'strict' (the default), a UnicodeError exception is raised. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error(). See Error Handlers for details.

For performance reasons, the value of errors is not checked for validity unless an encoding error actually occurs, Python 開發模式 is enabled or a debug build is used.

在 3.1 版的變更: 新增關鍵字引數的支援。

在 3.9 版的變更: The value of the errors argument is now checked in Python 開發模式 and in debug mode.

str.endswith(suffix[, start[, end]])

Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position.

str.expandtabs(tabsize=8)

Return a copy of the string where all tab characters are replaced by one or more spaces, depending on the current column and the given tab size. Tab positions occur every tabsize characters (default is 8, giving tab positions at columns 0, 8, 16 and so on). To expand the string, the current column is set to zero and the string is examined character by character. If the character is a tab (\t), one or more space characters are inserted in the result until the current column is equal to the next tab position. (The tab character itself is not copied.) If the character is a newline (\n) or return (\r), it is copied and the current column is reset to zero. Any other character is copied unchanged and the current column is incremented by one regardless of how the character is represented when printed.

>>> '01\t012\t0123\t01234'.expandtabs()
'01      012     0123    01234'
>>> '01\t012\t0123\t01234'.expandtabs(4)
'01  012 0123    01234'
str.find(sub[, start[, end]])

Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

備註

The find() method should be used only if you need to know the position of sub. To check if sub is a substring or not, use the in operator:

>>> 'Py' in 'Python'
True
str.format(*args, **kwargs)

Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.

>>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'

See 格式化文字語法 for a description of the various formatting options that can be specified in format strings.

備註

When formatting a number (int, float, complex, decimal.Decimal and subclasses) with the n type (ex: '{:n}'.format(1234)), the function temporarily sets the LC_CTYPE locale to the LC_NUMERIC locale to decode decimal_point and thousands_sep fields of localeconv() if they are non-ASCII or longer than 1 byte, and the LC_NUMERIC locale is different than the LC_CTYPE locale. This temporary change affects other threads.

在 3.7 版的變更: When formatting a number with the n type, the function sets temporarily the LC_CTYPE locale to the LC_NUMERIC locale in some cases.

str.format_map(mapping, /)

Similar to str.format(**mapping), except that mapping is used directly and not copied to a dict. This is useful if for example mapping is a dict subclass:

>>> class Default(dict):
...     def __missing__(self, key):
...         return key
...
>>> '{name} was born in {country}'.format_map(Default(name='Guido'))
'Guido was born in country'

在 3.2 版被加入.

str.index(sub[, start[, end]])

Like find(), but raise ValueError when the substring is not found.

str.isalnum()

Return True if all characters in the string are alphanumeric and there is at least one character, False otherwise. A character c is alphanumeric if one of the following returns True: c.isalpha(), c.isdecimal(), c.isdigit(), or c.isnumeric().

str.isalpha()

Return True if all characters in the string are alphabetic and there is at least one character, False otherwise. Alphabetic characters are those characters defined in the Unicode character database as "Letter", i.e., those with general category property being one of "Lm", "Lt", "Lu", "Ll", or "Lo". Note that this is different from the Alphabetic property defined in the section 4.10 'Letters, Alphabetic, and Ideographic' of the Unicode Standard.

str.isascii()

Return True if the string is empty or all characters in the string are ASCII, False otherwise. ASCII characters have code points in the range U+0000-U+007F.

在 3.7 版被加入.

str.isdecimal()

Return True if all characters in the string are decimal characters and there is at least one character, False otherwise. Decimal characters are those that can be used to form numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Formally a decimal character is a character in the Unicode General Category "Nd".

str.isdigit()

Return True if all characters in the string are digits and there is at least one character, False otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.

str.isidentifier()

Return True if the string is a valid identifier according to the language definition, section Identifiers and keywords.

keyword.iskeyword() can be used to test whether string s is a reserved identifier, such as def and class.

範例:

>>> from keyword import iskeyword

>>> 'hello'.isidentifier(), iskeyword('hello')
(True, False)
>>> 'def'.isidentifier(), iskeyword('def')
(True, True)
str.islower()

Return True if all cased characters [4] in the string are lowercase and there is at least one cased character, False otherwise.

str.isnumeric()

Return True if all characters in the string are numeric characters, and there is at least one character, False otherwise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.

str.isprintable()

Return True if all characters in the string are printable or the string is empty, False otherwise. Nonprintable characters are those characters defined in the Unicode character database as "Other" or "Separator", excepting the ASCII space (0x20) which is considered printable. (Note that printable characters in this context are those which should not be escaped when repr() is invoked on a string. It has no bearing on the handling of strings written to sys.stdout or sys.stderr.)

str.isspace()

Return True if there are only whitespace characters in the string and there is at least one character, False otherwise.

A character is whitespace if in the Unicode character database (see unicodedata), either its general category is Zs ("Separator, space"), or its bidirectional class is one of WS, B, or S.

str.istitle()

Return True if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise.

str.isupper()

Return True if all cased characters [4] in the string are uppercase and there is at least one cased character, False otherwise.

>>> 'BANANA'.isupper()
True
>>> 'banana'.isupper()
False
>>> 'baNana'.isupper()
False
>>> ' '.isupper()
False
str.join(iterable)

Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.

str.ljust(width[, fillchar])

Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).

str.lower()

Return a copy of the string with all the cased characters [4] converted to lowercase.

The lowercasing algorithm used is described in section 3.13 'Default Case Folding' of the Unicode Standard.

str.lstrip([chars])

Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped:

>>> '   spacious   '.lstrip()
'spacious   '
>>> 'www.example.com'.lstrip('cmowz.')
'example.com'

See str.removeprefix() for a method that will remove a single prefix string rather than all of a set of characters. For example:

>>> 'Arthur: three!'.lstrip('Arthur: ')
'ee!'
>>> 'Arthur: three!'.removeprefix('Arthur: ')
'three!'
static str.maketrans(x[, y[, z]])

This static method returns a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or None. Character keys will then be converted to ordinals.

If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

str.partition(sep)

Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.

str.removeprefix(prefix, /)

If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string:

>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'BaseTestCase'.removeprefix('Test')
'BaseTestCase'

在 3.9 版被加入.

str.removesuffix(suffix, /)

If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string:

>>> 'MiscTests'.removesuffix('Tests')
'Misc'
>>> 'TmpDirMixin'.removesuffix('Tests')
'TmpDirMixin'

在 3.9 版被加入.

str.replace(old, new, count=-1)

Return a copy of the string with all occurrences of substring old replaced by new. If count is given, only the first count occurrences are replaced. If count is not specified or -1, then all occurrences are replaced.

在 3.13 版的變更: count 現在作為關鍵字引數被支援。

str.rfind(sub[, start[, end]])

Return the highest index in the string where substring sub is found, such that sub is contained within s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.

str.rindex(sub[, start[, end]])

Like rfind() but raises ValueError when the substring sub is not found.

str.rjust(width[, fillchar])

Return the string right justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).

str.rpartition(sep)

Split the string at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself.

str.rsplit(sep=None, maxsplit=-1)

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or None, any whitespace string is a separator. Except for splitting from the right, rsplit() behaves like split() which is described in detail below.

str.rstrip([chars])

Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped:

>>> '   spacious   '.rstrip()
'   spacious'
>>> 'mississippi'.rstrip('ipz')
'mississ'

See str.removesuffix() for a method that will remove a single suffix string rather than all of a set of characters. For example:

>>> 'Monty Python'.rstrip(' Python')
'M'
>>> 'Monty Python'.removesuffix(' Python')
'Monty'
str.split(sep=None, maxsplit=-1)

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).

If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). The sep argument may consist of multiple characters as a single delimiter (to split with multiple delimiters, use re.split()). Splitting an empty string with a specified separator returns [''].

舉例來說:

>>> '1,2,3'.split(',')
['1', '2', '3']
>>> '1,2,3'.split(',', maxsplit=1)
['1', '2,3']
>>> '1,2,,3,'.split(',')
['1', '2', '', '3', '']
>>> '1<>2<>3<4'.split('<>')
['1', '2', '3<4']

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

舉例來說:

>>> '1 2 3'.split()
['1', '2', '3']
>>> '1 2 3'.split(maxsplit=1)
['1', '2 3']
>>> '   1   2   3   '.split()
['1', '2', '3']
str.splitlines(keepends=False)

Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.

This method splits on the following line boundaries. In particular, the boundaries are a superset of universal newlines.

Representation

描述

\n

Line Feed

\r

Carriage Return

\r\n

Carriage Return + Line Feed

\v\x0b

Line Tabulation

\f\x0c

Form Feed

\x1c

File Separator

\x1d

Group Separator

\x1e

Record Separator

\x85

Next Line (C1 Control Code)

\u2028

Line Separator

\u2029

Paragraph Separator

在 3.2 版的變更: \v and \f added to list of line boundaries.

舉例來說:

>>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
['ab c', '', 'de fg', 'kl']
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
['ab c\n', '\n', 'de fg\r', 'kl\r\n']

Unlike split() when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:

>>> "".splitlines()
[]
>>> "One line\n".splitlines()
['One line']

For comparison, split('\n') gives:

>>> ''.split('\n')
['']
>>> 'Two lines\n'.split('\n')
['Two lines', '']
str.startswith(prefix[, start[, end]])

Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.

str.strip([chars])

Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:

>>> '   spacious   '.strip()
'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'

The outermost leading and trailing chars argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in chars. A similar action takes place on the trailing end. For example:

>>> comment_string = '#....... Section 3.2.1 Issue #32 .......'
>>> comment_string.strip('.#! ')
'Section 3.2.1 Issue #32'
str.swapcase()

Return a copy of the string with uppercase characters converted to lowercase and vice versa. Note that it is not necessarily true that s.swapcase().swapcase() == s.

str.title()

Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase.

舉例來說:

>>> 'Hello world'.title()
'Hello World'

The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result:

>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"

The string.capwords() function does not have this problem, as it splits words on spaces only.

Alternatively, a workaround for apostrophes can be constructed using regular expressions:

>>> import re
>>> def titlecase(s):
...     return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
...                   lambda mo: mo.group(0).capitalize(),
...                   s)
...
>>> titlecase("they're bill's friends.")
"They're Bill's Friends."
str.translate(table)

Return a copy of the string in which each character has been mapped through the given translation table. The table must be an object that implements indexing via __getitem__(), typically a mapping or sequence. When indexed by a Unicode ordinal (an integer), the table object can do any of the following: return a Unicode ordinal or a string, to map the character to one or more other characters; return None, to delete the character from the return string; or raise a LookupError exception, to map the character to itself.

You can use str.maketrans() to create a translation map from character-to-character mappings in different formats.

See also the codecs module for a more flexible approach to custom character mappings.

str.upper()

Return a copy of the string with all the cased characters [4] converted to uppercase. Note that s.upper().isupper() might be False if s contains uncased characters or if the Unicode category of the resulting character(s) is not "Lu" (Letter, uppercase), but e.g. "Lt" (Letter, titlecase).

The uppercasing algorithm used is described in section 3.13 'Default Case Folding' of the Unicode Standard.

str.zfill(width)

Return a copy of the string left filled with ASCII '0' digits to make a string of length width. A leading sign prefix ('+'/'-') is handled by inserting the padding after the sign character rather than before. The original string is returned if width is less than or equal to len(s).

舉例來說:

>>> "42".zfill(5)
'00042'
>>> "-42".zfill(5)
'-0042'

printf-style String Formatting

備註

The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals, the str.format() interface, or template strings may help avoid these errors. Each of these alternatives provides their own trade-offs and benefits of simplicity, flexibility, and/or extensibility.

String objects have one unique built-in operation: the % operator (modulo). This is also known as the string formatting or interpolation operator. Given format % values (where format is a string), % conversion specifications in format are replaced with zero or more elements of values. The effect is similar to using the sprintf() function in the C language. For example:

>>> print('%s has %d quote types.' % ('Python', 2))
Python has 2 quote types.

If format requires a single argument, values may be a single non-tuple object. [5] Otherwise, values must be a tuple with exactly the number of items specified by the format string, or a single mapping object (for example, a dictionary).

A conversion specifier contains two or more characters and has the following components, which must occur in this order:

  1. The '%' character, which marks the start of the specifier.

  2. Mapping key (optional), consisting of a parenthesised sequence of characters (for example, (somename)).

  3. Conversion flags (optional), which affect the result of some conversion types.

  4. Minimum field width (optional). If specified as an '*' (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision.

  5. Precision (optional), given as a '.' (dot) followed by the precision. If specified as '*' (an asterisk), the actual precision is read from the next element of the tuple in values, and the value to convert comes after the precision.

  6. Length modifier (optional).

  7. Conversion type.

When the right argument is a dictionary (or other mapping type), then the formats in the string must include a parenthesised mapping key into that dictionary inserted immediately after the '%' character. The mapping key selects the value to be formatted from the mapping. For example:

>>> print('%(language)s has %(number)03d quote types.' %
...       {'language': "Python", "number": 2})
Python has 002 quote types.

In this case no * specifiers may occur in a format (since they require a sequential parameter list).

The conversion flag characters are:

Flag

含義

'#'

The value conversion will use the "alternate form" (where defined below).

'0'

The conversion will be zero padded for numeric values.

'-'

The converted value is left adjusted (overrides the '0' conversion if both are given).

' '

(a space) A blank should be left before a positive number (or empty string) produced by a signed conversion.

'+'

A sign character ('+' or '-') will precede the conversion (overrides a "space" flag).

A length modifier (h, l, or L) may be present, but is ignored as it is not necessary for Python -- so e.g. %ld is identical to %d.

The conversion types are:

Conversion

含義

註解

'd'

Signed integer decimal.

'i'

Signed integer decimal.

'o'

Signed octal value.

(1)

'u'

Obsolete type -- it is identical to 'd'.

(6)

'x'

Signed hexadecimal (lowercase).

(2)

'X'

Signed hexadecimal (uppercase).

(2)

'e'

Floating-point exponential format (lowercase).

(3)

'E'

Floating-point exponential format (uppercase).

(3)

'f'

Floating-point decimal format.

(3)

'F'

Floating-point decimal format.

(3)

'g'

Floating-point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.

(4)

'G'

Floating-point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.

(4)

'c'

Single character (accepts integer or single character string).

'r'

String (converts any Python object using repr()).

(5)

's'

String (converts any Python object using str()).

(5)

'a'

String (converts any Python object using ascii()).

(5)

'%'

No argument is converted, results in a '%' character in the result.

註解:

  1. The alternate form causes a leading octal specifier ('0o') to be inserted before the first digit.

  2. The alternate form causes a leading '0x' or '0X' (depending on whether the 'x' or 'X' format was used) to be inserted before the first digit.

  3. The alternate form causes the result to always contain a decimal point, even if no digits follow it.

    The precision determines the number of digits after the decimal point and defaults to 6.

  4. The alternate form causes the result to always contain a decimal point, and trailing zeroes are not removed as they would otherwise be.

    The precision determines the number of significant digits before and after the decimal point and defaults to 6.

  5. If precision is N, the output is truncated to N characters.

  6. 參閱 PEP 237

Since Python strings have an explicit length, %s conversions do not assume that '\0' is the end of the string.

在 3.1 版的變更: %f conversions for numbers whose absolute value is over 1e50 are no longer replaced by %g conversions.

Binary Sequence Types --- bytes, bytearray, memoryview

The core built-in types for manipulating binary data are bytes and bytearray. They are supported by memoryview which uses the buffer protocol to access the memory of other binary objects without needing to make a copy.

The array module supports efficient storage of basic data types like 32-bit integers and IEEE754 double-precision floating values.

Bytes Objects

Bytes objects are immutable sequences of single bytes. Since many major binary protocols are based on the ASCII text encoding, bytes objects offer several methods that are only valid when working with ASCII compatible data and are closely related to string objects in a variety of other ways.

class bytes([source[, encoding[, errors]]])

Firstly, the syntax for bytes literals is largely the same as that for string literals, except that a b prefix is added:

  • Single quotes: b'still allows embedded "double" quotes'

  • Double quotes: b"still allows embedded 'single' quotes"

  • Triple quoted: b'''3 single quotes''', b"""3 double quotes"""

Only ASCII characters are permitted in bytes literals (regardless of the declared source code encoding). Any binary values over 127 must be entered into bytes literals using the appropriate escape sequence.

As with string literals, bytes literals may also use a r prefix to disable processing of escape sequences. See String and Bytes literals for more about the various forms of bytes literal, including supported escape sequences.

While bytes literals and representations are based on ASCII text, bytes objects actually behave like immutable sequences of integers, with each value in the sequence restricted such that 0 <= x < 256 (attempts to violate this restriction will trigger ValueError). This is done deliberately to emphasise that while many binary formats include ASCII based elements and can be usefully manipulated with some text-oriented algorithms, this is not generally the case for arbitrary binary data (blindly applying text processing algorithms to binary data formats that are not ASCII compatible will usually lead to data corruption).

In addition to the literal forms, bytes objects can be created in a number of other ways:

  • A zero-filled bytes object of a specified length: bytes(10)

  • From an iterable of integers: bytes(range(20))

  • Copying existing binary data via the buffer protocol: bytes(obj)

Also see the bytes built-in.

Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal numbers are a commonly used format for describing binary data. Accordingly, the bytes type has an additional class method to read data in that format:

classmethod fromhex(string)

This bytes class method returns a bytes object, decoding the given string object. The string must contain two hexadecimal digits per byte, with ASCII whitespace being ignored.

>>> bytes.fromhex('2Ef0 F1f2  ')
b'.\xf0\xf1\xf2'

在 3.7 版的變更: bytes.fromhex() now skips all ASCII whitespace in the string, not just spaces.

A reverse conversion function exists to transform a bytes object into its hexadecimal representation.

hex([sep[, bytes_per_sep]])

Return a string object containing two hexadecimal digits for each byte in the instance.

>>> b'\xf0\xf1\xf2'.hex()
'f0f1f2'

If you want to make the hex string easier to read, you can specify a single character separator sep parameter to include in the output. By default, this separator will be included between each byte. A second optional bytes_per_sep parameter controls the spacing. Positive values calculate the separator position from the right, negative values from the left.

>>> value = b'\xf0\xf1\xf2'
>>> value.hex('-')
'f0-f1-f2'
>>> value.hex('_', 2)
'f0_f1f2'
>>> b'UUDDLRLRAB'.hex(' ', -4)
'55554444 4c524c52 4142'

在 3.5 版被加入.

在 3.8 版的變更: bytes.hex() now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output.

Since bytes objects are sequences of integers (akin to a tuple), for a bytes object b, b[0] will be an integer, while b[0:1] will be a bytes object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1)

The representation of bytes objects uses the literal format (b'...') since it is often more useful than e.g. bytes([46, 46, 46]). You can always convert a bytes object into a list of integers using list(b).

Bytearray Objects

bytearray objects are a mutable counterpart to bytes objects.

class bytearray([source[, encoding[, errors]]])

There is no dedicated literal syntax for bytearray objects, instead they are always created by calling the constructor:

  • Creating an empty instance: bytearray()

  • Creating a zero-filled instance with a given length: bytearray(10)

  • From an iterable of integers: bytearray(range(20))

  • Copying existing binary data via the buffer protocol: bytearray(b'Hi!')

As bytearray objects are mutable, they support the mutable sequence operations in addition to the common bytes and bytearray operations described in Bytes and Bytearray Operations.

Also see the bytearray built-in.

Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal numbers are a commonly used format for describing binary data. Accordingly, the bytearray type has an additional class method to read data in that format:

classmethod fromhex(string)

This bytearray class method returns bytearray object, decoding the given string object. The string must contain two hexadecimal digits per byte, with ASCII whitespace being ignored.

>>> bytearray.fromhex('2Ef0 F1f2  ')
bytearray(b'.\xf0\xf1\xf2')

在 3.7 版的變更: bytearray.fromhex() now skips all ASCII whitespace in the string, not just spaces.

A reverse conversion function exists to transform a bytearray object into its hexadecimal representation.

hex([sep[, bytes_per_sep]])

Return a string object containing two hexadecimal digits for each byte in the instance.

>>> bytearray(b'\xf0\xf1\xf2').hex()
'f0f1f2'

在 3.5 版被加入.

在 3.8 版的變更: Similar to bytes.hex(), bytearray.hex() now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output.

Since bytearray objects are sequences of integers (akin to a list), for a bytearray object b, b[0] will be an integer, while b[0:1] will be a bytearray object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1)

The representation of bytearray objects uses the bytes literal format (bytearray(b'...')) since it is often more useful than e.g. bytearray([46, 46, 46]). You can always convert a bytearray object into a list of integers using list(b).

Bytes and Bytearray Operations

Both bytes and bytearray objects support the common sequence operations. They interoperate not just with operands of the same type, but with any bytes-like object. Due to this flexibility, they can be freely mixed in operations without causing errors. However, the return type of the result may depend on the order of operands.

備註

The methods on bytes and bytearray objects don't accept strings as their arguments, just as the methods on strings don't accept bytes as their arguments. For example, you have to write:

a = "abc"
b = a.replace("a", "f")

和:

a = b"abc"
b = a.replace(b"a", b"f")

Some bytes and bytearray operations assume the use of ASCII compatible binary formats, and hence should be avoided when working with arbitrary binary data. These restrictions are covered below.

備註

Using these ASCII based operations to manipulate binary data that is not stored in an ASCII based format may lead to data corruption.

The following methods on bytes and bytearray objects can be used with arbitrary binary data.

bytes.count(sub[, start[, end]])
bytearray.count(sub[, start[, end]])

Return the number of non-overlapping occurrences of subsequence sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.

If sub is empty, returns the number of empty slices between characters which is the length of the bytes object plus one.

在 3.3 版的變更: Also accept an integer in the range 0 to 255 as the subsequence.

bytes.removeprefix(prefix, /)
bytearray.removeprefix(prefix, /)

If the binary data starts with the prefix string, return bytes[len(prefix):]. Otherwise, return a copy of the original binary data:

>>> b'TestHook'.removeprefix(b'Test')
b'Hook'
>>> b'BaseTestCase'.removeprefix(b'Test')
b'BaseTestCase'

The prefix may be any bytes-like object.

備註

The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.

在 3.9 版被加入.

bytes.removesuffix(suffix, /)
bytearray.removesuffix(suffix, /)

If the binary data ends with the suffix string and that suffix is not empty, return bytes[:-len(suffix)]. Otherwise, return a copy of the original binary data:

>>> b'MiscTests'.removesuffix(b'Tests')
b'Misc'
>>> b'TmpDirMixin'.removesuffix(b'Tests')
b'TmpDirMixin'

The suffix may be any bytes-like object.

備註

The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.

在 3.9 版被加入.

bytes.decode(encoding='utf-8', errors='strict')
bytearray.decode(encoding='utf-8', errors='strict')

Return the bytes decoded to a str.

encoding defaults to 'utf-8'; see Standard Encodings for possible values.

errors controls how decoding errors are handled. If 'strict' (the default), a UnicodeError exception is raised. Other possible values are 'ignore', 'replace', and any other name registered via codecs.register_error(). See Error Handlers for details.

For performance reasons, the value of errors is not checked for validity unless a decoding error actually occurs, Python 開發模式 is enabled or a debug build is used.

備註

Passing the encoding argument to str allows decoding any bytes-like object directly, without needing to make a temporary bytes or bytearray object.

在 3.1 版的變更: 新增關鍵字引數的支援。

在 3.9 版的變更: The value of the errors argument is now checked in Python 開發模式 and in debug mode.

bytes.endswith(suffix[, start[, end]])
bytearray.endswith(suffix[, start[, end]])

Return True if the binary data ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position.

The suffix(es) to search for may be any bytes-like object.

bytes.find(sub[, start[, end]])
bytearray.find(sub[, start[, end]])

Return the lowest index in the data where the subsequence sub is found, such that sub is contained in the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.

備註

The find() method should be used only if you need to know the position of sub. To check if sub is a substring or not, use the in operator:

>>> b'Py' in b'Python'
True

在 3.3 版的變更: Also accept an integer in the range 0 to 255 as the subsequence.

bytes.index(sub[, start[, end]])
bytearray.index(sub[, start[, end]])

Like find(), but raise ValueError when the subsequence is not found.

The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.

在 3.3 版的變更: Also accept an integer in the range 0 to 255 as the subsequence.

bytes.join(iterable)
bytearray.join(iterable)

Return a bytes or bytearray object which is the concatenation of the binary data sequences in iterable. A TypeError will be raised if there are any values in iterable that are not bytes-like objects, including str objects. The separator between elements is the contents of the bytes or bytearray object providing this method.

static bytes.maketrans(from, to)
static bytearray.maketrans(from, to)

This static method returns a translation table usable for bytes.translate() that will map each character in from into the character at the same position in to; from and to must both be bytes-like objects and have the same length.

在 3.1 版被加入.

bytes.partition(sep)
bytearray.partition(sep)

Split the sequence at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself or its bytearray copy, and the part after the separator. If the separator is not found, return a 3-tuple containing a copy of the original sequence, followed by two empty bytes or bytearray objects.

The separator to search for may be any bytes-like object.

bytes.replace(old, new[, count])
bytearray.replace(old, new[, count])

Return a copy of the sequence with all occurrences of subsequence old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

The subsequence to search for and its replacement may be any bytes-like object.

備註

The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.

bytes.rfind(sub[, start[, end]])
bytearray.rfind(sub[, start[, end]])

Return the highest index in the sequence where the subsequence sub is found, such that sub is contained within s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.

The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.

在 3.3 版的變更: Also accept an integer in the range 0 to 255 as the subsequence.

bytes.rindex(sub[, start[, end]])
bytearray.rindex(sub[, start[, end]])

Like rfind() but raises ValueError when the subsequence sub is not found.

The subsequence to search for may be any bytes-like object or an integer in the range 0 to 255.

在 3.3 版的變更: Also accept an integer in the range 0 to 255 as the subsequence.

bytes.rpartition(sep)
bytearray.rpartition(sep)

Split the sequence at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself or its bytearray copy, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty bytes or bytearray objects, followed by a copy of the original sequence.

The separator to search for may be any bytes-like object.

bytes.startswith(prefix[, start[, end]])
bytearray.startswith(prefix[, start[, end]])

Return True if the binary data starts with the specified prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position.

The prefix(es) to search for may be any bytes-like object.

bytes.translate(table, /, delete=b'')
bytearray.translate(table, /, delete=b'')

Return a copy of the bytes or bytearray object where all bytes occurring in the optional argument delete are removed, and the remaining bytes have been mapped through the given translation table, which must be a bytes object of length 256.

You can use the bytes.maketrans() method to create a translation table.

Set the table argument to None for translations that only delete characters:

>>> b'read this short text'.translate(None, b'aeiou')
b'rd ths shrt txt'

在 3.6 版的變更: delete is now supported as a keyword argument.

The following methods on bytes and bytearray objects have default behaviours that assume the use of ASCII compatible binary formats, but can still be used with arbitrary binary data by passing appropriate arguments. Note that all of the bytearray methods in this section do not operate in place, and instead produce new objects.

bytes.center(width[, fillbyte])
bytearray.center(width[, fillbyte])

Return a copy of the object centered in a sequence of length width. Padding is done using the specified fillbyte (default is an ASCII space). For bytes objects, the original sequence is returned if width is less than or equal to len(s).

備註

The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.

bytes.ljust(width[, fillbyte])
bytearray.ljust(width[, fillbyte])

Return a copy of the object left justified in a sequence of length width. Padding is done using the specified fillbyte (default is an ASCII space). For bytes objects, the original sequence is returned if width is less than or equal to len(s).

備註

The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.

bytes.lstrip([chars])
bytearray.lstrip([chars])

Return a copy of the sequence with specified leading bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or None, the chars argument defaults to removing ASCII whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped:

>>> b'   spacious   '.lstrip()
b'spacious   '
>>> b'www.example.com'.lstrip(b'cmowz.')
b'example.com'

The binary sequence of byte values to remove may be any bytes-like object. See removeprefix() for a method that will remove a single prefix string rather than all of a set of characters. For example:

>>> b'Arthur: three!'.lstrip(b'Arthur: ')
b'ee!'
>>> b'Arthur: three!'.removeprefix(b'Arthur: ')
b'three!'

備註

The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.

bytes.rjust(width[, fillbyte])
bytearray.rjust(width[, fillbyte])

Return a copy of the object right justified in a sequence of length width. Padding is done using the specified fillbyte (default is an ASCII space). For bytes objects, the original sequence is returned if width is less than or equal to len(s).

備註

The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.

bytes.rsplit(sep=None, maxsplit=-1)
bytearray.rsplit(sep=None, maxsplit=-1)

Split the binary sequence into subsequences of the same type, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or None, any subsequence consisting solely of ASCII whitespace is a separator. Except for splitting from the right, rsplit() behaves like split() which is described in detail below.

bytes.rstrip([chars])
bytearray.rstrip([chars])

Return a copy of the sequence with specified trailing bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or None, the chars argument defaults to removing ASCII whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped:

>>> b'   spacious   '.rstrip()
b'   spacious'
>>> b'mississippi'.rstrip(b'ipz')
b'mississ'

The binary sequence of byte values to remove may be any bytes-like object. See removesuffix() for a method that will remove a single suffix string rather than all of a set of characters. For example:

>>> b'Monty Python'.rstrip(b' Python')
b'M'
>>> b'Monty Python'.removesuffix(b' Python')
b'Monty'

備註

The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.

bytes.split(sep=None, maxsplit=-1)
bytearray.split(sep=None, maxsplit=-1)

Split the binary sequence into subsequences of the same type, using sep as the delimiter string. If maxsplit is given and non-negative, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or is -1, then there is no limit on the number of splits (all possible splits are made).

If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty subsequences (for example, b'1,,2'.split(b',') returns [b'1', b'', b'2']). The sep argument may consist of a multibyte sequence as a single delimiter. Splitting an empty sequence with a specified separator returns [b''] or [bytearray(b'')] depending on the type of object being split. The sep argument may be any bytes-like object.

舉例來說:

>>> b'1,2,3'.split(b',')
[b'1', b'2', b'3']
>>> b'1,2,3'.split(b',', maxsplit=1)
[b'1', b'2,3']
>>> b'1,2,,3,'.split(b',')
[b'1', b'2', b'', b'3', b'']
>>> b'1<>2<>3<4'.split(b'<>')
[b'1', b'2', b'3<4']

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive ASCII whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the sequence has leading or trailing whitespace. Consequently, splitting an empty sequence or a sequence consisting solely of ASCII whitespace without a specified separator returns [].

舉例來說:

>>> b'1 2 3'.split()
[b'1', b'2', b'3']
>>> b'1 2 3'.split(maxsplit=1)
[b'1', b'2 3']
>>> b'   1   2   3   '.split()
[b'1', b'2', b'3']
bytes.strip([chars])
bytearray.strip([chars])

Return a copy of the sequence with specified leading and trailing bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or None, the chars argument defaults to removing ASCII whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:

>>> b'   spacious   '.strip()
b'spacious'
>>> b'www.example.com'.strip(b'cmowz.')
b'example'

The binary sequence of byte values to remove may be any bytes-like object.

備註

The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.

The following methods on bytes and bytearray objects assume the use of ASCII compatible binary formats and should not be applied to arbitrary binary data. Note that all of the bytearray methods in this section do not operate in place, and instead produce new objects.

bytes.capitalize()
bytearray.capitalize()

Return a copy of the sequence with each byte interpreted as an ASCII character, and the first byte capitalized and the rest lowercased. Non-ASCII byte values are passed through unchanged.

備註

The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.

bytes.expandtabs(tabsize=8)
bytearray.expandtabs(tabsize=8)

Return a copy of the sequence where all ASCII tab characters are replaced by one or more ASCII spaces, depending on the current column and the given tab size. Tab positions occur every tabsize bytes (default is 8, giving tab positions at columns 0, 8, 16 and so on). To expand the sequence, the current column is set to zero and the sequence is examined byte by byte. If the byte is an ASCII tab character (b'\t'), one or more space characters are inserted in the result until the current column is equal to the next tab position. (The tab character itself is not copied.) If the current byte is an ASCII newline (b'\n') or carriage return (b'\r'), it is copied and the current column is reset to zero. Any other byte value is copied unchanged and the current column is incremented by one regardless of how the byte value is represented when printed:

>>> b'01\t012\t0123\t01234'.expandtabs()
b'01      012     0123    01234'
>>> b'01\t012\t0123\t01234'.expandtabs(4)
b'01  012 0123    01234'

備註

The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.

bytes.isalnum()
bytearray.isalnum()

Return True if all bytes in the sequence are alphabetical ASCII characters or ASCII decimal digits and the sequence is not empty, False otherwise. Alphabetic ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'. ASCII decimal digits are those byte values in the sequence b'0123456789'.

舉例來說:

>>> b'ABCabc1'.isalnum()
True
>>> b'ABC abc1'.isalnum()
False
bytes.isalpha()
bytearray.isalpha()

Return True if all bytes in the sequence are alphabetic ASCII characters and the sequence is not empty, False otherwise. Alphabetic ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.

舉例來說:

>>> b'ABCabc'.isalpha()
True
>>> b'ABCabc1'.isalpha()
False
bytes.isascii()
bytearray.isascii()

Return True if the sequence is empty or all bytes in the sequence are ASCII, False otherwise. ASCII bytes are in the range 0-0x7F.

在 3.7 版被加入.

bytes.isdigit()
bytearray.isdigit()

Return True if all bytes in the sequence are ASCII decimal digits and the sequence is not empty, False otherwise. ASCII decimal digits are those byte values in the sequence b'0123456789'.

舉例來說:

>>> b'1234'.isdigit()
True
>>> b'1.23'.isdigit()
False
bytes.islower()
bytearray.islower()

Return True if there is at least one lowercase ASCII character in the sequence and no uppercase ASCII characters, False otherwise.

舉例來說:

>>> b'hello world'.islower()
True
>>> b'Hello world'.islower()
False

Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.

bytes.isspace()
bytearray.isspace()

Return True if all bytes in the sequence are ASCII whitespace and the sequence is not empty, False otherwise. ASCII whitespace characters are those byte values in the sequence b' \t\n\r\x0b\f' (space, tab, newline, carriage return, vertical tab, form feed).

bytes.istitle()
bytearray.istitle()

Return True if the sequence is ASCII titlecase and the sequence is not empty, False otherwise. See bytes.title() for more details on the definition of "titlecase".

舉例來說:

>>> b'Hello World'.istitle()
True
>>> b'Hello world'.istitle()
False
bytes.isupper()
bytearray.isupper()

Return True if there is at least one uppercase alphabetic ASCII character in the sequence and no lowercase ASCII characters, False otherwise.

舉例來說:

>>> b'HELLO WORLD'.isupper()
True
>>> b'Hello world'.isupper()
False

Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.

bytes.lower()
bytearray.lower()

Return a copy of the sequence with all the uppercase ASCII characters converted to their corresponding lowercase counterpart.

舉例來說:

>>> b'Hello World'.lower()
b'hello world'

Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.

備註

The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.

bytes.splitlines(keepends=False)
bytearray.splitlines(keepends=False)

Return a list of the lines in the binary sequence, breaking at ASCII line boundaries. This method uses the universal newlines approach to splitting lines. Line breaks are not included in the resulting list unless keepends is given and true.

舉例來說:

>>> b'ab c\n\nde fg\rkl\r\n'.splitlines()
[b'ab c', b'', b'de fg', b'kl']
>>> b'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
[b'ab c\n', b'\n', b'de fg\r', b'kl\r\n']

Unlike split() when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:

>>> b"".split(b'\n'), b"Two lines\n".split(b'\n')
([b''], [b'Two lines', b''])
>>> b"".splitlines(), b"One line\n".splitlines()
([], [b'One line'])
bytes.swapcase()
bytearray.swapcase()

Return a copy of the sequence with all the lowercase ASCII characters converted to their corresponding uppercase counterpart and vice-versa.

舉例來說:

>>> b'Hello World'.swapcase()
b'hELLO wORLD'

Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.

Unlike str.swapcase(), it is always the case that bin.swapcase().swapcase() == bin for the binary versions. Case conversions are symmetrical in ASCII, even though that is not generally true for arbitrary Unicode code points.

備註

The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.

bytes.title()
bytearray.title()

Return a titlecased version of the binary sequence where words start with an uppercase ASCII character and the remaining characters are lowercase. Uncased byte values are left unmodified.

舉例來說:

>>> b'Hello world'.title()
b'Hello World'

Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. All other byte values are uncased.

The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result:

>>> b"they're bill's friends from the UK".title()
b"They'Re Bill'S Friends From The Uk"

A workaround for apostrophes can be constructed using regular expressions:

>>> import re
>>> def titlecase(s):
...     return re.sub(rb"[A-Za-z]+('[A-Za-z]+)?",
...                   lambda mo: mo.group(0)[0:1].upper() +
...                              mo.group(0)[1:].lower(),
...                   s)
...
>>> titlecase(b"they're bill's friends.")
b"They're Bill's Friends."

備註

The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.

bytes.upper()
bytearray.upper()

Return a copy of the sequence with all the lowercase ASCII characters converted to their corresponding uppercase counterpart.

舉例來說:

>>> b'Hello World'.upper()
b'HELLO WORLD'

Lowercase ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyz'. Uppercase ASCII characters are those byte values in the sequence b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.

備註

The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.

bytes.zfill(width)
bytearray.zfill(width)

Return a copy of the sequence left filled with ASCII b'0' digits to make a sequence of length width. A leading sign prefix (b'+'/ b'-') is handled by inserting the padding after the sign character rather than before. For bytes objects, the original sequence is returned if width is less than or equal to len(seq).

舉例來說:

>>> b"42".zfill(5)
b'00042'
>>> b"-42".zfill(5)
b'-0042'

備註

The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.

printf-style Bytes Formatting

備註

The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). If the value being printed may be a tuple or dictionary, wrap it in a tuple.

Bytes objects (bytes/bytearray) have one unique built-in operation: the % operator (modulo). This is also known as the bytes formatting or interpolation operator. Given format % values (where format is a bytes object), % conversion specifications in format are replaced with zero or more elements of values. The effect is similar to using the sprintf() in the C language.

If format requires a single argument, values may be a single non-tuple object. [5] Otherwise, values must be a tuple with exactly the number of items specified by the format bytes object, or a single mapping object (for example, a dictionary).

A conversion specifier contains two or more characters and has the following components, which must occur in this order:

  1. The '%' character, which marks the start of the specifier.

  2. Mapping key (optional), consisting of a parenthesised sequence of characters (for example, (somename)).

  3. Conversion flags (optional), which affect the result of some conversion types.

  4. Minimum field width (optional). If specified as an '*' (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision.

  5. Precision (optional), given as a '.' (dot) followed by the precision. If specified as '*' (an asterisk), the actual precision is read from the next element of the tuple in values, and the value to convert comes after the precision.

  6. Length modifier (optional).

  7. Conversion type.

When the right argument is a dictionary (or other mapping type), then the formats in the bytes object must include a parenthesised mapping key into that dictionary inserted immediately after the '%' character. The mapping key selects the value to be formatted from the mapping. For example:

>>> print(b'%(language)s has %(number)03d quote types.' %
...       {b'language': b"Python", b"number": 2})
b'Python has 002 quote types.'

In this case no * specifiers may occur in a format (since they require a sequential parameter list).

The conversion flag characters are:

Flag

含義

'#'

The value conversion will use the "alternate form" (where defined below).

'0'

The conversion will be zero padded for numeric values.

'-'

The converted value is left adjusted (overrides the '0' conversion if both are given).

' '

(a space) A blank should be left before a positive number (or empty string) produced by a signed conversion.

'+'

A sign character ('+' or '-') will precede the conversion (overrides a "space" flag).

A length modifier (h, l, or L) may be present, but is ignored as it is not necessary for Python -- so e.g. %ld is identical to %d.

The conversion types are:

Conversion

含義

註解

'd'

Signed integer decimal.

'i'

Signed integer decimal.

'o'

Signed octal value.

(1)

'u'

Obsolete type -- it is identical to 'd'.

(8)

'x'

Signed hexadecimal (lowercase).

(2)

'X'

Signed hexadecimal (uppercase).

(2)

'e'

Floating-point exponential format (lowercase).

(3)

'E'

Floating-point exponential format (uppercase).

(3)

'f'

Floating-point decimal format.

(3)

'F'

Floating-point decimal format.

(3)

'g'

Floating-point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.

(4)

'G'

Floating-point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.

(4)

'c'

Single byte (accepts integer or single byte objects).

'b'

Bytes (any object that follows the buffer protocol or has __bytes__()).

(5)

's'

's' is an alias for 'b' and should only be used for Python2/3 code bases.

(6)

'a'

Bytes (converts any Python object using repr(obj).encode('ascii', 'backslashreplace')).

(5)

'r'

'r' is an alias for 'a' and should only be used for Python2/3 code bases.

(7)

'%'

No argument is converted, results in a '%' character in the result.

註解:

  1. The alternate form causes a leading octal specifier ('0o') to be inserted before the first digit.

  2. The alternate form causes a leading '0x' or '0X' (depending on whether the 'x' or 'X' format was used) to be inserted before the first digit.

  3. The alternate form causes the result to always contain a decimal point, even if no digits follow it.

    The precision determines the number of digits after the decimal point and defaults to 6.

  4. The alternate form causes the result to always contain a decimal point, and trailing zeroes are not removed as they would otherwise be.

    The precision determines the number of significant digits before and after the decimal point and defaults to 6.

  5. If precision is N, the output is truncated to N characters.

  6. b'%s' is deprecated, but will not be removed during the 3.x series.

  7. b'%r' is deprecated, but will not be removed during the 3.x series.

  8. 參閱 PEP 237

備註

The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.

也參考

PEP 461 - Adding % formatting to bytes and bytearray

在 3.5 版被加入.

Memory Views

memoryview objects allow Python code to access the internal data of an object that supports the buffer protocol without copying.

class memoryview(object)

Create a memoryview that references object. object must support the buffer protocol. Built-in objects that support the buffer protocol include bytes and bytearray.

A memoryview has the notion of an element, which is the atomic memory unit handled by the originating object. For many simple types such as bytes and bytearray, an element is a single byte, but other types such as array.array may have bigger elements.

len(view) is equal to the length of tolist, which is the nested list representation of the view. If view.ndim = 1, this is equal to the number of elements in the view.

在 3.12 版的變更: If view.ndim == 0, len(view) now raises TypeError instead of returning 1.

The itemsize attribute will give you the number of bytes in a single element.

A memoryview supports slicing and indexing to expose its data. One-dimensional slicing will result in a subview:

>>> v = memoryview(b'abcefg')
>>> v[1]
98
>>> v[-1]
103
>>> v[1:4]
<memory at 0x7f3ddc9f4350>
>>> bytes(v[1:4])
b'bce'

If format is one of the native format specifiers from the struct module, indexing with an integer or a tuple of integers is also supported and returns a single element with the correct type. One-dimensional memoryviews can be indexed with an integer or a one-integer tuple. Multi-dimensional memoryviews can be indexed with tuples of exactly ndim integers where ndim is the number of dimensions. Zero-dimensional memoryviews can be indexed with the empty tuple.

Here is an example with a non-byte format:

>>> import array
>>> a = array.array('l', [-11111111, 22222222, -33333333, 44444444])
>>> m = memoryview(a)
>>> m[0]
-11111111
>>> m[-1]
44444444
>>> m[::2].tolist()
[-11111111, -33333333]

If the underlying object is writable, the memoryview supports one-dimensional slice assignment. Resizing is not allowed:

>>> data = bytearray(b'abcefg')
>>> v = memoryview(data)
>>> v.readonly
False
>>> v[0] = ord(b'z')
>>> data
bytearray(b'zbcefg')
>>> v[1:4] = b'123'
>>> data
bytearray(b'z123fg')
>>> v[2:3] = b'spam'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: memoryview assignment: lvalue and rvalue have different structures
>>> v[2:6] = b'spam'
>>> data
bytearray(b'z1spam')

One-dimensional memoryviews of hashable (read-only) types with formats 'B', 'b' or 'c' are also hashable. The hash is defined as hash(m) == hash(m.tobytes()):

>>> v = memoryview(b'abcefg')
>>> hash(v) == hash(b'abcefg')
True
>>> hash(v[2:4]) == hash(b'ce')
True
>>> hash(v[::-2]) == hash(b'abcefg'[::-2])
True

在 3.3 版的變更: One-dimensional memoryviews can now be sliced. One-dimensional memoryviews with formats 'B', 'b' or 'c' are now hashable.

在 3.4 版的變更: memoryview is now registered automatically with collections.abc.Sequence

在 3.5 版的變更: memoryviews can now be indexed with tuple of integers.

在 3.14 版的變更: memoryview is now a generic type.

memoryview has several methods:

__eq__(exporter)

A memoryview and a PEP 3118 exporter are equal if their shapes are equivalent and if all corresponding values are equal when the operands' respective format codes are interpreted using struct syntax.

For the subset of struct format strings currently supported by tolist(), v and w are equal if v.tolist() == w.tolist():

>>> import array
>>> a = array.array('I', [1, 2, 3, 4, 5])
>>> b = array.array('d', [1.0, 2.0, 3.0, 4.0, 5.0])
>>> c = array.array('b', [5, 3, 1])
>>> x = memoryview(a)
>>> y = memoryview(b)
>>> x == a == y == b
True
>>> x.tolist() == a.tolist() == y.tolist() == b.tolist()
True
>>> z = y[::-2]
>>> z == c
True
>>> z.tolist() == c.tolist()
True

If either format string is not supported by the struct module, then the objects will always compare as unequal (even if the format strings and buffer contents are identical):

>>> from ctypes import BigEndianStructure, c_long
>>> class BEPoint(BigEndianStructure):
...     _fields_ = [("x", c_long), ("y", c_long)]
...
>>> point = BEPoint(100, 200)
>>> a = memoryview(point)
>>> b = memoryview(point)
>>> a == point
False
>>> a == b
False

Note that, as with floating-point numbers, v is w does not imply v == w for memoryview objects.

在 3.3 版的變更: Previous versions compared the raw memory disregarding the item format and the logical array structure.

tobytes(order='C')

Return the data in the buffer as a bytestring. This is equivalent to calling the bytes constructor on the memoryview.

>>> m = memoryview(b"abc")
>>> m.tobytes()
b'abc'
>>> bytes(m)
b'abc'

For non-contiguous arrays the result is equal to the flattened list representation with all elements converted to bytes. tobytes() supports all format strings, including those that are not in struct module syntax.

在 3.8 版被加入: order can be {'C', 'F', 'A'}. When order is 'C' or 'F', the data of the original array is converted to C or Fortran order. For contiguous views, 'A' returns an exact copy of the physical memory. In particular, in-memory Fortran order is preserved. For non-contiguous views, the data is converted to C first. order=None is the same as order='C'.

hex([sep[, bytes_per_sep]])

Return a string object containing two hexadecimal digits for each byte in the buffer.

>>> m = memoryview(b"abc")
>>> m.hex()
'616263'

在 3.5 版被加入.

在 3.8 版的變更: Similar to bytes.hex(), memoryview.hex() now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output.

tolist()

Return the data in the buffer as a list of elements.

>>> memoryview(b'abc').tolist()
[97, 98, 99]
>>> import array
>>> a = array.array('d', [1.1, 2.2, 3.3])
>>> m = memoryview(a)
>>> m.tolist()
[1.1, 2.2, 3.3]

在 3.3 版的變更: tolist() now supports all single character native formats in struct module syntax as well as multi-dimensional representations.

toreadonly()

Return a readonly version of the memoryview object. The original memoryview object is unchanged.

>>> m = memoryview(bytearray(b'abc'))
>>> mm = m.toreadonly()
>>> mm.tolist()
[97, 98, 99]
>>> mm[0] = 42
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot modify read-only memory
>>> m[0] = 43
>>> mm.tolist()
[43, 98, 99]

在 3.8 版被加入.

release()

Release the underlying buffer exposed by the memoryview object. Many objects take special actions when a view is held on them (for example, a bytearray would temporarily forbid resizing); therefore, calling release() is handy to remove these restrictions (and free any dangling resources) as soon as possible.

After this method has been called, any further operation on the view raises a ValueError (except release() itself which can be called multiple times):

>>> m = memoryview(b'abc')
>>> m.release()
>>> m[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operation forbidden on released memoryview object

The context management protocol can be used for a similar effect, using the with statement:

>>> with memoryview(b'abc') as m:
...     m[0]
...
97
>>> m[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operation forbidden on released memoryview object

在 3.2 版被加入.

cast(format[, shape])

Cast a memoryview to a new format or shape. shape defaults to [byte_length//new_itemsize], which means that the result view will be one-dimensional. The return value is a new memoryview, but the buffer itself is not copied. Supported casts are 1D -> C-contiguous and C-contiguous -> 1D.

The destination format is restricted to a single element native format in struct syntax. One of the formats must be a byte format ('B', 'b' or 'c'). The byte length of the result must be the same as the original length. Note that all byte lengths may depend on the operating system.

Cast 1D/long to 1D/unsigned bytes:

>>> import array
>>> a = array.array('l', [1,2,3])
>>> x = memoryview(a)
>>> x.format
'l'
>>> x.itemsize
8
>>> len(x)
3
>>> x.nbytes
24
>>> y = x.cast('B')
>>> y.format
'B'
>>> y.itemsize
1
>>> len(y)
24
>>> y.nbytes
24

Cast 1D/unsigned bytes to 1D/char:

>>> b = bytearray(b'zyz')
>>> x = memoryview(b)
>>> x[0] = b'a'
Traceback (most recent call last):
  ...
TypeError: memoryview: invalid type for format 'B'
>>> y = x.cast('c')
>>> y[0] = b'a'
>>> b
bytearray(b'ayz')

Cast 1D/bytes to 3D/ints to 1D/signed char:

>>> import struct
>>> buf = struct.pack("i"*12, *list(range(12)))
>>> x = memoryview(buf)
>>> y = x.cast('i', shape=[2,2,3])
>>> y.tolist()
[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]
>>> y.format
'i'
>>> y.itemsize
4
>>> len(y)
2
>>> y.nbytes
48
>>> z = y.cast('b')
>>> z.format
'b'
>>> z.itemsize
1
>>> len(z)
48
>>> z.nbytes
48

Cast 1D/unsigned long to 2D/unsigned long:

>>> buf = struct.pack("L"*6, *list(range(6)))
>>> x = memoryview(buf)
>>> y = x.cast('L', shape=[2,3])
>>> len(y)
2
>>> y.nbytes
48
>>> y.tolist()
[[0, 1, 2], [3, 4, 5]]

在 3.3 版被加入.

在 3.5 版的變更: The source format is no longer restricted when casting to a byte view.

There are also several readonly attributes available:

obj

The underlying object of the memoryview:

>>> b  = bytearray(b'xyz')
>>> m = memoryview(b)
>>> m.obj is b
True

在 3.3 版被加入.

nbytes

nbytes == product(shape) * itemsize == len(m.tobytes()). This is the amount of space in bytes that the array would use in a contiguous representation. It is not necessarily equal to len(m):

>>> import array
>>> a = array.array('i', [1,2,3,4,5])
>>> m = memoryview(a)
>>> len(m)
5
>>> m.nbytes
20
>>> y = m[::2]
>>> len(y)
3
>>> y.nbytes
12
>>> len(y.tobytes())
12

Multi-dimensional arrays:

>>> import struct
>>> buf = struct.pack("d"*12, *[1.5*x for x in range(12)])
>>> x = memoryview(buf)
>>> y = x.cast('d', shape=[3,4])
>>> y.tolist()
[[0.0, 1.5, 3.0, 4.5], [6.0, 7.5, 9.0, 10.5], [12.0, 13.5, 15.0, 16.5]]
>>> len(y)
3
>>> y.nbytes
96

在 3.3 版被加入.

readonly

A bool indicating whether the memory is read only.

format

A string containing the format (in struct module style) for each element in the view. A memoryview can be created from exporters with arbitrary format strings, but some methods (e.g. tolist()) are restricted to native single element formats.

在 3.3 版的變更: format 'B' is now handled according to the struct module syntax. This means that memoryview(b'abc')[0] == b'abc'[0] == 97.

itemsize

The size in bytes of each element of the memoryview:

>>> import array, struct
>>> m = memoryview(array.array('H', [32000, 32001, 32002]))
>>> m.itemsize
2
>>> m[0]
32000
>>> struct.calcsize('H') == m.itemsize
True
ndim

An integer indicating how many dimensions of a multi-dimensional array the memory represents.

shape

A tuple of integers the length of ndim giving the shape of the memory as an N-dimensional array.

在 3.3 版的變更: An empty tuple instead of None when ndim = 0.

strides

A tuple of integers the length of ndim giving the size in bytes to access each element for each dimension of the array.

在 3.3 版的變更: An empty tuple instead of None when ndim = 0.

suboffsets

Used internally for PIL-style arrays. The value is informational only.

c_contiguous

A bool indicating whether the memory is C-contiguous.

在 3.3 版被加入.

f_contiguous

A bool indicating whether the memory is Fortran contiguous.

在 3.3 版被加入.

contiguous

A bool indicating whether the memory is contiguous.

在 3.3 版被加入.

Set Types --- set, frozenset

A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. (For other containers see the built-in dict, list, and tuple classes, and the collections module.)

Like other collections, sets support x in set, len(set), and for x in set. Being an unordered collection, sets do not record element position or order of insertion. Accordingly, sets do not support indexing, slicing, or other sequence-like behavior.

There are currently two built-in set types, set and frozenset. The set type is mutable --- the contents can be changed using methods like add() and remove(). Since it is mutable, it has no hash value and cannot be used as either a dictionary key or as an element of another set. The frozenset type is immutable and hashable --- its contents cannot be altered after it is created; it can therefore be used as a dictionary key or as an element of another set.

Non-empty sets (not frozensets) can be created by placing a comma-separated list of elements within braces, for example: {'jack', 'sjoerd'}, in addition to the set constructor.

The constructors for both classes work the same:

class set([iterable])
class frozenset([iterable])

Return a new set or frozenset object whose elements are taken from iterable. The elements of a set must be hashable. To represent sets of sets, the inner sets must be frozenset objects. If iterable is not specified, a new empty set is returned.

Sets can be created by several means:

  • Use a comma-separated list of elements within braces: {'jack', 'sjoerd'}

  • Use a set comprehension: {c for c in 'abracadabra' if c not in 'abc'}

  • Use the type constructor: set(), set('foobar'), set(['a', 'b', 'foo'])

Instances of set and frozenset provide the following operations:

len(s)

Return the number of elements in set s (cardinality of s).

x in s

Test x for membership in s.

x not in s

Test x for non-membership in s.

isdisjoint(other)

Return True if the set has no elements in common with other. Sets are disjoint if and only if their intersection is the empty set.

issubset(other)
set <= other

Test whether every element in the set is in other.

set < other

Test whether the set is a proper subset of other, that is, set <= other and set != other.

issuperset(other)
set >= other

Test whether every element in other is in the set.

set > other

Test whether the set is a proper superset of other, that is, set >= other and set != other.

union(*others)
set | other | ...

Return a new set with elements from the set and all others.

intersection(*others)
set & other & ...

Return a new set with elements common to the set and all others.

difference(*others)
set - other - ...

Return a new set with elements in the set that are not in the others.

symmetric_difference(other)
set ^ other

Return a new set with elements in either the set or other but not both.

copy()

Return a shallow copy of the set.

Note, the non-operator versions of union(), intersection(), difference(), symmetric_difference(), issubset(), and issuperset() methods will accept any iterable as an argument. In contrast, their operator based counterparts require their arguments to be sets. This precludes error-prone constructions like set('abc') & 'cbs' in favor of the more readable set('abc').intersection('cbs').

Both set and frozenset support set to set comparisons. Two sets are equal if and only if every element of each set is contained in the other (each is a subset of the other). A set is less than another set if and only if the first set is a proper subset of the second set (is a subset, but is not equal). A set is greater than another set if and only if the first set is a proper superset of the second set (is a superset, but is not equal).

Instances of set are compared to instances of frozenset based on their members. For example, set('abc') == frozenset('abc') returns True and so does set('abc') in set([frozenset('abc')]).

The subset and equality comparisons do not generalize to a total ordering function. For example, any two nonempty disjoint sets are not equal and are not subsets of each other, so all of the following return False: a<b, a==b, or a>b.

Since sets only define partial ordering (subset relationships), the output of the list.sort() method is undefined for lists of sets.

Set elements, like dictionary keys, must be hashable.

Binary operations that mix set instances with frozenset return the type of the first operand. For example: frozenset('ab') | set('bc') returns an instance of frozenset.

The following table lists operations available for set that do not apply to immutable instances of frozenset:

update(*others)
set |= other | ...

Update the set, adding elements from all others.

intersection_update(*others)
set &= other & ...

Update the set, keeping only elements found in it and all others.

difference_update(*others)
set -= other | ...

Update the set, removing elements found in others.

symmetric_difference_update(other)
set ^= other

Update the set, keeping only elements found in either set, but not in both.

add(elem)

Add element elem to the set.

remove(elem)

Remove element elem from the set. Raises KeyError if elem is not contained in the set.

discard(elem)

Remove element elem from the set if it is present.

pop()

Remove and return an arbitrary element from the set. Raises KeyError if the set is empty.

clear()

Remove all elements from the set.

Note, the non-operator versions of the update(), intersection_update(), difference_update(), and symmetric_difference_update() methods will accept any iterable as an argument.

Note, the elem argument to the __contains__(), remove(), and discard() methods may be a set. To support searching for an equivalent frozenset, a temporary one is created from elem.

Mapping Types --- dict

A mapping object maps hashable values to arbitrary objects. Mappings are mutable objects. There is currently only one standard mapping type, the dictionary. (For other containers see the built-in list, set, and tuple classes, and the collections module.)

A dictionary's keys are almost arbitrary values. Values that are not hashable, that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys. Values that compare equal (such as 1, 1.0, and True) can be used interchangeably to index the same dictionary entry.

class dict(**kwargs)
class dict(mapping, **kwargs)
class dict(iterable, **kwargs)

Return a new dictionary initialized from an optional positional argument and a possibly empty set of keyword arguments.

Dictionaries can be created by several means:

  • Use a comma-separated list of key: value pairs within braces: {'jack': 4098, 'sjoerd': 4127} or {4098: 'jack', 4127: 'sjoerd'}

  • Use a dict comprehension: {}, {x: x ** 2 for x in range(10)}

  • Use the type constructor: dict(), dict([('foo', 100), ('bar', 200)]), dict(foo=100, bar=200)

If no positional argument is given, an empty dictionary is created. If a positional argument is given and it defines a keys() method, a dictionary is created by calling __getitem__() on the argument with each returned key from the method. Otherwise, the positional argument must be an iterable object. Each item in the iterable must itself be an iterable with exactly two elements. The first element of each item becomes a key in the new dictionary, and the second element the corresponding value. If a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary.

If keyword arguments are given, the keyword arguments and their values are added to the dictionary created from the positional argument. If a key being added is already present, the value from the keyword argument replaces the value from the positional argument.

To illustrate, the following examples all return a dictionary equal to {"one": 1, "two": 2, "three": 3}:

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> f = dict({'one': 1, 'three': 3}, two=2)
>>> a == b == c == d == e == f
True

Providing keyword arguments as in the first example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used.

These are the operations that dictionaries support (and therefore, custom mapping types should support too):

list(d)

Return a list of all the keys used in the dictionary d.

len(d)

Return the number of items in the dictionary d.

d[key]

Return the item of d with key key. Raises a KeyError if key is not in the map.

If a subclass of dict defines a method __missing__() and key is not present, the d[key] operation calls that method with the key key as argument. The d[key] operation then returns or raises whatever is returned or raised by the __missing__(key) call. No other operations or methods invoke __missing__(). If __missing__() is not defined, KeyError is raised. __missing__() must be a method; it cannot be an instance variable:

>>> class Counter(dict):
...     def __missing__(self, key):
...         return 0
...
>>> c = Counter()
>>> c['red']
0
>>> c['red'] += 1
>>> c['red']
1

The example above shows part of the implementation of collections.Counter. A different __missing__ method is used by collections.defaultdict.

d[key] = value

Set d[key] to value.

del d[key]

Remove d[key] from d. Raises a KeyError if key is not in the map.

key in d

Return True if d has a key key, else False.

key not in d

Equivalent to not key in d.

iter(d)

Return an iterator over the keys of the dictionary. This is a shortcut for iter(d.keys()).

clear()

Remove all items from the dictionary.

copy()

Return a shallow copy of the dictionary.

classmethod fromkeys(iterable, value=None, /)

Create a new dictionary with keys from iterable and values set to value.

fromkeys() is a class method that returns a new dictionary. value defaults to None. All of the values refer to just a single instance, so it generally doesn't make sense for value to be a mutable object such as an empty list. To get distinct values, use a dict comprehension instead.

get(key, default=None)

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

items()

Return a new view of the dictionary's items ((key, value) pairs). See the documentation of view objects.

keys()

Return a new view of the dictionary's keys. See the documentation of view objects.

pop(key[, default])

If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.

popitem()

Remove and return a (key, value) pair from the dictionary. Pairs are returned in LIFO order.

popitem() is useful to destructively iterate over a dictionary, as often used in set algorithms. If the dictionary is empty, calling popitem() raises a KeyError.

在 3.7 版的變更: LIFO order is now guaranteed. In prior versions, popitem() would return an arbitrary key/value pair.

reversed(d)

Return a reverse iterator over the keys of the dictionary. This is a shortcut for reversed(d.keys()).

在 3.8 版被加入.

setdefault(key, default=None)

If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.

update([other])

Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.

update() accepts either another object with a keys() method (in which case __getitem__() is called with every key returned from the method) or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: d.update(red=1, blue=2).

values()

Return a new view of the dictionary's values. See the documentation of view objects.

An equality comparison between one dict.values() view and another will always return False. This also applies when comparing dict.values() to itself:

>>> d = {'a': 1}
>>> d.values() == d.values()
False
d | other

Create a new dictionary with the merged keys and values of d and other, which must both be dictionaries. The values of other take priority when d and other share keys.

在 3.9 版被加入.

d |= other

Update the dictionary d with keys and values from other, which may be either a mapping or an iterable of key/value pairs. The values of other take priority when d and other share keys.

在 3.9 版被加入.

Dictionaries compare equal if and only if they have the same (key, value) pairs (regardless of ordering). Order comparisons ('<', '<=', '>=', '>') raise TypeError.

Dictionaries preserve insertion order. Note that updating a key does not affect the order. Keys added after deletion are inserted at the end.

>>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
>>> d
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> list(d)
['one', 'two', 'three', 'four']
>>> list(d.values())
[1, 2, 3, 4]
>>> d["one"] = 42
>>> d
{'one': 42, 'two': 2, 'three': 3, 'four': 4}
>>> del d["two"]
>>> d["two"] = None
>>> d
{'one': 42, 'three': 3, 'four': 4, 'two': None}

在 3.7 版的變更: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.

Dictionaries and dictionary views are reversible.

>>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
>>> d
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> list(reversed(d))
['four', 'three', 'two', 'one']
>>> list(reversed(d.values()))
[4, 3, 2, 1]
>>> list(reversed(d.items()))
[('four', 4), ('three', 3), ('two', 2), ('one', 1)]

在 3.8 版的變更: Dictionaries are now reversible.

也參考

types.MappingProxyType can be used to create a read-only view of a dict.

字典視圖物件

The objects returned by dict.keys(), dict.values() and dict.items() are view objects. They provide a dynamic view on the dictionary's entries, which means that when the dictionary changes, the view reflects these changes.

Dictionary views can be iterated over to yield their respective data, and support membership tests:

len(dictview)

Return the number of entries in the dictionary.

iter(dictview)

Return an iterator over the keys, values or items (represented as tuples of (key, value)) in the dictionary.

Keys and values are iterated over in insertion order. This allows the creation of (value, key) pairs using zip(): pairs = zip(d.values(), d.keys()). Another way to create the same list is pairs = [(v, k) for (k, v) in d.items()].

Iterating views while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries.

在 3.7 版的變更: Dictionary order is guaranteed to be insertion order.

x in dictview

Return True if x is in the underlying dictionary's keys, values or items (in the latter case, x should be a (key, value) tuple).

reversed(dictview)

Return a reverse iterator over the keys, values or items of the dictionary. The view will be iterated in reverse order of the insertion.

在 3.8 版的變更: Dictionary views are now reversible.

dictview.mapping

Return a types.MappingProxyType that wraps the original dictionary to which the view refers.

在 3.10 版被加入.

Keys views are set-like since their entries are unique and hashable. Items views also have set-like operations since the (key, value) pairs are unique and the keys are hashable. If all values in an items view are hashable as well, then the items view can interoperate with other sets. (Values views are not treated as set-like since the entries are generally not unique.) For set-like views, all of the operations defined for the abstract base class collections.abc.Set are available (for example, ==, <, or ^). While using set operators, set-like views accept any iterable as the other operand, unlike sets which only accept sets as the input.

An example of dictionary view usage:

>>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
>>> keys = dishes.keys()
>>> values = dishes.values()

>>> # iteration
>>> n = 0
>>> for val in values:
...     n += val
...
>>> print(n)
504

>>> # keys and values are iterated over in the same order (insertion order)
>>> list(keys)
['eggs', 'sausage', 'bacon', 'spam']
>>> list(values)
[2, 1, 1, 500]

>>> # view objects are dynamic and reflect dict changes
>>> del dishes['eggs']
>>> del dishes['sausage']
>>> list(keys)
['bacon', 'spam']

>>> # set operations
>>> keys & {'eggs', 'bacon', 'salad'}
{'bacon'}
>>> keys ^ {'sausage', 'juice'} == {'juice', 'sausage', 'bacon', 'spam'}
True
>>> keys | ['juice', 'juice', 'juice'] == {'bacon', 'spam', 'juice'}
True

>>> # get back a read-only proxy for the original dictionary
>>> values.mapping
mappingproxy({'bacon': 1, 'spam': 500})
>>> values.mapping['spam']
500

情境管理器型別

Python 的 with 陳述式支援了由情境管理器定義之 runtime 情境的概念,要使用兩個方法來實作,該方法讓使用者定義類別能夠去定義 runtime 情境,且該情境在執行陳述式主體 (statement body) 之前進入、在陳述式結束時退出:

contextmanager.__enter__()

輸入 runtime 情境並回傳此物件或者與 runtime 情境相關的另一個物件。此方法回傳的值有被綁定到使用此情境管理器的 with 陳述式的 as 子句中的識別字。

一個會回傳自己的情境管理器範例是 file object。檔案物件從 __enter__() 回傳自己,以允許將 open() 用作 with 陳述式中的情境運算式。

一個會回傳相關物件的情境管理器範例是由 decimal.localcontext() 回傳的管理器。這些管理器將有效的十進位情境設定為原始十進位情境的副本,然後回傳該副本。這允許對 with 陳述式主體中的當前十進位情境進行更改,而不會影響 with 陳述式外部的程式碼。

contextmanager.__exit__(exc_type, exc_val, exc_tb)

退出 runtime 情境並回傳布林旗標以表示是否應抑制曾發生的任何例外。如果在執行 with 陳述式主體時發生例外,則引數包含例外型別、值和回溯 (traceback) 資訊。否則,所有三個引數都是 None

從此方法回傳 true 值將導致 with 陳述式抑制例外並繼續執行緊接著 with 陳述式之後的陳述式。否則,該例外將在該方法執行完畢後繼續傳播 (propagate)。執行此方法期間發生的例外會取代 with 陳述式主體中發生的任何例外。

傳入的例外不應明確重新引發 - 取而代之的是,此方法應回傳 false 值以指示該方法已成功完成且不希望抑制引發的例外。這讓情境管理程式碼能輕鬆檢測 __exit__() 方法是否曾實際失敗過。

Python 定義了多個情境管理器來支援簡單的執行緒同步、檔案或其他物件的提示關閉以及對有效十進位算術情境的更簡單操作。除了情境管理協定的實作之外,不會對特定型別進行特殊處理。更多範例請參閱 contextlib 模組。

Python 的 generatorcontextlib.contextmanager 裝飾器提供了一種便捷的方法來實作這些協定。如果產生器函式以 contextlib.contextmanager 裝飾器裝飾,它將回傳一個有實作出需要的 __enter__()__exit__() 方法的情境管理器,而不是由未裝飾產生器函式產生的疊代器。

請注意,Python/C API 中 Python 物件的型別結構中的任何方法都沒有特定的槽。想要定義這些方法的擴充型別必須將它們作為普通的 Python 可存取方法提供。與設定 runtime 情境的開銷相比,單一類別字典查找的開銷可以忽略不計。

型別註釋的型別 --- 泛型別名 (Generic Alias)聯合 (Union)

型別註釋 的核心內建型別是泛型別名聯合

泛型別名型別

GenericAlias 物件通常是透過下標 (subscripting) 一個類別來建立的。它們最常與容器類別 一起使用,像是 listdict。例如 list[int] 是一個``GenericAlias`` 物件,它是透過使用引數 int 來下標 list 類別而建立的。GenericAlias 物件主要會與型別註釋 一起使用。

備註

通常只有當類別有實作特殊方法 __class_getitem__() 時才可以去下標該類別。

將一個 GenericAlias 物件用作 generic type 的代理,實作參數化泛型 (parameterized generics)

對於一個容器類別,提供給該類別的下標引數可以代表物件所包含元素的型別。例如 set[bytes] 可以用於型別註釋來表示一個 set,其中所有元素的型別都是 bytes

對於定義 __class_getitem__() 但不是容器的類別,提供給該類別的下標引數通常會指示物件上有定義的一個或多個方法的回傳型別。例如正規表示式可以用於 strbytes 資料型別:

  • 如果 x = re.search('foo', 'foo')x 將會是一個 re.Match 物件,其中 x.group(0)x[0] 的回傳值都是 str 型別。我們就可以用 GenericAlias re.Match[str] 在型別註釋中表示這種物件。

  • 如果 y = re.search(b'bar', b'bar')(注意 bytesb), y 也會是 re.Match 的實例,但 y.group(0)y[0] 的回傳值的型別都是 bytes。在型別註釋中,我們將用 re.Match[bytes] 來表示各種 re.Match 物件。

GenericAlias 物件是 types.GenericAlias 類別的實例,也可以用來直接建立 GenericAlias 物件。

T[X, Y, ...]

建立一個 GenericAlias 來表示一個型別 T,其以型別 XY 等(取決於所使用的 T)來參數化。例如,一個函式需要一個包含 float 元素的 list

def average(values: list[float]) -> float:
    return sum(values) / len(values)

對映物件的另一個範例,使用 dict,它是一個泛型型別,需要兩個型別參數,分別表示鍵型別和值型別。在此範例中,函式需要一個 dict,其帶有 str 型別的鍵和 int 型別的值:

def send_post_request(url: str, body: dict[str, int]) -> None:
    ...

內建函式 isinstance()issubclass() 不接受 GenericAlias 型別作為第二個引數:

>>> isinstance([1, 2], list[str])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: isinstance() argument 2 cannot be a parameterized generic

Python runtime 不強制執行型別註釋。這也擴展到泛型型別及其型別參數。當從 GenericAlias 建立容器物件時,不會檢查容器中元素的型別。例如,不鼓勵使用以下程式碼,但 runtime 不會出現錯誤:

>>> t = list[str]
>>> t([1, 2, 3])
[1, 2, 3]

此外,參數化泛型在物件建立期間會擦除 (erase) 型別參數:

>>> t = list[str]
>>> type(t)
<class 'types.GenericAlias'>

>>> l = t()
>>> type(l)
<class 'list'>

在泛型上呼叫 repr()str() 會顯示參數化型別:

>>> repr(list[int])
'list[int]'

>>> str(list[int])
'list[int]'

為防止像是 dict[str][str] 的錯誤出現,泛型容器的 __getitem__() 方法會在這種情況下引發例外:

>>> dict[str][str]
Traceback (most recent call last):
  ...
TypeError: dict[str] is not a generic class

然而當使用型別變數 (type variable) 時,此類運算式是有效的。索引的元素數量必須與 GenericAlias 物件的 __args__ 中的型別變數項目一樣多:

>>> from typing import TypeVar
>>> Y = TypeVar('Y')
>>> dict[str, Y][int]
dict[str, int]

標準泛型類別

以下標準函式庫類別有支援參數化泛型。此列表並非詳盡無遺。

GenericAlias 物件的特殊屬性

所有參數化泛型都有實作特殊的唯讀屬性。

genericalias.__origin__

此屬性指向非參數化泛型類別:

>>> list[int].__origin__
<class 'list'>
genericalias.__args__

此屬性是傳遞給泛型類別之原始 __class_getitem__() 的泛型型別 tuple(長度可以為 1):

>>> dict[str, list[int]].__args__
(<class 'str'>, list[int])
genericalias.__parameters__

此屬性是個會被延遲計算 (lazily computed) 的元組(可能為空),包含了在 __args__ 中找得到的不重複型別變數:

>>> from typing import TypeVar

>>> T = TypeVar('T')
>>> list[T].__parameters__
(~T,)

備註

具有 typing.ParamSpec 參數的一個 GenericAlias 物件在替換後可能沒有正確的 __parameters__,因為 typing.ParamSpec 主要用於靜態型別檢查。

genericalias.__unpacked__

如果別名已使用 * 運算子解包 (unpack) 則為 true 的布林值(請參閱 TypeVarTuple)。

在 3.11 版被加入.

也參考

PEP 484 - 型別提示

引入 Python 的型別註釋框架。

PEP 585 - 標準集合 (Standard Collections) 中的型別提示泛型

引入原生參數化標準函式庫類別的能力,前提是它們有實作特殊的類別方法 __class_getitem__()

泛型使用者定義泛型typing.Generic

有關如何實作可以在 runtime 參數化並能被靜態型別檢查器理解的泛型類別的文件。

在 3.9 版被加入.

聯合型別 (Union Type)

一個聯合物件可以保存多個型別物件 (type object)|(位元 or)運算的值。這些型別主要用於型別註釋 (type annotation)。與 typing.Union 相比,聯合型別運算式可以讓型別提示語法更清晰簡潔。

X | Y | ...

定義一個包含 XY 等型別的聯合物件。X | Y 表示 X 或 Y。它相當於 typing.Union[X, Y]。舉例來說,下列函式需要一個型別為 intfloat 的引數:

def square(number: int | float) -> int | float:
    return number ** 2

備註

不能在 runtime 使用 | 運算元 (operand) 來定義有一個以上的成員為向前參照 (forward reference) 的聯合。例如 int | "Foo",其中 "Foo" 是對未定義類別的參照,將在 runtime 失敗。對於包含向前參照的聯合,請將整個運算式以字串呈現,例如 "int | Foo"

union_object == other

聯合物件可以與其他聯合物件一起進行相等性測試。細節如下:

  • 聯合的聯合會被扁平化:

    (int | str) | float == int | str | float
    
  • 冗餘型別會被刪除:

    int | str | int == int | str
    
  • 比較聯合時,順序會被忽略:

    int | str == str | int
    
  • 它與 typing.Union 相容:

    int | str == typing.Union[int, str]
    
  • 可選型別可以表示為與 None 的聯合:

    str | None == typing.Optional[str]
    
isinstance(obj, union_object)
issubclass(obj, union_object)

聯合物件也支援 isinstance()issubclass() 的呼叫:

>>> isinstance("", int | str)
True

然而聯合物件中的參數化泛型則無法被檢查:

>>> isinstance(1, int | list[int])  # short-circuit evaluation
True
>>> isinstance([1], int | list[int])
Traceback (most recent call last):
  ...
TypeError: isinstance() argument 2 cannot be a parameterized generic

構成聯合物件的對使用者公開型別 (user-exposed type) 可以透過 types.UnionType 存取並用於 isinstance() 檢查。物件不能以型別來實例化:

>>> import types
>>> isinstance(int | str, types.UnionType)
True
>>> types.UnionType()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot create 'types.UnionType' instances

備註

新增了型別物件的 __or__() 方法來支援 X | Y 語法。如果元類別有實作 __or__(),則 Union 可以覆寫 (override) 它:

>>> class M(type):
...     def __or__(self, other):
...         return "Hello"
...
>>> class C(metaclass=M):
...     pass
...
>>> C | int
'Hello'
>>> int | C
int | C

也參考

PEP 604 -- PEP 提出 X | Y 語法和聯合型別。

在 3.10 版被加入.

Other Built-in Types

The interpreter supports several other kinds of objects. Most of these support only one or two operations.

模組

The only special operation on a module is attribute access: m.name, where m is a module and name accesses a name defined in m's symbol table. Module attributes can be assigned to. (Note that the import statement is not, strictly speaking, an operation on a module object; import foo does not require a module object named foo to exist, rather it requires an (external) definition for a module named foo somewhere.)

A special attribute of every module is __dict__. This is the dictionary containing the module's symbol table. Modifying this dictionary will actually change the module's symbol table, but direct assignment to the __dict__ attribute is not possible (you can write m.__dict__['a'] = 1, which defines m.a to be 1, but you can't write m.__dict__ = {}). Modifying __dict__ directly is not recommended.

Modules built into the interpreter are written like this: <module 'sys' (built-in)>. If loaded from a file, they are written as <module 'os' from '/usr/local/lib/pythonX.Y/os.pyc'>.

Classes and Class Instances

See 物件、數值和型別 and 類別定義 for these.

函式

Function objects are created by function definitions. The only operation on a function object is to call it: func(argument-list).

There are really two flavors of function objects: built-in functions and user-defined functions. Both support the same operation (to call the function), but the implementation is different, hence the different object types.

更多資訊請見 函式定義

Methods

Methods are functions that are called using the attribute notation. There are two flavors: built-in methods (such as append() on lists) and class instance method. Built-in methods are described with the types that support them.

If you access a method (a function defined in a class namespace) through an instance, you get a special object: a bound method (also called instance method) object. When called, it will add the self argument to the argument list. Bound methods have two special read-only attributes: m.__self__ is the object on which the method operates, and m.__func__ is the function implementing the method. Calling m(arg-1, arg-2, ..., arg-n) is completely equivalent to calling m.__func__(m.__self__, arg-1, arg-2, ..., arg-n).

Like function objects, bound method objects support getting arbitrary attributes. However, since method attributes are actually stored on the underlying function object (method.__func__), setting method attributes on bound methods is disallowed. Attempting to set an attribute on a method results in an AttributeError being raised. In order to set a method attribute, you need to explicitly set it on the underlying function object:

>>> class C:
...     def method(self):
...         pass
...
>>> c = C()
>>> c.method.whoami = 'my name is method'  # 不得設定於方法
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'method' object has no attribute 'whoami'
>>> c.method.__func__.whoami = 'my name is method'
>>> c.method.whoami
'my name is method'

更多資訊請見 實例方法

程式碼物件

Code objects are used by the implementation to represent "pseudo-compiled" executable Python code such as a function body. They differ from function objects because they don't contain a reference to their global execution environment. Code objects are returned by the built-in compile() function and can be extracted from function objects through their __code__ attribute. See also the code module.

存取 __code__ 會引發一個附帶引數 obj"__code__"稽核事件 object.__getattr__

A code object can be executed or evaluated by passing it (instead of a source string) to the exec() or eval() built-in functions.

更多資訊請見 標準型別階層

Type Objects

Type objects represent the various object types. An object's type is accessed by the built-in function type(). There are no special operations on types. The standard module types defines names for all standard built-in types.

Types are written like this: <class 'int'>.

Null 物件

This object is returned by functions that don't explicitly return a value. It supports no special operations. There is exactly one null object, named None (a built-in name). type(None)() produces the same singleton.

它被寫為 None

The Ellipsis Object

This object is commonly used by slicing (see Slicings). It supports no special operations. There is exactly one ellipsis object, named Ellipsis (a built-in name). type(Ellipsis)() produces the Ellipsis singleton.

它被寫為 Ellipsis...

NotImplemented 物件

This object is returned from comparisons and binary operations when they are asked to operate on types they don't support. See Comparisons for more information. There is exactly one NotImplemented object. type(NotImplemented)() produces the singleton instance.

It is written as NotImplemented.

Internal Objects

See 標準型別階層 for this information. It describes stack frame objects, traceback objects, and slice objects.

特殊屬性

The implementation adds a few special read-only attributes to several object types, where they are relevant. Some of these are not reported by the dir() built-in function.

definition.__name__

The name of the class, function, method, descriptor, or generator instance.

definition.__qualname__

The qualified name of the class, function, method, descriptor, or generator instance.

在 3.3 版被加入.

definition.__module__

The name of the module in which a class or function was defined.

definition.__doc__

The documentation string of a class or function, or None if undefined.

definition.__type_params__

The type parameters of generic classes, functions, and type aliases. For classes and functions that are not generic, this will be an empty tuple.

在 3.12 版被加入.

Integer string conversion length limitation

CPython has a global limit for converting between int and str to mitigate denial of service attacks. This limit only applies to decimal or other non-power-of-two number bases. Hexadecimal, octal, and binary conversions are unlimited. The limit can be configured.

The int type in CPython is an arbitrary length number stored in binary form (commonly known as a "bignum"). There exists no algorithm that can convert a string to a binary integer or a binary integer to a string in linear time, unless the base is a power of 2. Even the best known algorithms for base 10 have sub-quadratic complexity. Converting a large value such as int('1' * 500_000) can take over a second on a fast CPU.

Limiting conversion size offers a practical way to avoid CVE 2020-10735.

The limit is applied to the number of digit characters in the input or output string when a non-linear conversion algorithm would be involved. Underscores and the sign are not counted towards the limit.

When an operation would exceed the limit, a ValueError is raised:

>>> import sys
>>> sys.set_int_max_str_digits(4300)  # Illustrative, this is the default.
>>> _ = int('2' * 5432)
Traceback (most recent call last):
...
ValueError: Exceeds the limit (4300 digits) for integer string conversion: value has 5432 digits; use sys.set_int_max_str_digits() to increase the limit
>>> i = int('2' * 4300)
>>> len(str(i))
4300
>>> i_squared = i*i
>>> len(str(i_squared))
Traceback (most recent call last):
...
ValueError: Exceeds the limit (4300 digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit
>>> len(hex(i_squared))
7144
>>> assert int(hex(i_squared), base=16) == i*i  # Hexadecimal is unlimited.

The default limit is 4300 digits as provided in sys.int_info.default_max_str_digits. The lowest limit that can be configured is 640 digits as provided in sys.int_info.str_digits_check_threshold.

Verification:

>>> import sys
>>> assert sys.int_info.default_max_str_digits == 4300, sys.int_info
>>> assert sys.int_info.str_digits_check_threshold == 640, sys.int_info
>>> msg = int('578966293710682886880994035146873798396722250538762761564'
...           '9252925514383915483333812743580549779436104706260696366600'
...           '571186405732').to_bytes(53, 'big')
...

在 3.11 版被加入.

受影響的 API

The limitation only applies to potentially slow conversions between int and str or bytes:

  • int(string) 以預設的 10 為底。

  • int(string, base) for all bases that are not a power of 2.

  • str(integer)

  • repr(integer)

  • any other string conversion to base 10, for example f"{integer}", "{}".format(integer), or b"%d" % integer.

The limitations do not apply to functions with a linear algorithm:

設定限制

Before Python starts up you can use an environment variable or an interpreter command line flag to configure the limit:

From code, you can inspect the current limit and set a new one using these sys APIs:

Information about the default and minimum can be found in sys.int_info:

在 3.11 版被加入.

警示

Setting a low limit can lead to problems. While rare, code exists that contains integer constants in decimal in their source that exceed the minimum threshold. A consequence of setting the limit is that Python source code containing decimal integer literals longer than the limit will encounter an error during parsing, usually at startup time or import time or even at installation time - anytime an up to date .pyc does not already exist for the code. A workaround for source that contains such large constants is to convert them to 0x hexadecimal form as it has no limit.

Test your application thoroughly if you use a low limit. Ensure your tests run with the limit set early via the environment or flag so that it applies during startup and even during any installation step that may invoke Python to precompile .py sources to .pyc files.