內建型別

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

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

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

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

真值檢測

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

預設情況下,一個物件會被視為真值,除非它的 class 定義了會回傳 False__bool__() method 或是定義了會回傳零的 __len__() method。[1] 如果其中一個 method 在被呼叫時引發例外,該例外將會被傳播,且該物件不具有真值(例如 NotImplemented)。以下列出了大部分會被視為 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 的複數)。你也可以將整數與浮點數相加以得到一個有實部與虛部的複數。

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

Python 完全支援混和運算:當一個二元運算子的運算元有不同內建數值型別時,「較窄」型別的運算元會被拓寬到另一個型別的運算元:

  • If both arguments are complex numbers, no conversion is performed;

  • if either argument is a complex or a floating-point number, the other is converted to a floating-point number;

  • otherwise, both must be integers and no conversion is necessary.

Arithmetic with complex and real operands is defined by the usual mathematical formula, for example:

x + complex(u, v) = complex(x + u, v)
x * complex(u, v) = complex(x * u, x * v)

不同型別的數值之間進行比較時,其行為就像是在比較這些數值的實際值 [2]

所有數值型別(除複數外)皆支援以下的運算(有關運算的先後順序,詳見 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()) 或以上)並至少有一個額外的符號擴展位元,便足以得到與無窮多個符號位元相同的結果。

整數型別的附加方法

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

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 版被加入.

浮點數的附加方法

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

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'

複數的附加方法

complex 型別實作了 numbers.Complex 抽象基底類別complex 也有下列附加方法。

classmethod complex.from_number(x)

將一個數字轉換為複數的類別方法。

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。

目前在具有 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

如果 s 的一個項目等於 x 則為 True,否則為 False

(1)

x not in s

如果 s 的一個項目等於 x 則為 False,否則為 True

(1)

s + t

st 的串接

(6)(7)

s * nn * s

等同於將 s 加到自己 n

(2)(7)

s[i]

s 的第 i 項,起始為 0

(3)(8)

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 中最大的項目

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 如何建立多維度串列?.

  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.

    • 假如 i 被省略或為 None,則使用 0

    • 假如 j 被省略或為 None,則使用 len(s)

    • 假如 ij 小於 -len(s),則使用 0

    • 假如 ij 大於 len(s),則使用 len(s)

    • 假如 i 大於或等於 j,則該切片為空。

  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. An IndexError is raised if i is outside the sequence range.

序列方法

序列型別也支援以下方法:

sequence.count(value, /)

回傳 sequencevalue 出現的總次數。

sequence.index(value[, start[, stop]])

回傳 sequencevalue 首次出現的索引。

value 不在 sequence 中時引發 ValueError

The start or stop arguments allow for efficient searching of subsections of the sequence, beginning at start and ending at stop. This is roughly equivalent to start + sequence[start:stop].index(value), only without copying any data.

警示

Not all sequence types support passing the start and stop arguments.

不可變序列型別

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.

可變序列型別

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

del s[i]

移除 s 中的項目 i

s[i:j] = t

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

del s[i:j]

移除串列中 s[i:j] 的元素(和 s[i:j] = [] 相同)

s[i:j:k] = t

s[i:j:k] 的元素被 t 的元素取代

(1)

del s[i:j:k]

移除串列中 s[i:j:k] 的元素

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

(2)

註解:

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

  2. 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.

可變序列方法

可變序列型別也支援以下方法:

sequence.append(value, /)

value 附加到序列末尾,這和 seq[len(seq):len(seq)] = [value] 相同。

sequence.clear()

在 3.3 版被加入.

移除 sequence 中的所有項目,這和 del sequence[:] 相同。

sequence.copy()

在 3.3 版被加入.

建立 sequence 的淺層複製,這和 sequence[:] 相同。

提示

The copy() method is not part of the MutableSequence ABC, but most concrete mutable sequence types provide it.

sequence.extend(iterable, /)

Extend sequence with the contents of iterable. For the most part, this is the same as writing seq[len(seq):len(seq)] = iterable.

sequence.insert(index, value, /)

Insert value into sequence at the given index. This is equivalent to writing sequence[index:index] = [value].

sequence.pop(index=-1, /)

Retrieve the item at index and also removes it from sequence. By default, the last item in sequence is removed and returned.

sequence.remove(value, /)

Remove the first item from sequence where sequence[i] == value.

value 不在 sequence 中時引發 ValueError

sequence.reverse()

Reverse the items of sequence in place. This method maintains economy of space when reversing a large sequence. To remind users that it operates by side-effect, it returns None.

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]

  • 使用串列綜合運算式:[x for x in iterable]

  • 使用型別建構函式:list()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.

也參考

For detailed information on thread-safety guarantees for list objects, see Thread safety for list objects.

Tuple(元組)

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=(), /)

元組可以以多種方式建構:

  • 使用一對圓括號表示空元組:()

  • 使用末尾的逗號表示單元素元組:a,(a,)

  • 使用逗號分隔項目:a, b, c(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=1, /)

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 and Binary Sequence Type Methods Summary

The following table summarizes the text and binary sequence types methods by category.

分類

str 方法

bytesbytearray 方法

格式化

str.format()

str.format_map()

f-string(f 字串)

printf-style String Formatting

printf-style Bytes Formatting

搜尋和取代

str.find()

str.rfind()

bytes.find()

bytes.rfind()

str.index()

str.rindex()

bytes.index()

bytes.rindex()

str.startswith()

bytes.startswith()

str.endswith()

bytes.endswith()

str.count()

bytes.count()

str.replace()

bytes.replace()

分割和連接

str.split()

str.rsplit()

bytes.split()

bytes.rsplit()

str.splitlines()

bytes.splitlines()

str.partition()

bytes.partition()

str.rpartition()

bytes.rpartition()

str.join()

bytes.join()

字串分類

str.isalpha()

bytes.isalpha()

str.isdecimal()

str.isdigit()

bytes.isdigit()

str.isnumeric()

str.isalnum()

bytes.isalnum()

str.isidentifier()

str.islower()

bytes.islower()

str.isupper()

bytes.isupper()

str.istitle()

bytes.istitle()

str.isspace()

bytes.isspace()

str.isprintable()

大小寫操作

str.lower()

bytes.lower()

str.upper()

bytes.upper()

str.casefold()

str.capitalize()

bytes.capitalize()

str.title()

bytes.title()

str.swapcase()

bytes.swapcase()

填充和去除空白

str.ljust()

str.rjust()

bytes.ljust()

bytes.rjust()

str.center()

bytes.center()

str.expandtabs()

bytes.expandtabs()

str.strip()

bytes.strip()

str.lstrip()

str.rstrip()

bytes.lstrip()

bytes.rstrip()

翻譯和編碼

str.translate()

bytes.translate()

str.maketrans()

bytes.maketrans()

str.encode()

bytes.decode()

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(*, encoding='utf-8', errors='strict')
class str(object)
class str(object, encoding, errors='strict')
class str(object, *, errors)

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 字串方法 section below. To output formatted strings, see the f-string(f 字串) and 格式化文字語法 sections. In addition, see the 文本處理 (Text Processing) 服務 section.

字串方法

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". For example:

>>> 'straße'.lower()
'straße'
>>> 'straße'.casefold()
'strasse'

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). For example:

>>> 'Python'.center(10)
'  Python  '
>>> 'Python'.center(10, '-')
'--Python--'
>>> 'Python'.center(4)
'Python'
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. For example:

>>> 'spam, spam, spam'.count('spam')
3
>>> 'spam, spam, spam'.count('spam', 5)
2
>>> 'spam, spam, spam'.count('spam', 5, 10)
1
>>> 'spam, spam, spam'.count('eggs')
0
>>> 'spam, spam, spam'.count('')
17
str.encode(encoding='utf-8', errors='strict')

Return the string encoded to bytes.

encoding defaults to 'utf-8'; see 標準編碼 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. For example:

>>> encoded_str_to_bytes = 'Python'.encode()
>>> type(encoded_str_to_bytes)
<class 'bytes'>
>>> encoded_str_to_bytes
b'Python'

在 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. Using start and end is equivalent to str[start:end].endswith(suffix). For example:

>>> 'Python'.endswith('on')
True
>>> 'a tuple of suffixes'.endswith(('at', 'in'))
False
>>> 'a tuple of suffixes'.endswith(('at', 'es'))
True
>>> 'Python is amazing'.endswith('is', 0, 9)
True

另請參閱 startswith()removesuffix()

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. For example:

>>> '01\t012\t0123\t01234'.expandtabs()
'01      012     0123    01234'
>>> '01\t012\t0123\t01234'.expandtabs(4)
'01  012 0123    01234'
>>> print('01\t012\n0123\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. For example:

>>> 'spam, spam, spam'.find('sp')
0
>>> 'spam, spam, spam'.find('sp', 5)
6

另請參閱 rfind()index()

備註

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. For example:

>>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'
>>> "The sum of {a} + {b} is {answer}".format(answer=1+2, a=1, b=2)
'The sum of 1 + 2 is 3'
>>> "{1} expects the {0} Inquisition!".format("Spanish", "Nobody")
'Nobody expects the Spanish Inquisition!'

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. For example:

>>> 'spam, spam, spam'.index('spam')
0
>>> 'spam, spam, spam'.index('eggs')
Traceback (most recent call last):
  File "<python-input-0>", line 1, in <module>
    'spam, spam, spam'.index('eggs')
    ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
ValueError: substring not found

另請參閱 rindex()

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(). For example:

>>> 'abc123'.isalnum()
True
>>> 'abc123!@#'.isalnum()
False
>>> ''.isalnum()
False
>>> ' '.isalnum()
False
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. For example:

>>> 'Letters and spaces'.isalpha()
False
>>> 'LettersOnly'.isalpha()
True
>>> 'µ'.isalpha()  # 非 ASCII 字元也可以被視為字母
True

請參閱 Unicode Properties

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. For example:

>>> 'ASCII characters'.isascii()
True
>>> 'µ'.isascii()
False

在 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, such as U+0660, ARABIC-INDIC DIGIT ZERO. Formally a decimal character is a character in the Unicode General Category "Nd". For example:

>>> '0123456789'.isdecimal()
True
>>> '٠١٢٣٤٥٦٧٨٩'.isdecimal()  # 阿拉伯-印度數字零到九
True
>>> 'alphabetic'.isdecimal()
False
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 Names (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. For example:

>>> '0123456789'.isnumeric()
True
>>> '٠١٢٣٤٥٦٧٨٩'.isnumeric()  # 阿拉伯-印度數字零到九
True
>>> '⅕'.isnumeric()  # 普通分數五分之一
True
>>> '²'.isdecimal(), '²'.isdigit(),  '²'.isnumeric()
(False, True, True)

也請參閱 isdecimal()isdigit()。數字字元是十進位數字的超集。

str.isprintable()

Return True if all characters in the string are printable, False if it contains at least one non-printable character.

Here "printable" means the character is suitable for repr() to use in its output; "non-printable" means that repr() on built-in types will hex-escape the character. It has no bearing on the handling of strings written to sys.stdout or sys.stderr.

The printable characters are those which in the Unicode character database (see unicodedata) have a general category in group Letter, Mark, Number, Punctuation, or Symbol (L, M, N, P, or S); plus the ASCII space 0x20. Nonprintable characters are those in group Separator or Other (Z or C), except the ASCII space.

舉例來說:

>>> ''.isprintable(), ' '.isprintable()
(True, True)
>>> '\t'.isprintable(), '\n'.isprintable()
(False, False)

另請參閱 isspace()

str.isspace()

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

舉例來說:

>>> ''.isspace()
False
>>> ' '.isspace()
True
>>> '\t\n'.isspace() # TAB and BREAK LINE
True
>>> '\u3000'.isspace() # IDEOGRAPHIC SPACE
True

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.

另請參閱 isprintable()

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.

舉例來說:

>>> 'Spam, Spam, Spam'.istitle()
True
>>> 'spam, spam, spam'.istitle()
False
>>> 'SPAM, SPAM, SPAM'.istitle()
False

另請參閱 title()

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. For example:

>>> ', '.join(['spam', 'spam', 'spam'])
'spam, spam, spam'
>>> '-'.join('Python')
'P-y-t-h-o-n'

另請參閱 split()

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).

舉例來說:

>>> 'Python'.ljust(10)
'Python    '
>>> 'Python'.ljust(10, '.')
'Python....'
>>> 'Monty Python'.ljust(10, '.')
'Monty Python'

另請參閱 rjust()

str.lower()

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

>>> 'Lower Method Example'.lower()
'lower method example'

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

str.lstrip(chars=None, /)

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(dict, /)
static str.maketrans(from, to, remove='', /)

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 from will be mapped to the character at the same position in to. 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.

舉例來說:

>>> 'Monty Python'.partition(' ')
('Monty', ' ', 'Python')
>>> "Monty Python's Flying Circus".partition(' ')
('Monty', ' ', "Python's Flying Circus")
>>> 'Monty Python'.partition('-')
('Monty Python', '', '')

另請參閱 rpartition()

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 版被加入.

另請參閱 removesuffix()startswith()

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 版被加入.

另請參閱 removeprefix()endswith()

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. For example:

>>> 'spam, spam, spam'.replace('spam', 'eggs')
'eggs, eggs, eggs'
>>> 'spam, spam, spam'.replace('spam', 'eggs', 1)
'eggs, spam, spam'

在 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. For example:

>>> 'spam, spam, spam'.rfind('sp')
12
>>> 'spam, spam, spam'.rfind('sp', 0, 10)
6

另請參閱 find()rindex()

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

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

>>> 'spam, spam, spam'.rindex('spam')
12
>>> 'spam, spam, spam'.rindex('eggs')
Traceback (most recent call last):
  File "<stdin-0>", line 1, in <module>
    'spam, spam, spam'.rindex('eggs')
    ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
ValueError: substring not found

另請參閱 index()find()

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).

舉例來說:

>>> 'Python'.rjust(10)
'    Python'
>>> 'Python'.rjust(10, '.')
'....Python'
>>> 'Monty Python'.rjust(10, '.')
'Monty Python'

另請參閱 ljust()zfill()

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.

舉例來說:

>>> 'Monty Python'.rpartition(' ')
('Monty', ' ', 'Python')
>>> "Monty Python's Flying Circus".rpartition(' ')
("Monty Python's Flying", ' ', 'Circus')
>>> 'Monty Python'.rpartition('-')
('', '', 'Monty Python')

另請參閱 partition()

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=None, /)

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. For example:

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

See 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'

另請參閱 strip()

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']

If sep is not specified or is None and maxsplit is 0, only leading runs of consecutive whitespace are considered.

舉例來說:

>>> "".split(None, 0)
[]
>>> "   ".split(None, 0)
[]
>>> "   foo   ".split(maxsplit=0)
['foo   ']

另請參閱 join()

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(