Kiểu dữ liệu nào là kiểu trong Python?

Các kiểu dữ liệu là sự phân loại các mục dữ liệu. Các kiểu dữ liệu đại diện cho một loại giá trị xác định những gì có thể được thực hiện đối với dữ liệu đó


Các loại dữ liệu khác nhau trong Python là gì?

Kiểu dữ liệuVí dụGiải thíchCó thể thay đổi/Không thể thay đổi?Chuỗi"Xin chào. ", "23. 34"Văn bản - bất cứ thứ gì giữa
" "  trở thành chuỗiImmutableIntegers5364Số nguyênImmutableFloats3. 1415Số thập phânImmutableBooleansCác giá trịTrue, FalseTruth đại diện cho Yes/NoImmutableLists[1,2,3,4,5]Một tập hợp dữ liệu,
nằm giữa  [ ]  MutableTuples[1,2,3,4,5]Tập hợp dữ liệu,
nằm giữa [ ]  ImmutableDictionaries{"a". 1, "b". 2, "c". 3}Tập hợp dữ liệu,
nằm giữa  { }  Có thể thay đổi

Một số lớp bộ sưu tập có thể thay đổi. Các phương thức cộng, trừ hoặc sắp xếp lại các thành viên của chúng tại chỗ và không trả về một mục cụ thể, không bao giờ trả về chính thể hiện của bộ sưu tập nhưng

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
31

Một số hoạt động được hỗ trợ bởi một số loại đối tượng; . Hàm thứ hai được sử dụng ngầm khi một đối tượng được viết bởi hàm

Kiểm tra giá trị thật

Bất kỳ đối tượng nào cũng có thể được kiểm tra giá trị thực, để sử dụng trong một hoặc điều kiện hoặc dưới dạng toán hạng của các phép toán Boolean bên dưới

Theo mặc định, một đối tượng được coi là đúng trừ khi lớp của nó định nghĩa một phương thức

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
37 trả về
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
38 hoặc một phương thức
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
39 trả về 0 khi được gọi với đối tượng. Dưới đây là hầu hết các đối tượng tích hợp được coi là sai

  • hằng số được xác định là sai.

    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
    
    31 và
    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
    
    38

  • số không của bất kỳ loại số nào.

    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
    
    42,
    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
    
    43,
    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
    
    44,
    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
    
    45,
    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
    
    46

  • trình tự và bộ sưu tập trống.

    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
    
    47,
    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
    
    48,
    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
    
    49,
    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
    
    50,
    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
    
    51,
    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
    
    52

Các phép toán và hàm dựng sẵn có kết quả Boolean luôn trả về

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
42 hoặc
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
38 nếu sai và
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
55 hoặc
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
56 nếu đúng, trừ khi có quy định khác. [Ngoại lệ quan trọng. các phép toán Boolean
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
57 và
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
58 luôn trả về một trong các toán hạng của chúng. ]

Phép toán Boolean —
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
58,
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
57,
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
61

Đây là các phép toán Boolean, được sắp xếp theo mức độ ưu tiên tăng dần

Hoạt động

Kết quả

ghi chú

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
62

nếu x sai, thì y, ngược lại x

[1]

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
63

nếu x sai, thì x, ngược lại y

[2]

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
64

nếu x sai, thì

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
56, ngược lại thì
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
38

[3]

ghi chú

  1. Đây là toán tử ngắn mạch, vì vậy nó chỉ đánh giá đối số thứ hai nếu đối số thứ nhất sai

  2. Đây là toán tử ngắn mạch, vì vậy nó chỉ đánh giá đối số thứ hai nếu đối số thứ nhất đúng

  3. 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
    
    61 có mức ưu tiên thấp hơn so với các toán tử không phải Boolean, vì vậy
    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
    
    68 được hiểu là
    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
    
    69 và
    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
    
    70 là một lỗi cú pháp

so sánh

Có tám thao tác so sánh trong Python. Tất cả chúng đều có cùng mức độ ưu tiên [cao hơn so với các phép toán Boolean]. So sánh có thể được xâu chuỗi tùy ý;

Bảng này tóm tắt các hoạt động so sánh

Hoạt động

Nghĩa

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
74

strictly less than

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
75

nhỏ hơn hoặc bằng

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
76

tuyệt đối lớn hơn

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
77

lớn hơn hoặc bằng

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
78

công bằng

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
79

không công bằng

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
80

nhận dạng đối tượng

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
81

danh tính đối tượng phủ định

Các đối tượng thuộc các loại khác nhau, ngoại trừ các loại số khác nhau, không bao giờ so sánh bằng nhau. Toán tử

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
78 luôn được xác định nhưng đối với một số loại đối tượng [ví dụ: đối tượng lớp] tương đương với. Các toán tử
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
74,
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
75,
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
76 và
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
77 chỉ được xác định khi chúng có ý nghĩa;

Các thể hiện không giống nhau của một lớp thường được so sánh là không bằng nhau trừ khi lớp đó định nghĩa phương thức

Các thể hiện của một lớp không thể được sắp xếp đối với các thể hiện khác của cùng một lớp hoặc các loại đối tượng khác, trừ khi lớp đó định nghĩa đủ các phương thức , , , và [nói chung là đủ, nếu bạn muốn ý nghĩa quy ước của

Không thể tùy chỉnh hành vi của toán tử và;

Hai thao tác nữa có cùng mức ưu tiên cú pháp và , được hỗ trợ bởi các loại hoặc triển khai phương thức

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
00

Các loại số — , ,

Có ba loại số riêng biệt. số nguyên, số dấu phẩy động và số phức. Ngoài ra, Booleans là một kiểu con của số nguyên. Số nguyên có độ chính xác không giới hạn. Số dấu phẩy động thường được triển khai bằng cách sử dụng double trong C; . Số phức có phần thực và phần ảo, mỗi phần là một số dấu phẩy động. Để trích xuất các phần này từ một số phức z, hãy sử dụng

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
05 và
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
06. [The standard library includes the additional numeric types , for rationals, and , for floating-point numbers with user-definable precision. ]

Các số được tạo bởi các chữ số hoặc là kết quả của các hàm và toán tử tích hợp. Unadorned integer literals [including hex, octal and binary numbers] yield integers. Chữ số có chứa dấu thập phân hoặc dấu mũ mang lại số dấu phẩy động. Việc thêm

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
09 hoặc
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
10 vào một chữ số sẽ tạo ra một số ảo [một số phức có phần thực bằng 0] mà bạn có thể thêm vào một số nguyên hoặc dấu phẩy động để nhận được một số phức có phần thực và phần ảo

Python fully supports mixed arithmetic. khi một toán tử số học nhị phân có các toán hạng thuộc các kiểu số khác nhau, thì toán hạng có loại "hẹp hơn" được mở rộng sang toán hạng kia, trong đó số nguyên hẹp hơn dấu phẩy động, hẹp hơn phức hợp. So sánh giữa các số thuộc các loại khác nhau hoạt động như thể các giá trị chính xác của các số đó đang được so sánh.

Các hàm tạo , , và có thể được sử dụng để tạo các số thuộc một loại cụ thể

Tất cả các loại số [ngoại trừ phức tạp] đều hỗ trợ các thao tác sau [để biết mức độ ưu tiên của các thao tác, xem phần ]

Hoạt động

Kết quả

ghi chú

tài liệu đầy đủ

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
14

tổng của x và y

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
15

sự khác biệt của x và y

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
16

sản phẩm của x và y

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
17

thương của x và y

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
18

thương số sàn của x và y

[1]

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
19

phần còn lại của

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
17

[2]

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
21

x phủ định

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
22

x không thay đổi

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
23

giá trị tuyệt đối hoặc độ lớn của x

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
25

x chuyển thành số nguyên

[3][6]

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
27

x được chuyển đổi thành dấu phẩy động

[4][6]

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
29

số phức có phần thực là phần ảo. tôi mặc định là không

[6]

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
31

liên hợp của số phức c

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
32

cặp

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
33

[2]

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
35

x lũy thừa y

[5]

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
37

x lũy thừa y

[5]

ghi chú

  1. Còn gọi là phép chia số nguyên. Giá trị kết quả là một số nguyên, mặc dù loại kết quả không nhất thiết phải là int. Kết quả luôn được làm tròn về phía âm vô cực.

    >>> n = 19
    >>> bin[n]
    '0b10011'
    >>> n.bit_count[]
    3
    >>> [-n].bit_count[]
    3
    
    38 là _______0_______42, _______51_______40 là _______51_______41, _______51_______42 là _______51_______41, và _______51_______44 là _________42

  2. Không dành cho số phức. Thay vào đó, hãy chuyển đổi thành float bằng cách sử dụng nếu thích hợp

  3. Chuyển đổi từ dấu phẩy động sang số nguyên có thể làm tròn hoặc cắt ngắn như trong C;

  4. float cũng chấp nhận các chuỗi “nan” và “inf” với tiền tố tùy chọn “+” hoặc “-” cho Không phải là Số [NaN] và vô cực dương hoặc âm

  5. Python định nghĩa

    >>> n = 19
    >>> bin[n]
    '0b10011'
    >>> n.bit_count[]
    3
    >>> [-n].bit_count[]
    3
    
    49 và
    >>> n = 19
    >>> bin[n]
    '0b10011'
    >>> n.bit_count[]
    3
    >>> [-n].bit_count[]
    3
    
    50 là
    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
    
    55, như thường thấy đối với các ngôn ngữ lập trình

  6. Các chữ số được chấp nhận bao gồm các chữ số

    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
    
    42 đến
    >>> n = 19
    >>> bin[n]
    '0b10011'
    >>> n.bit_count[]
    3
    >>> [-n].bit_count[]
    3
    
    53 hoặc bất kỳ mã Unicode tương đương nào [điểm mã với thuộc tính
    >>> n = 19
    >>> bin[n]
    '0b10011'
    >>> n.bit_count[]
    3
    >>> [-n].bit_count[]
    3
    
    54]

    Xem https. //www. unicode. tổ chức/Công khai/14. 0. 0/ucd/extracted/DerivedNumericType. txt để biết danh sách đầy đủ các điểm mã với thuộc tính

    >>> n = 19
    >>> bin[n]
    '0b10011'
    >>> n.bit_count[]
    3
    >>> [-n].bit_count[]
    3
    
    54

Tất cả các loại [ và ] cũng bao gồm các thao tác sau

Hoạt động

Kết quả

x cắt ngắn thành

x làm tròn đến n chữ số, làm tròn một nửa thành chẵn. Nếu n bị bỏ qua, nó mặc định là 0

lớn nhất = x

Đối với các hoạt động số bổ sung, hãy xem và mô-đun

Hoạt động Bitwise trên các loại số nguyên

Hoạt động bitwise chỉ có ý nghĩa đối với số nguyên. Kết quả của các hoạt động theo bit được tính toán như thể được thực hiện trong phần bù hai với số lượng bit dấu vô hạn

Tất cả các ưu tiên của các phép toán bitwise nhị phân đều thấp hơn các phép toán số và cao hơn các phép so sánh;

Bảng này liệt kê các hoạt động bitwise được sắp xếp theo mức độ ưu tiên tăng dần

Hoạt động

Kết quả

ghi chú

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
71

bitwise hoặc của x và y

[4]

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
72

loại trừ theo bit hoặc của x và y

[4]

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
73

bitwise và của x và y

[4]

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
74

x dịch sang trái n bit

[1][2]

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
75

x shifted right by n bits

[1][3]

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
76

các bit của x đảo ngược

ghi chú

  1. Số lần thay đổi âm là bất hợp pháp và gây ra một sự gia tăng

  2. Dịch trái n bit tương đương với phép nhân với

    >>> n = 19
    >>> bin[n]
    '0b10011'
    >>> n.bit_count[]
    3
    >>> [-n].bit_count[]
    3
    
    78

  3. Dịch chuyển sang phải n bit tương đương với phép chia sàn cho

    >>> n = 19
    >>> bin[n]
    '0b10011'
    >>> n.bit_count[]
    3
    >>> [-n].bit_count[]
    3
    
    78

  4. Thực hiện các tính toán này với ít nhất một bit mở rộng dấu phụ trong biểu diễn phần bù của hai hữu hạn [độ rộng bit làm việc là

    >>> n = 19
    >>> bin[n]
    '0b10011'
    >>> n.bit_count[]
    3
    >>> [-n].bit_count[]
    3
    
    80 trở lên] là đủ để có được kết quả tương tự như thể có vô số bit dấu

Các phương thức bổ sung trên các kiểu số nguyên

Kiểu int thực hiện. Ngoài ra nó còn cung cấp thêm một số phương pháp

int. bit_length[]

Trả về số bit cần thiết để biểu diễn một số nguyên ở dạng nhị phân, không bao gồm dấu và các số 0 ở đầu

>>> n = -37
>>> bin[n]
'-0b100101'
>>> n.bit_length[]
6

Chính xác hơn, nếu

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
82 khác không, thì
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
83 là số nguyên dương duy nhất
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
84 sao cho
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
85. Tương tự, khi
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
23 đủ nhỏ để có logarit được làm tròn chính xác, thì
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
87. Nếu
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
82 bằng 0, thì
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
83 trả về
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
42

Tương đương với

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

Mới trong phiên bản 3. 1

int. bit_count[]

Trả về số đơn vị trong biểu diễn nhị phân của giá trị tuyệt đối của số nguyên. Đây còn được gọi là số lượng dân số. Thí dụ

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3

Tương đương với

def bit_count[self]:
    return bin[self].count["1"]

Mới trong phiên bản 3. 10

int. to_byte[độ dài=1, byteorder='big', *, signed=False]

Trả về một mảng byte đại diện cho một số nguyên

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

Số nguyên được biểu diễn bằng byte độ dài và mặc định là 1. An được nâng lên nếu số nguyên không thể biểu thị được với số byte đã cho

Đối số byteorder xác định thứ tự byte được sử dụng để biểu thị số nguyên và mặc định là

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
92. Nếu thứ tự byte là
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
92, thì byte quan trọng nhất nằm ở đầu mảng byte. Nếu byteorder là
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
94, thì byte quan trọng nhất nằm ở cuối mảng byte

Đối số đã ký xác định xem phần bù của hai có được sử dụng để biểu diễn số nguyên hay không. Nếu được ký là

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
38 và một số nguyên âm được đưa ra, thì an được nâng lên. Giá trị mặc định cho đã ký là
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
38

Các giá trị mặc định có thể được sử dụng để biến một số nguyên thành một đối tượng byte đơn một cách thuận tiện. Tuy nhiên, khi sử dụng các đối số mặc định, đừng cố chuyển đổi một giá trị lớn hơn 255, nếu không bạn sẽ nhận được một

>>> [65].to_bytes[]
b'A'

Tương đương với

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]

Mới trong phiên bản 3. 2

Đã thay đổi trong phiên bản 3. 11. Đã thêm các giá trị đối số mặc định cho

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
99 và
def bit_count[self]:
    return bin[self].count["1"]
00.

phương thức lớp int. từ_byte[byte , thứ tự byte='big', *, signed=False]

Trả về số nguyên được đại diện bởi mảng byte đã cho

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

Các byte đối số phải là một hoặc một byte tạo ra có thể lặp lại

Đối số byteorder xác định thứ tự byte được sử dụng để biểu thị số nguyên và mặc định là

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
92. Nếu thứ tự byte là
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
92, thì byte quan trọng nhất nằm ở đầu mảng byte. If byteorder is
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
94, the most significant byte is at the end of the byte array. Để yêu cầu thứ tự byte gốc của hệ thống máy chủ, hãy sử dụng làm giá trị thứ tự byte

Đối số có dấu cho biết liệu phần bù hai có được sử dụng để biểu diễn số nguyên hay không

Tương đương với

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  6
56 nếu đối tượng float là hữu hạn với giá trị nguyên và ngược lại là
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
38

>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False

Hai phương pháp hỗ trợ chuyển đổi sang và từ các chuỗi thập lục phân. Vì số float của Python được lưu trữ bên trong dưới dạng số nhị phân, nên việc chuyển đổi số float thành hoặc từ chuỗi thập phân thường liên quan đến một lỗi làm tròn nhỏ. Ngược lại, các chuỗi thập lục phân cho phép biểu diễn và đặc tả chính xác các số dấu phẩy động. Điều này có thể hữu ích khi gỡ lỗi và trong công việc số

nổi. hex[]

Trả về biểu diễn của số dấu phẩy động dưới dạng chuỗi thập lục phân. Đối với các số có dấu phẩy động hữu hạn, biểu diễn này sẽ luôn bao gồm một số ở đầu

def bit_count[self]:
    return bin[self].count["1"]
12 và một số sau ____113_______13 và số mũ

phương thức lớp phao. từ hex[s]

Phương thức lớp để trả về số float được biểu thị bằng chuỗi thập lục phân s. Chuỗi s có thể có khoảng trắng ở đầu và cuối

Lưu ý rằng đó là một phương thức cá thể, trong khi đó là một phương thức lớp

A hexadecimal string takes the form

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
0

trong đó tùy chọn

def bit_count[self]:
    return bin[self].count["1"]
16 có thể bằng cách hoặc là
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
69 hoặc là
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
70,
def bit_count[self]:
    return bin[self].count["1"]
19 và
def bit_count[self]:
    return bin[self].count["1"]
20 là các chuỗi chữ số thập lục phân và
def bit_count[self]:
    return bin[self].count["1"]
21 là số nguyên thập phân có dấu ở đầu tùy chọn. Trường hợp không đáng kể và phải có ít nhất một chữ số thập lục phân trong số nguyên hoặc phân số. Cú pháp này tương tự như cú pháp quy định tại mục 6. 4. 4. 2 của tiêu chuẩn C99 và cả cú pháp được sử dụng trong Java 1. 5 onwards. Cụ thể, đầu ra của có thể được sử dụng dưới dạng ký tự dấu phẩy động thập lục phân trong mã C hoặc Java và các chuỗi thập lục phân được tạo bởi ký tự định dạng
def bit_count[self]:
    return bin[self].count["1"]
23 của C hoặc
def bit_count[self]:
    return bin[self].count["1"]
24 của Java được chấp nhận bởi

Lưu ý rằng số mũ được viết dưới dạng thập phân chứ không phải thập lục phân và nó mang lại sức mạnh của 2 để nhân hệ số. Ví dụ: chuỗi thập lục phân

def bit_count[self]:
    return bin[self].count["1"]
26 đại diện cho số dấu phẩy động
def bit_count[self]:
    return bin[self].count["1"]
27 hoặc
def bit_count[self]:
    return bin[self].count["1"]
28

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
1

Applying the reverse conversion to

def bit_count[self]:
    return bin[self].count["1"]
28 gives a different hexadecimal string representing the same number

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
2

Hashing of numeric types

For numbers

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
82 and
def bit_count[self]:
    return bin[self].count["1"]
31, possibly of different types, it’s a requirement that
def bit_count[self]:
    return bin[self].count["1"]
32 whenever
def bit_count[self]:
    return bin[self].count["1"]
33 [see the method documentation for more details]. For ease of implementation and efficiency across a variety of numeric types [including , , and ] Python’s hash for numeric types is based on a single mathematical function that’s defined for any rational number, and hence applies to all instances of and , and all finite instances of and . Essentially, this function is given by reduction modulo
def bit_count[self]:
    return bin[self].count["1"]
43 for a fixed prime
def bit_count[self]:
    return bin[self].count["1"]
43. The value of
def bit_count[self]:
    return bin[self].count["1"]
43 is made available to Python as the
def bit_count[self]:
    return bin[self].count["1"]
46 attribute of

CPython implementation detail. Currently, the prime used is

def bit_count[self]:
    return bin[self].count["1"]
48 on machines with 32-bit C longs and
def bit_count[self]:
    return bin[self].count["1"]
49 on machines with 64-bit C longs

Here are the rules in detail

  • If

    def bit_count[self]:
        return bin[self].count["1"]
    
    50 is a nonnegative rational number and
    def bit_count[self]:
        return bin[self].count["1"]
    
    51 is not divisible by
    def bit_count[self]:
        return bin[self].count["1"]
    
    43, define
    def bit_count[self]:
        return bin[self].count["1"]
    
    53 as
    def bit_count[self]:
        return bin[self].count["1"]
    
    54, where
    def bit_count[self]:
        return bin[self].count["1"]
    
    55 gives the inverse of
    def bit_count[self]:
        return bin[self].count["1"]
    
    51 modulo
    def bit_count[self]:
        return bin[self].count["1"]
    
    43

  • If

    def bit_count[self]:
        return bin[self].count["1"]
    
    50 is a nonnegative rational number and
    def bit_count[self]:
        return bin[self].count["1"]
    
    51 is divisible by
    def bit_count[self]:
        return bin[self].count["1"]
    
    43 [but
    def bit_count[self]:
        return bin[self].count["1"]
    
    61 is not] then
    def bit_count[self]:
        return bin[self].count["1"]
    
    51 has no inverse modulo
    def bit_count[self]:
        return bin[self].count["1"]
    
    43 and the rule above doesn’t apply; in this case define
    def bit_count[self]:
        return bin[self].count["1"]
    
    53 to be the constant value
    def bit_count[self]:
        return bin[self].count["1"]
    
    65

  • If

    def bit_count[self]:
        return bin[self].count["1"]
    
    50 is a negative rational number define
    def bit_count[self]:
        return bin[self].count["1"]
    
    53 as
    def bit_count[self]:
        return bin[self].count["1"]
    
    68. If the resulting hash is
    >>> n = 19
    >>> bin[n]
    '0b10011'
    >>> n.bit_count[]
    3
    >>> [-n].bit_count[]
    3
    
    41, replace it with
    def bit_count[self]:
        return bin[self].count["1"]
    
    70

  • The particular values

    def bit_count[self]:
        return bin[self].count["1"]
    
    65 and
    def bit_count[self]:
        return bin[self].count["1"]
    
    72 are used as hash values for positive infinity or negative infinity [respectively]

  • For a number

    def bit_count[self]:
        return bin[self].count["1"]
    
    74, the hash values of the real and imaginary parts are combined by computing
    def bit_count[self]:
        return bin[self].count["1"]
    
    75, reduced modulo
    def bit_count[self]:
        return bin[self].count["1"]
    
    76 so that it lies in
    def bit_count[self]:
        return bin[self].count["1"]
    
    77. Again, if the result is
    >>> n = 19
    >>> bin[n]
    '0b10011'
    >>> n.bit_count[]
    3
    >>> [-n].bit_count[]
    3
    
    41, it’s replaced with
    def bit_count[self]:
        return bin[self].count["1"]
    
    70

To clarify the above rules, here’s some example Python code, equivalent to the built-in hash, for computing the hash of a rational number, , or

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

Iterator Types

Python supports a concept of iteration over containers. This is implemented using two distinct methods; these are used to allow user-defined classes to support iteration. Sequences, described below in more detail, always support the iteration methods

One method needs to be defined for container objects to provide support

container. __iter__[]

Return an object. The object is required to support the iterator protocol described below. If a container supports different types of iteration, additional methods can be provided to specifically request iterators for those iteration types. [An example of an object supporting multiple forms of iteration would be a tree structure which supports both breadth-first and depth-first traversal. ] This method corresponds to the slot of the type structure for Python objects in the Python/C API

The iterator objects themselves are required to support the following two methods, which together form the iterator protocol

iterator. __iter__[]

Return the object itself. This is required to allow both containers and iterators to be used with the and statements. This method corresponds to the slot of the type structure for Python objects in the Python/C API

iterator. __next__[]

Return the next item from the . If there are no further items, raise the exception. This method corresponds to the slot of the type structure for Python objects in the Python/C API

Python defines several iterator objects to support iteration over general and specific sequence types, dictionaries, and other more specialized forms. The specific types are not important beyond their implementation of the iterator protocol

Once an iterator’s method raises , it must continue to do so on subsequent calls. Implementations that do not obey this property are deemed broken

Generator Types

Python’s s provide a convenient way to implement the iterator protocol. If a container object’s

def bit_count[self]:
    return bin[self].count["1"]
90 method is implemented as a generator, it will automatically return an iterator object [technically, a generator object] supplying the
def bit_count[self]:
    return bin[self].count["1"]
90 and methods. More information about generators can be found in

Sequence Types — , ,

There are three basic sequence types. lists, tuples, and range objects. Additional sequence types tailored for processing of and 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 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

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
98 and
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
99 operations have the same priorities as the comparison operations. The
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
69 [concatenation] and
>>> [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'
00 [repetition] operations have the same priority as the corresponding numeric operations.

Hoạt động

Kết quả

ghi chú

>>> [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'
01

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
56 if an item of s is equal to x, else
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
38

[1]

>>> [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'
04

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
38 if an item of s is equal to x, else
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
56

[1]

>>> [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'
07

the concatenation of s and t

[6][7]

>>> [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'
08 or
>>> [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'
09

equivalent to adding s to itself n times

[2][7]

>>> [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'
10

ith item of s, origin 0

[3]

>>> [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'
11

slice of s from i to j

[3][4]

>>> [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'
12

lát s từ i đến j với bước k

[3][5]

>>> [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'
13

chiều dài của s

>>> [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'
14

mục nhỏ nhất của s

>>> [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'
15

mục lớn nhất của s

>>> [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'
16

chỉ số của lần xuất hiện đầu tiên của x trong s [tại hoặc sau chỉ số i và trước chỉ số j]

[số 8]

>>> [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'
17

tổng số lần xuất hiện của x trong s

Các chuỗi cùng loại cũng hỗ trợ so sánh. Cụ thể, các bộ dữ liệu và danh sách được so sánh theo từ điển bằng cách so sánh các phần tử tương ứng. Điều này có nghĩa là để so sánh bằng nhau, mọi phần tử phải so sánh bằng nhau và hai dãy phải cùng loại và có cùng độ dài. [Để biết đầy đủ chi tiết xem trong tài liệu tham khảo ngôn ngữ. ]

Các trình vòng lặp chuyển tiếp và đảo ngược qua các chuỗi có thể thay đổi truy cập các giá trị bằng chỉ mục. Chỉ số đó sẽ tiếp tục tiến [hoặc lùi] ngay cả khi trình tự cơ bản bị đột biến. Trình vòng lặp chỉ kết thúc khi gặp an hoặc a [hoặc khi chỉ số giảm xuống dưới 0]

ghi chú

  1. Trong khi các hoạt động

    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
    
    98 và
    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
    
    99 chỉ được sử dụng cho thử nghiệm ngăn chặn đơn giản trong trường hợp chung, một số trình tự chuyên biệt [chẳng hạn như , và ] cũng sử dụng chúng cho thử nghiệm trình tự tiếp theo

    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
    
    4

  2. Các giá trị của n nhỏ hơn

    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
    
    42 được coi là
    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
    
    42 [tạo ra một chuỗi trống cùng loại với s]. Lưu ý rằng các mục trong chuỗi s không được sao chép; . Điều này thường ám ảnh các lập trình viên Python mới;

    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
    
    5

    Điều đã xảy ra là

    >>> [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'
    
    27 là danh sách một phần tử chứa danh sách trống, vì vậy cả ba phần tử của
    >>> [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'
    
    28 đều là tham chiếu đến danh sách trống duy nhất này. Sửa đổi bất kỳ thành phần nào của
    >>> [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'
    
    29 sẽ sửa đổi danh sách đơn này. Bạn có thể tạo một danh sách các danh sách khác nhau theo cách này

    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
    
    6

    Giải thích thêm có sẵn trong mục Câu hỏi thường gặp

  3. If i or j is negative, the index is relative to the end of sequence s.

    >>> [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'
    
    30 or
    >>> [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'
    
    31 is substituted. But note that
    >>> [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'
    
    32 is still
    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
    
    42

  4. The slice of s from i to j is defined as the sequence of items with index k such that

    >>> [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'
    
    34. If i or j is greater than
    >>> [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'
    
    13, use
    >>> [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'
    
    13. If i is omitted or
    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
    
    31, use
    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
    
    42. If j is omitted or
    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
    
    31, use
    >>> [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'
    
    13. 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

    >>> [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'
    
    41 such that
    >>> [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'
    
    42. In other words, the indices are
    >>> [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'
    
    43,
    >>> [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'
    
    44,
    >>> [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'
    
    45,
    >>> [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'
    
    46 and so on, stopping when j is reached [but never including j]. When k is positive, i and j are reduced to
    >>> [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'
    
    13 if they are greater. When k is negative, i and j are reduced to
    >>> [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'
    
    48 if they are greater. If i or j are omitted or
    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
    
    31, they become “end” values [which end depends on the sign of k]. Note, k cannot be zero. If k is
    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
    
    31, it is treated like
    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
    
    55

  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 objects, you can build a list and use at the end or else write to an instance and retrieve its value when complete

    • if concatenating objects, you can similarly use or , or you can do in-place concatenation with a object. objects are mutable and have an efficient overallocation mechanism

    • if concatenating objects, extend a instead

    • for other types, investigate the relevant class documentation

  7. Some sequence types [such as ] only support item sequences that follow specific patterns, and hence don’t support sequence concatenation or repetition

  8. >>> [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'
    
    63 raises 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
    >>> [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'
    
    65, 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 built-in

This support allows immutable sequences, such as instances, to be used as keys and stored in and instances

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

Mutable Sequence Types

The operations in the following table are defined on mutable sequence types. The 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, only accepts integers that meet the value restriction

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

Hoạt động

Kết quả

ghi chú

>>> [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'
75

item i of s is replaced by x

>>> [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'
76

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

>>> [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'
77

same as

>>> [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'
78

>>> [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'
79

the elements of

>>> [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'
12 are replaced by those of t

[1]

>>> [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'
81

removes the elements of

>>> [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'
12 from the list

>>> [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'
83

appends x to the end of the sequence [same as

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

>>> [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'
85

removes all items from s [same as

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

[5]

>>> [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'
87

creates a shallow copy of s [same as

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

[5]

>>> [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'
89 or
>>> [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'
90

extends s with the contents of t [for the most part the same as

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

>>> [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'
92

updates s with its contents repeated n times

[6]

>>> [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'
93

inserts x into s at the index given by i [same as

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

>>> [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'
95 or
>>> [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'
96

retrieves the item at i and also removes it from s

[2]

>>> [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'
97

remove the first item from s where

>>> [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'
10 is equal to x

[3]

>>> [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'
99

reverses the items of s in place

[4]

ghi chú

  1. t must have the same length as the slice it is replacing

  2. The optional argument i defaults to

    >>> n = 19
    >>> bin[n]
    '0b10011'
    >>> n.bit_count[]
    3
    >>> [-n].bit_count[]
    3
    
    41, so that by default the last item is removed and returned

  3. >>> [65].to_bytes[]
    b'A'
    
    01 raises when x is not found in s

  4. The

    >>> [65].to_bytes[]
    b'A'
    
    03 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. >>> [65].to_bytes[]
    b'A'
    
    04 and
    >>> [65].to_bytes[]
    b'A'
    
    05 are included for consistency with the interfaces of mutable containers that don’t support slicing operations [such as and ].
    >>> [65].to_bytes[]
    b'A'
    
    05 is not part of the ABC, but most concrete mutable sequence classes provide it

    Mới trong phiên bản 3. 3.

    >>> [65].to_bytes[]
    b'A'
    
    04 and
    >>> [65].to_bytes[]
    b'A'
    
    05 methods.

  6. The value n is an integer, or an object implementing . Zero and negative values of n clear the sequence. Items in the sequence are not copied; they are referenced multiple times, as explained for

    >>> [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'
    
    08 under

Lists

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.

    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
    
    49

  • Using square brackets, separating items with commas.

    >>> [65].to_bytes[]
    b'A'
    
    15,
    >>> [65].to_bytes[]
    b'A'
    
    16

  • Using a list comprehension.

    >>> [65].to_bytes[]
    b'A'
    
    17

  • Using the type constructor.

    >>> [65].to_bytes[]
    b'A'
    
    18 or
    >>> [65].to_bytes[]
    b'A'
    
    19

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

>>> [65].to_bytes[]
b'A'
20. For example,
>>> [65].to_bytes[]
b'A'
21 returns
>>> [65].to_bytes[]
b'A'
22 and
>>> [65].to_bytes[]
b'A'
23 returns
>>> [65].to_bytes[]
b'A'
24. If no argument is given, the constructor creates a new empty list,
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
49

Many other operations also produce lists, including the built-in

Lists implement all of the and sequence operations. Danh sách cũng cung cấp phương pháp bổ sung sau

sort[* , key=None , reverse=False]

This method sorts the list in place, using only

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

chấp nhận hai đối số chỉ có thể được truyền bằng từ khóa []

key specifies a function of one argument that is used to extract a comparison key from each list element [for example,

>>> [65].to_bytes[]
b'A'
29]. Khóa tương ứng với mỗi mục trong danh sách được tính một lần và sau đó được sử dụng cho toàn bộ quá trình sắp xếp. The default value of
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
31 means that list items are sorted directly without calculating a separate key value

The utility is available to convert a 2. x style cmp function to a key function

reverse is a boolean value. If set to

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
56, then the list elements are sorted as if each comparison were reversed

Phương pháp này sửa đổi trình tự tại chỗ để tiết kiệm không gian khi sắp xếp một trình tự lớn. Để nhắc nhở người dùng rằng nó hoạt động theo tác dụng phụ, nó không trả về chuỗi đã sắp xếp [sử dụng để yêu cầu rõ ràng một thể hiện danh sách được sắp xếp mới]

Phương pháp được đảm bảo ổn định. Một sắp xếp ổn định nếu nó đảm bảo không thay đổi thứ tự tương đối của các phần tử được so sánh bằng nhau — điều này hữu ích cho việc sắp xếp theo nhiều lần [ví dụ: sắp xếp theo bộ phận, sau đó theo bậc lương]

Để biết các ví dụ sắp xếp và hướng dẫn sắp xếp ngắn gọn, hãy xem

Chi tiết triển khai CPython. Trong khi danh sách đang được sắp xếp, tác động của việc cố gắng thay đổi hoặc thậm chí kiểm tra, danh sách không được xác định. Việc triển khai C của Python làm cho danh sách xuất hiện trống trong suốt thời gian và tăng lên nếu nó có thể phát hiện ra rằng danh sách đã bị thay đổi trong quá trình sắp xếp

bộ dữ liệu

Các bộ dữ liệu là các chuỗi bất biến, thường được sử dụng để lưu trữ các bộ sưu tập dữ liệu không đồng nhất [chẳng hạn như 2 bộ dữ liệu được tạo bởi bộ tích hợp]. Các bộ dữ liệu cũng được sử dụng cho các trường hợp cần một chuỗi dữ liệu đồng nhất bất biến [chẳng hạn như cho phép lưu trữ trong một hoặc một thể hiện]

lớp bộ[[có thể lặp lại]]

Tuples có thể được xây dựng trong một số cách

  • Sử dụng một cặp dấu ngoặc đơn để biểu thị bộ dữ liệu trống.

    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
    
    48

  • Sử dụng dấu phẩy ở cuối cho một tuple đơn lẻ.

    >>> [65].to_bytes[]
    b'A'
    
    40 hoặc
    >>> [65].to_bytes[]
    b'A'
    
    41

  • Tách các mục bằng dấu phẩy.

    >>> [65].to_bytes[]
    b'A'
    
    42 or
    >>> [65].to_bytes[]
    b'A'
    
    43

  • Sử dụng tích hợp.

    >>> [65].to_bytes[]
    b'A'
    
    44 hoặc
    >>> [65].to_bytes[]
    b'A'
    
    46

Hàm tạo xây dựng một bộ có các mục giống nhau và theo cùng thứ tự như các mục của iterable. iterable có thể là một chuỗi, một vùng chứa hỗ trợ phép lặp hoặc một đối tượng lặp. Nếu iterable đã là một Tuple, nó sẽ được trả về không thay đổi. Ví dụ:

>>> [65].to_bytes[]
b'A'
47 trả về
>>> [65].to_bytes[]
b'A'
48 và
>>> [65].to_bytes[]
b'A'
49 trả về
>>> [65].to_bytes[]
b'A'
50. Nếu không có đối số nào được đưa ra, hàm tạo sẽ tạo một bộ dữ liệu trống mới,
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
48

Lưu ý rằng thực ra dấu phẩy tạo nên một bộ chứ không phải dấu ngoặc đơn. Các dấu ngoặc đơn là tùy chọn, ngoại trừ trong trường hợp bộ dữ liệu trống hoặc khi cần thiết để tránh sự mơ hồ về cú pháp. Ví dụ:

>>> [65].to_bytes[]
b'A'
52 là lệnh gọi hàm có ba đối số, trong khi
>>> [65].to_bytes[]
b'A'
53 là lệnh gọi hàm có 3 bộ làm đối số duy nhất

Tuples thực hiện tất cả các hoạt động trình tự

Đối với các bộ sưu tập dữ liệu không đồng nhất trong đó truy cập theo tên rõ ràng hơn truy cập theo chỉ mục, có thể là lựa chọn phù hợp hơn so với đối tượng tuple đơn giản

Các dãy

Loại đại diện cho một dãy số bất biến và thường được sử dụng để lặp một số lần cụ thể trong các vòng lặp

lớp phạm vi[dừng]class range[start, stop[, step]]

Các đối số cho hàm tạo phạm vi phải là số nguyên [tích hợp sẵn hoặc bất kỳ đối tượng nào triển khai phương thức đặc biệt]. Nếu đối số bước bị bỏ qua, nó sẽ mặc định là

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
55. Nếu đối số bắt đầu bị bỏ qua, nó sẽ mặc định là
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
42. Nếu bước bằng 0, được nâng lên

Đối với một bước tích cực, nội dung của phạm vi

>>> [65].to_bytes[]
b'A'
62 được xác định theo công thức
>>> [65].to_bytes[]
b'A'
63 trong đó
>>> [65].to_bytes[]
b'A'
64 và
>>> [65].to_bytes[]
b'A'
65

Đối với bước phủ định, nội dung của phạm vi vẫn được xác định theo công thức

>>> [65].to_bytes[]
b'A'
63, nhưng các ràng buộc là
>>> [65].to_bytes[]
b'A'
64 và
>>> [65].to_bytes[]
b'A'
68

Một đối tượng phạm vi sẽ trống nếu

>>> [65].to_bytes[]
b'A'
69 không đáp ứng ràng buộc giá trị. Phạm vi hỗ trợ các chỉ số âm, nhưng chúng được hiểu là lập chỉ mục từ cuối chuỗi được xác định bởi các chỉ số dương

Phạm vi chứa giá trị tuyệt đối lớn hơn giá trị cho phép nhưng một số tính năng [chẳng hạn như ] có thể tăng

Ví dụ phạm vi

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
7

Phạm vi thực hiện tất cả các thao tác trình tự ngoại trừ phép nối và phép lặp [do thực tế là các đối tượng phạm vi chỉ có thể biểu diễn các trình tự tuân theo một mẫu nghiêm ngặt và phép lặp và phép nối thường sẽ vi phạm mẫu đó]

bắt đầu

Giá trị của tham số bắt đầu [hoặc

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
42 nếu tham số không được cung cấp]

dừng lại

Giá trị của tham số dừng

bươc

Giá trị của tham số bước [hoặc

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
55 nếu tham số không được cung cấp]

Ưu điểm của loại so với thông thường hoặc đối tượng sẽ luôn chiếm cùng một lượng bộ nhớ [nhỏ], bất kể kích thước của phạm vi mà nó đại diện [vì nó chỉ lưu trữ các giá trị

>>> [65].to_bytes[]
b'A'
79,
>>> [65].to_bytes[]
b'A'
80 và
>>> [65].to_bytes[]
b'A'
81, tính toán các mục riêng lẻ

Các đối tượng phạm vi triển khai ABC và cung cấp các tính năng như kiểm tra ngăn chặn, tra cứu chỉ số phần tử, cắt và hỗ trợ cho các chỉ số âm [xem]

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
8

Kiểm tra các đối tượng phạm vi cho bình đẳng với

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
78 và
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
79 so sánh chúng như trình tự. Nghĩa là, hai đối tượng phạm vi được coi là bằng nhau nếu chúng đại diện cho cùng một chuỗi giá trị. [Lưu ý rằng hai đối tượng phạm vi so sánh bằng nhau có thể có các thuộc tính và thuộc tính khác nhau, ví dụ:
>>> [65].to_bytes[]
b'A'
88 hoặc
>>> [65].to_bytes[]
b'A'
89. ]

Đã thay đổi trong phiên bản 3. 2. Triển khai Trình tự ABC. Hỗ trợ cắt lát và chỉ số âm. Kiểm tra các đối tượng để trở thành thành viên trong thời gian không đổi thay vì lặp qua tất cả các mục.

Đã thay đổi trong phiên bản 3. 3. Xác định ‘==’ và ‘. =’ để so sánh các đối tượng phạm vi dựa trên chuỗi giá trị mà chúng xác định [thay vì so sánh dựa trên danh tính đối tượng].

Mới trong phiên bản 3. 3. Các thuộc tính , và.

Xem thêm

  • Công thức linspace cho thấy cách triển khai phiên bản phạm vi lười biếng phù hợp với các ứng dụng dấu phẩy động

Loại chuỗi văn bản —

Dữ liệu văn bản trong Python được xử lý bằng các đối tượng hoặc chuỗi. Các chuỗi là bất biến của các điểm mã Unicode. Chuỗi ký tự được viết theo nhiều cách khác nhau

  • Dấu nháy đơn.

    >>> [65].to_bytes[]
    b'A'
    
    96

  • Dấu ngoặc kép.

    >>> [65].to_bytes[]
    b'A'
    
    97

  • Ba trích dẫn.

    >>> [65].to_bytes[]
    b'A'
    
    98,
    >>> [65].to_bytes[]
    b'A'
    
    99

Các chuỗi được trích dẫn ba lần có thể kéo dài trên nhiều dòng - tất cả khoảng trắng được liên kết sẽ được bao gồm trong chuỗi ký tự

Các chuỗi ký tự là một phần của một biểu thức và chỉ có khoảng trắng giữa chúng sẽ được chuyển đổi hoàn toàn thành một chuỗi ký tự đơn. Tức là,

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

Xem để biết thêm về các dạng chuỗi ký tự khác nhau, bao gồm các chuỗi thoát được hỗ trợ và tiền tố

>>> [65].to_bytes[]
b'A'
62 [“raw”] vô hiệu hóa hầu hết quá trình xử lý chuỗi thoát

Các chuỗi cũng có thể được tạo từ các đối tượng khác bằng cách sử dụng hàm tạo

Vì không có loại "ký tự" riêng biệt, nên việc lập chỉ mục một chuỗi sẽ tạo ra các chuỗi có độ dài 1. Nghĩa là, đối với một chuỗi không trống s,

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

Cũng không có loại chuỗi có thể thay đổi, nhưng hoặc có thể được sử dụng để xây dựng chuỗi từ nhiều đoạn một cách hiệu quả

Đã thay đổi trong phiên bản 3. 3. Để tương thích ngược với chuỗi Python 2, tiền tố

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]
06 một lần nữa được cho phép trên chuỗi ký tự. Nó không ảnh hưởng đến nghĩa của chuỗi ký tự và không thể kết hợp với tiền tố
>>> [65].to_bytes[]
b'A'
62.

lớp str[đối tượng='']class str[object=b'', encoding='utf-8', errors='strict']

Trả về một phiên bản của đối tượng. Nếu đối tượng không được cung cấp, trả về chuỗi rỗng. Mặt khác, hành vi của

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
33 phụ thuộc vào việc mã hóa hoặc lỗi được cung cấp hay không, như sau

Nếu không đưa ra mã hóa cũng như lỗi, thì

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]
09 trả về , đây là biểu diễn chuỗi đối tượng "không chính thức" hoặc có thể in được. For string objects, this is the string itself. If object does not have a method, then falls back to returning

If at least one of encoding or errors is given, object should be a [e. g. or ]. In this case, if object is a [or ] object, then

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]
18 is equivalent to . Otherwise, the bytes object underlying the buffer object is obtained before calling . See and for information on buffer objects

Passing a object to without the encoding or errors arguments falls under the first case of returning the informal string representation [see also the command-line option to Python]. For example

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
9

For more information on the

>>> [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'
22 class and its methods, see and the section below. To output formatted strings, see the and sections. Ngoài ra, xem phần

Phương thức chuỗi

Các chuỗi triển khai tất cả các thao tác trình tự, cùng với các phương thức bổ sung được mô tả bên dưới

Chuỗi cũng hỗ trợ hai kiểu định dạng chuỗi, một cung cấp mức độ linh hoạt và tùy chỉnh lớn [xem và ] và kiểu kia dựa trên định dạng kiểu C

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]
26 xử lý phạm vi loại hẹp hơn và khó sử dụng chính xác hơn một chút, nhưng thường là

Phần của thư viện chuẩn bao gồm một số mô-đun khác cung cấp nhiều tiện ích liên quan đến văn bản [bao gồm hỗ trợ biểu thức chính quy trong mô-đun]

str. viết hoa[]

Trả về một bản sao của chuỗi với ký tự đầu tiên được viết hoa và phần còn lại được viết thường

Đã thay đổi trong phiên bản 3. 8. Ký tự đầu tiên hiện được đặt thành chữ hoa tiêu đề thay vì chữ hoa. Điều này có nghĩa là các ký tự như chữ ghép sẽ chỉ viết hoa chữ cái đầu tiên, thay vì ký tự đầy đủ.

str. casefold[]

Trả về một bản sao của chuỗi. Chuỗi casefolded có thể được sử dụng để khớp không caseless

Casefolding tương tự như chữ thường nhưng tích cực hơn vì nó nhằm mục đích loại bỏ tất cả các phân biệt chữ hoa chữ thường trong một chuỗi. Ví dụ: chữ thường tiếng Đức

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]
28 tương đương với
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]
29. Vì nó đã là chữ thường, nên sẽ không làm gì với
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]
28;

Thuật toán casefolding được mô tả trong phần 3. 13 của Tiêu chuẩn Unicode

Mới trong phiên bản 3. 3

str. trung tâm[chiều rộng[ , fillchar]]

Trả về căn giữa trong một chuỗi có chiều dài chiều rộng. Việc đệm được thực hiện bằng cách sử dụng ký tự điền được chỉ định [mặc định là không gian ASCII]. Chuỗi ban đầu được trả về nếu chiều rộng nhỏ hơn hoặc bằng

>>> [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'
13

str. đếm[phụ[ , start[, end]]]

Trả về số lần xuất hiện không trùng lặp của chuỗi con sub trong phạm vi [bắt đầu, kết thúc]. Các đối số tùy chọn bắt đầu và kết thúc được diễn giải như trong ký hiệu lát cắt

Nếu phụ trống, trả về số lượng chuỗi trống giữa các ký tự bằng độ dài của chuỗi cộng với một

str. mã hóa[mã hóa=', errors='strict']

Trả lại chuỗi được mã hóa thành

mã hóa mặc định thành

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]
36;

lỗi kiểm soát cách xử lý lỗi mã hóa. Nếu

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]
37 [mặc định], một ngoại lệ sẽ được đưa ra. Các giá trị có thể khác là
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]
39,
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]
40,
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]
41,
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]
42 và bất kỳ tên nào khác được đăng ký qua. Xem để biết chi tiết

Vì lý do hiệu suất, giá trị của lỗi không được kiểm tra tính hợp lệ trừ khi thực sự xảy ra lỗi mã hóa, được bật hoặc a được sử dụng

Đã thay đổi trong phiên bản 3. 1. Đã thêm hỗ trợ cho đối số từ khóa.

Đã thay đổi trong phiên bản 3. 9. Giá trị của đối số lỗi hiện được kiểm tra trong và trong.

str. endswith[hậu tố[ , start[, end]]]

Trả về

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
56 nếu chuỗi kết thúc bằng hậu tố đã chỉ định, nếu không thì trả về
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
38. hậu tố cũng có thể là một bộ hậu tố cần tìm. Với bắt đầu tùy chọn, bắt đầu kiểm tra tại vị trí đó. Với đầu cuối tùy chọn, dừng so sánh tại vị trí đó

str. tab mở rộng[kích thước tab=8]

Trả về một bản sao của chuỗi trong đó tất cả các ký tự tab được thay thế bằng một hoặc nhiều dấu cách, tùy thuộc vào cột hiện tại và kích thước tab đã cho. Vị trí tab xảy ra với mọi ký tự kích thước tab [mặc định là 8, cho vị trí tab ở các cột 0, 8, 16, v.v.]. Để mở rộng chuỗi, cột hiện tại được đặt thành 0 và chuỗi được kiểm tra từng ký tự. Nếu ký tự là một tab [

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]
46], một hoặc nhiều ký tự khoảng trắng sẽ được chèn vào kết quả cho đến khi cột hiện tại bằng với vị trí tab tiếp theo. [Bản thân ký tự tab không được sao chép. ] Nếu ký tự là một dòng mới [
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]
47] hoặc trả về [
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]
48], nó sẽ được sao chép và cột hiện tại được đặt lại về 0. Bất kỳ ký tự nào khác được sao chép không thay đổi và cột hiện tại được tăng thêm một bất kể ký tự đó được thể hiện như thế nào khi in

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
0

str. tìm[phụ[ , start[, end]]]

Trả về chỉ số thấp nhất trong chuỗi nơi tìm thấy chuỗi con sub trong lát cắt

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]
49. Các đối số tùy chọn bắt đầu và kết thúc được diễn giải như trong ký hiệu lát cắt. Trả lại
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
41 nếu không tìm thấy phụ

Ghi chú

Phương pháp này chỉ nên được sử dụng nếu bạn cần biết vị trí của phụ. Để kiểm tra sub có phải là xâu con hay không ta dùng toán tử

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
1

str. định dạng[*args , **kwargs]

Thực hiện thao tác định dạng chuỗi. Chuỗi mà phương thức này được gọi có thể chứa văn bản bằng chữ hoặc các trường thay thế được phân tách bằng dấu ngoặc nhọn

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
50. Mỗi trường thay thế chứa chỉ mục số của đối số vị trí hoặc tên của đối số từ khóa. Trả về một bản sao của chuỗi trong đó mỗi trường thay thế được thay thế bằng giá trị chuỗi của đối số tương ứng

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
2

Xem mô tả về các tùy chọn định dạng khác nhau có thể được chỉ định trong chuỗi định dạng

Ghi chú

Khi định dạng một số [, , và các lớp con] với loại

def bit_count[self]:
    return bin[self].count["1"]
51 [ví dụ:.
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]
59], hàm tạm thời đặt ngôn ngữ
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]
60 thành ngôn ngữ
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]
61 để giải mã các trường
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]
62 và
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]
63 của
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]
64 nếu chúng không phải ASCII hoặc dài hơn 1 byte và ngôn ngữ
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]
61 khác với ngôn ngữ
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]
60. Thay đổi tạm thời này ảnh hưởng đến các chủ đề khác

Đã thay đổi trong phiên bản 3. 7. Khi định dạng một số với kiểu

def bit_count[self]:
    return bin[self].count["1"]
51, hàm sẽ tạm thời đặt ngôn ngữ
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]
60 thành ngôn ngữ
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]
61 trong một số trường hợp.

str. format_map[ánh xạ]

Tương tự như

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]
70, ngoại trừ việc
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]
71 được sử dụng trực tiếp và không được sao chép vào một. Điều này hữu ích nếu ví dụ
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]
71 là một lớp con dict

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
3

Mới trong phiên bản 3. 2

str. chỉ mục[phụ[ , start[, end]]]

Thích , nhưng tăng khi không tìm thấy chuỗi con

str. isalnum[]

Trả về

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
56 nếu tất cả các ký tự trong chuỗi là chữ và số và có ít nhất một ký tự, ngược lại là
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
38. Một ký tự
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]
78 là chữ và số nếu một trong các giá trị sau trả về
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
56.
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]
80,
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]
81,
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]
82 hoặc
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]
83

str. isalpha[]

Trả về

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
56 nếu tất cả các ký tự trong chuỗi là chữ cái và có ít nhất một ký tự, ngược lại là
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
38. Các ký tự chữ cái là những ký tự được định nghĩa trong cơ sở dữ liệu ký tự Unicode là “Chữ cái”, tôi. e. , những người có thuộc tính danh mục chung là một trong số “Lm”, “Lt”, “Lu”, “Ll”, hoặc “Lo”. Lưu ý rằng thuộc tính này khác với thuộc tính “Alphabetic” được xác định trong Tiêu chuẩn Unicode

str. isascii[]

Trả về

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
56 nếu chuỗi trống hoặc tất cả các ký tự trong chuỗi là ASCII, ngược lại là
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
38. Các ký tự ASCII có các điểm mã trong phạm vi U+0000-U+007F

Mới trong phiên bản 3. 7

str. hệ thập phân[]

Trả về

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
56 nếu tất cả các ký tự trong chuỗi là ký tự thập phân và có ít nhất một ký tự, ngược lại là
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
38. Các ký tự thập phân là những ký tự có thể được sử dụng để tạo thành các số trong cơ số 10, e. g. U+0660, CHỮ SỐ Ả Rập-INDIC. Chính thức, một ký tự thập phân là một ký tự trong Danh mục chung Unicode “Nd”

str. isdigit[]

Trả về

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
56 nếu tất cả các ký tự trong chuỗi là chữ số và có ít nhất một ký tự, ngược lại là
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
38. Chữ số bao gồm các ký tự thập phân và chữ số cần xử lý đặc biệt, chẳng hạn như chữ số chỉ số trên tương thích. Điều này bao gồm các chữ số không thể được sử dụng để tạo thành số trong cơ số 10, như số Kharosthi. Chính thức, một chữ số là một ký tự có giá trị thuộc tính Numeric_Type=Digit hoặc Numeric_Type=Decimal

str. mã định danh[]

Trả về

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
56 nếu chuỗi là mã định danh hợp lệ theo định nghĩa ngôn ngữ, phần

Gọi để kiểm tra xem chuỗi

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]
94 có phải là mã định danh dành riêng hay không, chẳng hạn như và

Thí dụ

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
4

str. giảm tốc[]

Trả về

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
56 nếu tất cả các ký tự viết hoa trong chuỗi là chữ thường và có ít nhất một ký tự viết hoa, ngược lại là _________38

str. số[]

Trả về

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
56 nếu tất cả các ký tự trong chuỗi là ký tự số và có ít nhất một ký tự, ngược lại là
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
38. Các ký tự số bao gồm các ký tự chữ số và tất cả các ký tự có thuộc tính giá trị số Unicode, e. g. U+2155, PHÂN SỐ Thô tục MỘT PHẦN NĂM. Về hình thức, các ký tự số là những ký tự có giá trị thuộc tính Numeric_Type=Digit, Numeric_Type=Decimal hoặc Numeric_Type=Numeric

str. có thể in được[]

Trả về

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
56 nếu tất cả các ký tự trong chuỗi có thể in được hoặc chuỗi trống, ngược lại là
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
38. Các ký tự không in được là những ký tự được xác định trong cơ sở dữ liệu ký tự Unicode là “Khác” hoặc “Dấu phân cách”, ngoại trừ khoảng trống ASCII [0x20] được coi là có thể in được. [Lưu ý rằng các ký tự có thể in được trong ngữ cảnh này là những ký tự không được thoát khi được gọi trên một chuỗi. Nó không liên quan đến việc xử lý các chuỗi được ghi vào hoặc. ]

str. không gian[]

Trả về

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
56 nếu chỉ có ký tự khoảng trắng trong chuỗi và có ít nhất một ký tự, ngược lại là
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
38

Một ký tự là khoảng trắng nếu trong cơ sở dữ liệu ký tự Unicode [xem ], loại chung của nó là

>>> 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
09 [“Dấu phân cách, dấu cách”] hoặc loại hai chiều của nó là một trong số
>>> 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
10,
>>> 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
11 hoặc
>>> 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
12

str. tiêu đề[]

Trả về

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
56 nếu chuỗi là một chuỗi có tiêu đề và có ít nhất một ký tự, ví dụ: các ký tự chữ hoa chỉ có thể theo sau các ký tự không có chữ hoa và các ký tự chữ thường chỉ theo sau các ký tự có chữ hoa. Trả lại
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
38 nếu không

str. ăn tối[]

Trả về

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
56 nếu tất cả các ký tự viết hoa trong chuỗi là chữ hoa và có ít nhất một ký tự viết hoa, ngược lại là
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
38

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
5

str. tham gia[có thể lặp lại]

Trả về một chuỗi là chuỗi nối của các chuỗi trong iterable. A sẽ được nâng lên nếu có bất kỳ giá trị không phải chuỗi nào có thể lặp lại, bao gồm cả các đối tượng. Dấu phân cách giữa các phần tử là chuỗi cung cấp phương thức này

str. ljust[chiều rộng[ , fillchar]]

Trả lại chuỗi căn trái trong một chuỗi có chiều dài chiều rộng. Việc đệm được thực hiện bằng cách sử dụng ký tự điền được chỉ định [mặc định là không gian ASCII]. Chuỗi ban đầu được trả về nếu chiều rộng nhỏ hơn hoặc bằng

>>> [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'
13

str. thấp hơn[]

Trả về một bản sao của chuỗi với tất cả các ký tự có hoa văn được chuyển đổi thành chữ thường

Thuật toán viết thường được sử dụng được mô tả trong phần 3. 13 của Tiêu chuẩn Unicode

str. lstrip[[ký tự]]

Trả về một bản sao của chuỗi đã xóa các ký tự đầu. Đối số ký tự là một chuỗi chỉ định bộ ký tự sẽ bị xóa. Nếu bỏ qua hoặc

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
31, đối số ký tự mặc định xóa khoảng trắng. Đối số ký tự không phải là tiền tố;

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
6

Xem phương pháp sẽ xóa một chuỗi tiền tố thay vì tất cả một bộ ký tự. Ví dụ

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
7

tĩnh str. maketrans[x[ , y[, z]]]

Phương thức tĩnh này trả về một bảng dịch có thể sử dụng được cho

Nếu chỉ có một đối số, thì đó phải là một từ điển ánh xạ thứ tự Unicode [số nguyên] hoặc ký tự [chuỗi có độ dài 1] sang thứ tự Unicode, chuỗi [có độ dài tùy ý] hoặc

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
31. Các phím ký tự sau đó sẽ được chuyển đổi thành thứ tự

Nếu có hai đối số, chúng phải là các chuỗi có độ dài bằng nhau và trong từ điển kết quả, mỗi ký tự trong x sẽ được ánh xạ tới ký tự ở cùng vị trí trong y. Nếu có đối số thứ ba, nó phải là một chuỗi, các ký tự của nó sẽ được ánh xạ tới ____0_______31 trong kết quả

str. phân vùng[sep]

Tách chuỗi ở lần xuất hiện đầu tiên của sep và trả về 3-tuple chứa phần trước dấu tách, chính dấu tách và phần sau dấu tách. Nếu không tìm thấy dấu tách, hãy trả về 3-bộ chứa chính chuỗi đó, theo sau là hai chuỗi trống

str. removeprefix[prefix , /]

Nếu chuỗi bắt đầu bằng chuỗi tiền tố, hãy trả về

>>> 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
25. Nếu không, hãy trả về một bản sao của chuỗi gốc

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
8

Mới trong phiên bản 3. 9

str. hậu tố loại bỏ[hậu tố , /]

Nếu chuỗi kết thúc bằng chuỗi hậu tố và hậu tố đó không trống, hãy trả về

>>> 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
26. Nếu không, hãy trả về một bản sao của chuỗi gốc

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
9

Mới trong phiên bản 3. 9

str. thay thế[ , mới[, count]]

Trả về một bản sao của chuỗi với tất cả các lần xuất hiện của chuỗi con cũ được thay thế bằng chuỗi mới. Nếu số lượng đối số tùy chọn được cung cấp, chỉ những lần xuất hiện đầu tiên được thay thế

str. rfind[phụ[ , start[, end]]]

Trả về chỉ số cao nhất trong chuỗi nơi tìm thấy chuỗi con sub, sao cho sub đó được chứa trong

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]
49. Các đối số tùy chọn bắt đầu và kết thúc được diễn giải như trong ký hiệu lát cắt. Trả lại
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
41 khi thất bại

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

Like nhưng tăng khi không tìm thấy chuỗi con sub

str. rjust[chiều rộng[ , fillchar]]

Trả về chuỗi được căn phải trong một chuỗi có chiều dài chiều rộng. Việc đệm được thực hiện bằng cách sử dụng ký tự điền được chỉ định [mặc định là không gian ASCII]. Chuỗi ban đầu được trả về nếu chiều rộng nhỏ hơn hoặc bằng

>>> [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'
13

str. phân vùng[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

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
31, any whitespace string is a separator. Except for splitting from the right, behaves like which is described in detail below

str. rstrip[[ký tự]]

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

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
31, the chars argument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped

def bit_count[self]:
    return bin[self].count["1"]
0

See for a method that will remove a single suffix string rather than all of a set of characters. For example

def bit_count[self]:
    return bin[self].count["1"]
1

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

>>> 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
37 elements]. If maxsplit is not specified or
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
41, 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,

>>> 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
39 returns
>>> 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
40]. The sep argument may consist of multiple characters [for example,
>>> 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
41 returns
>>> 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
42]. Splitting an empty string with a specified separator returns
>>> 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
43

For example

def bit_count[self]:
    return bin[self].count["1"]
2

If sep is not specified or is

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
31, 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
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
31 separator returns
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
49

For example

def bit_count[self]:
    return bin[self].count["1"]
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

Representation

Description

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

Line Feed

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

Carriage Return

>>> 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
49

Carriage Return + Line Feed

>>> 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
50 or
>>> 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
51

Line Tabulation

>>> 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
52 or
>>> 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
53

Form Feed

>>> 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
54

File Separator

>>> 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
55

Group Separator

>>> 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
56

Record Separator

>>> 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
57

Next Line [C1 Control Code]

>>> 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
58

Line Separator

>>> 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
59

Paragraph Separator

Changed in version 3. 2.

>>> 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
50 and
>>> 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
52 added to list of line boundaries.

For example

def bit_count[self]:
    return bin[self].count["1"]
4

Unlike 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

def bit_count[self]:
    return bin[self].count["1"]
5

For comparison,

>>> 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
63 gives

def bit_count[self]:
    return bin[self].count["1"]
6

str. startswith[prefix[ , start[ , end]]]

Return

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
56 if string starts with the prefix, otherwise return
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
38. 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

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
31, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped

def bit_count[self]:
    return bin[self].count["1"]
7

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

def bit_count[self]:
    return bin[self].count["1"]
8

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

>>> 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
67

str. title[]

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

For example

def bit_count[self]:
    return bin[self].count["1"]
9

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

>>> [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'
0

The function does not have this problem, as it splits words on spaces only

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

>>> [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'
1

str. dịch[bảng]

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

>>> 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
69, typically a or . 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
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
31, to delete the character from the return string; or raise a exception, to map the character to itself

You can use to create a translation map from character-to-character mappings in different formats

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

str. trên[]

Return a copy of the string with all the cased characters converted to uppercase. Lưu ý rằng

>>> 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
74 có thể là
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
38 nếu
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]
94 chứa các ký tự không được viết hoa hoặc nếu danh mục Unicode của [các] ký tự kết quả không phải là “Lu” [Chữ cái, chữ hoa], mà là e. g. “Lt” [Thư, tựa đề]

The uppercasing algorithm used is described in section 3. 13 of the Unicode Standard

str. zfill[width]

Return a copy of the string left filled with ASCII

>>> 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
77 digits to make a string of length width. A leading sign prefix [
>>> 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
78/
>>> 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
79] is handled by inserting the padding after the sign character rather than before. Chuỗi ban đầu được trả về nếu chiều rộng nhỏ hơn hoặc bằng
>>> [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'
13

For example

>>> [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'
2

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]
26-style String Formatting

Ghi chú

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 , the interface, or 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

>>> 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
83 operator [modulo]. This is also known as the string formatting or interpolation operator. Given
>>> 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
84 [where format is a string],
>>> 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
83 conversion specifications in format are replaced with zero or more elements of values. The effect is similar to using the
>>> 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
86 in the C language

If format requires a single argument, values may be a single non-tuple object. 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

    >>> 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
    
    87 character, which marks the start of the specifier

  2. Mapping key [optional], consisting of a parenthesised sequence of characters [for example,

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

  3. Conversion flags [optional], which affect the result of some conversion types

  4. Minimum field width [optional]. If specified as an

    >>> 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
    
    89 [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

    >>> 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
    
    90 [dot] followed by the precision. If specified as
    >>> 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
    
    89 [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

>>> 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
87 character. The mapping key selects the value to be formatted from the mapping. For example

>>> [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'
3

In this case no

>>> [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'
00 specifiers may occur in a format [since they require a sequential parameter list]

The conversion flag characters are

Flag

Nghĩa

>>> 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
94

The value conversion will use the “alternate form” [where defined below]

>>> 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
77

The conversion will be zero padded for numeric values

>>> 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
79

The converted value is left adjusted [overrides the

>>> 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
77 conversion if both are given]

>>> 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
98

[a space] A blank should be left before a positive number [or empty string] produced by a signed conversion

>>> 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
78

A sign character [

>>> 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
78 or
>>> 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
79] will precede the conversion [overrides a “space” flag]

A length modifier [

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 >> n.bit_count[]
3
>>> [-n].bit_count[]
3
41 on failure

The subsequence to search for may be any or an integer in the range 0 to 255

Đã thay đổi trong phiên bản 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 but raises when the subsequence sub is not found

The subsequence to search for may be any or an integer in the range 0 to 255

Đã thay đổi trong phiên bản 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. startswith[prefix[ , start[ , end]]]bytearray. startswith[prefix[ , start[ , end]]]

Return

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
56 if the binary data starts with the specified prefix, otherwise return
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
38. 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. 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 method to create a translation table

Set the table argument to

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
31 for translations that only delete characters

>>> [65].to_bytes[]
b'A'
4

Changed in version 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 objects, the original sequence is returned if width is less than or equal to

>>> [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'
13

Ghi chú

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. Quá trình đệm được thực hiện bằng cách sử dụng fillbyte đã chỉ định [mặc định là một không gian ASCII]. For objects, the original sequence is returned if width is less than or equal to

>>> [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'
13

Ghi chú

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

Trả về một bản sao của chuỗi đã xóa các byte đầu được chỉ định. 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

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
31, the chars argument defaults to removing ASCII whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped

>>> [65].to_bytes[]
b'A'
5

The binary sequence of byte values to remove may be any . Xem phương pháp sẽ xóa một chuỗi tiền tố thay vì tất cả một bộ ký tự. For example

>>> [65].to_bytes[]
b'A'
6

Ghi chú

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

byte. rjust[chiều rộng[ , . 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 objects, the original sequence is returned if width is less than or equal to

>>> [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'
13

Ghi chú

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

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
31, any subsequence consisting solely of ASCII whitespace is a separator. Except for splitting from the right, behaves like 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

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
31, the chars argument defaults to removing ASCII whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped

>>> [65].to_bytes[]
b'A'
7

The binary sequence of byte values to remove may be any . See for a method that will remove a single suffix string rather than all of a set of characters. For example

>>> [65].to_bytes[]
b'A'
8

Ghi chú

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]

Tách chuỗi nhị phân thành các chuỗi con cùng loại, sử dụng sep làm chuỗi phân cách. If maxsplit is given and non-negative, at most maxsplit splits are done [thus, the list will have at most

>>> 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
37 elements]. If maxsplit is not specified or is
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
41, 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,

>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
27 returns
>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
28]. The sep argument may consist of a multibyte sequence [for example,
>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
29 returns
>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
30]. Splitting an empty sequence with a specified separator returns
>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
31 or
>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
32 depending on the type of object being split. The sep argument may be any

For example

>>> [65].to_bytes[]
b'A'
9

If sep is not specified or is

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
31, 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
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
49

For example

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

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

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
31, 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

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

The binary sequence of byte values to remove may be any

Ghi chú

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

Các phương thức sau trên các đối tượng byte và bytearray giả sử sử dụng các định dạng nhị phân tương thích ASCII và không được áp dụng cho dữ liệu nhị phân tùy ý. 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

Ghi chú

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 [

>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
36], 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 [
>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
37] or carriage return [
>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
38], 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

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

Ghi chú

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

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
56 if all bytes in the sequence are alphabetical ASCII characters or ASCII decimal digits and the sequence is not empty,
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
38 otherwise. Alphabetic ASCII characters are those byte values in the sequence
>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
41. ASCII decimal digits are those byte values in the sequence
>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
42

For example

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

bytes. isalpha[]bytearray. isalpha[]

Return

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
56 if all bytes in the sequence are alphabetic ASCII characters and the sequence is not empty,
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
38 otherwise. Alphabetic ASCII characters are those byte values in the sequence
>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
41

For example

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

bytes. isascii[]bytearray. isascii[]

Return

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
56 if the sequence is empty or all bytes in the sequence are ASCII,
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
38 otherwise. ASCII bytes are in the range 0-0x7F

Mới trong phiên bản 3. 7

bytes. isdigit[]bytearray. isdigit[]

Return

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
56 if all bytes in the sequence are ASCII decimal digits and the sequence is not empty,
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
38 otherwise. ASCII decimal digits are those byte values in the sequence
>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
42

For example

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

bytes. islower[]bytearray. islower[]

Return

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
56 if there is at least one lowercase ASCII character in the sequence and no uppercase ASCII characters,
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
38 otherwise

For example

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

Lowercase ASCII characters are those byte values in the sequence

>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
53. Các ký tự ASCII chữ hoa là những giá trị byte trong chuỗi
>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
54

bytes. isspace[]bytearray. isspace[]

Trả về

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
56 nếu tất cả các byte trong chuỗi là khoảng trắng ASCII và chuỗi không trống, ngược lại là
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
38. Các ký tự khoảng trắng ASCII là các giá trị byte đó trong chuỗi
>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
57 [dấu cách, tab, dòng mới, xuống dòng, tab dọc, nguồn cấp biểu mẫu]

byte. tiêu đề[]bytearray. istitle[]

Trả về

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
56 nếu chuỗi là chữ cái tiêu đề ASCII và chuỗi không trống, ngược lại là
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
38. Xem để biết thêm chi tiết về định nghĩa của “titlecase”

For example

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

byte. isupper[]bytearray. isupper[]

Return

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
56 if there is at least one uppercase alphabetic ASCII character in the sequence and no lowercase ASCII characters,
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
38 otherwise

For example

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

Lowercase ASCII characters are those byte values in the sequence

>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
53. Các ký tự ASCII chữ hoa là những giá trị byte trong chuỗi
>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
54

bytes. lower[]bytearray. lower[]

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

For example

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

Lowercase ASCII characters are those byte values in the sequence

>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
53. Các ký tự ASCII chữ hoa là những giá trị byte trong chuỗi
>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
54

Ghi chú

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 approach to splitting lines. Line breaks are not included in the resulting list unless keepends is given and true

For example

>>> 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
0

Unlike 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

>>> 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
1

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

For example

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

Lowercase ASCII characters are those byte values in the sequence

>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
53. Các ký tự ASCII chữ hoa là những giá trị byte trong chuỗi
>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
54

Unlike , it is always the case that

>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
71 for the binary versions. Case conversions are symmetrical in ASCII, even though that is not generally true for arbitrary Unicode code points

Ghi chú

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

For example

>>> 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
3

Lowercase ASCII characters are those byte values in the sequence

>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
53. Uppercase ASCII characters are those byte values in the sequence
>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
54. 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

>>> 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
4

A workaround for apostrophes can be constructed using regular expressions

>>> 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
5

Ghi chú

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

For example

>>> 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
6

Lowercase ASCII characters are those byte values in the sequence

>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
53. Các ký tự ASCII chữ hoa là những giá trị byte trong chuỗi
>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
54

Ghi chú

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]

Trả lại một bản sao của chuỗi còn lại được điền bằng ASCII

>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
76 chữ số để tạo một chuỗi có chiều dài chiều rộng. A leading sign prefix [
>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
77/
>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
78] is handled by inserting the padding after the sign character rather than before. For objects, the original sequence is returned if width is less than or equal to
>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
80

For example

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

Ghi chú

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

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]
26-style Bytes Formatting

Ghi chú

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 [

>>> [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'
23/
>>> [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'
24] have one unique built-in operation. the
>>> 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
83 operator [modulo]. This is also known as the bytes formatting or interpolation operator. Given
>>> 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
84 [where format is a bytes object],
>>> 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
83 conversion specifications in format are replaced with zero or more elements of values. The effect is similar to using the
>>> 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
86 in the C language

If format requires a single argument, values may be a single non-tuple object. 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

    >>> 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
    
    87 character, which marks the start of the specifier

  2. Mapping key [optional], consisting of a parenthesised sequence of characters [for example,

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

  3. Conversion flags [optional], which affect the result of some conversion types

  4. Minimum field width [optional]. If specified as an

    >>> 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
    
    89 [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

    >>> 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
    
    90 [dot] followed by the precision. If specified as
    >>> 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
    
    89 [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

>>> 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
87 character. The mapping key selects the value to be formatted from the mapping. For example

>>> 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
8

In this case no

>>> [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'
00 specifiers may occur in a format [since they require a sequential parameter list]

The conversion flag characters are

Flag

Nghĩa

>>> 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
94

The value conversion will use the “alternate form” [where defined below]

>>> 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
77

The conversion will be zero padded for numeric values

>>> 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
79

The converted value is left adjusted [overrides the

>>> 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
77 conversion if both are given]

>>> 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
98

[a space] A blank should be left before a positive number [or empty string] produced by a signed conversion

>>> 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
78

A sign character [

>>> 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
78 or
>>> 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
79] will precede the conversion [overrides a “space” flag]

A length modifier [

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  '-0b100101'
    s = s.lstrip['-0b'] # remove leading zeros and minus sign
    return len[s]       # len['100101'] --> 6
085

>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
6

Multi-dimensional arrays

>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
7

Mới trong phiên bản 3. 3

readonly

A bool indicating whether the memory is read only

format

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

Changed in version 3. 3. format

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
088 is now handled according to the struct module syntax. This means that
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
089.

itemsize

The size in bytes of each element of the memoryview

>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
8

ndim

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

shape

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

Changed in version 3. 3. An empty tuple instead of

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
31 when ndim = 0.

strides

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

Changed in version 3. 3. An empty tuple instead of

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
31 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-

Mới trong phiên bản 3. 3

f_contiguous

A bool indicating whether the memory is Fortran

Mới trong phiên bản 3. 3

contiguous

A bool indicating whether the memory is

Mới trong phiên bản 3. 3

Set Types — ,

A set object is an unordered collection of distinct objects. Các ứng dụng phổ biến bao gồm kiểm tra tư cách thành viên, loại bỏ các bản trùng lặp khỏi chuỗi và tính toán các phép toán như giao, hợp, hiệu và hiệu đối xứng. [For other containers see the built-in , , and classes, and the module. ]

Like other collections, sets support

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
100,
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
101, and
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
102. Là một tập hợp không có thứ tự, các tập hợp không ghi vị trí phần tử hoặc thứ tự chèn. Accordingly, sets do not support indexing, slicing, or other sequence-like behavior

There are currently two built-in set types, and . Loại có thể thay đổi — nội dung có thể được thay đổi bằng các phương thức như

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
106 và
>>> [65].to_bytes[]
b'A'
01. 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. Loại là bất biến và — không thể thay đổi nội dung của nó sau khi nó được tạo;

Ví dụ: có thể tạo các tập hợp không trống [không phải tập hợp cố định] bằng cách đặt danh sách các phần tử được phân tách bằng dấu phẩy trong dấu ngoặc nhọn.

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
109, ngoài hàm tạo

Các hàm tạo cho cả hai lớp hoạt động như nhau

lớp bộ[[có thể lặp lại]]class frozenset[[iterable]]

Trả về một đối tượng set hoặc freezeset mới có các phần tử được lấy từ iterable. Các phần tử của một tập hợp phải. Để biểu diễn các tập hợp, các tập hợp bên trong phải là các đối tượng. Nếu iterable không được chỉ định, một bộ trống mới được trả về

Các bộ có thể được tạo bằng nhiều cách

  • Sử dụng danh sách các phần tử được phân tách bằng dấu phẩy trong dấu ngoặc nhọn.

    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
    
    109

  • Use a set comprehension.

    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
    
    113

  • Use the type constructor.

    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
    
    51,
    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
    
    115,
    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
    
    116

Instances of and 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

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
56 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 6 120

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,

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
121

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 , , , , , and 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

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
128 in favor of the more readable
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
129

Both and 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 are compared to instances of based on their members. For example,

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
134 returns
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
56 and so does
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
136

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

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
38.
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
138,
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
139, or
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
140

Since sets only define partial ordering [subset relationships], the output of the method is undefined for lists of sets

Set elements, like dictionary keys, must be

Binary operations that mix instances with return the type of the first operand. For example.

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
144 returns an instance of

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

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 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 if the set is empty

clear[]

Remove all elements from the set

Note, the non-operator versions of the , , , and methods will accept any iterable as an argument

Note, the elem argument to the

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
00, , and methods may be a set. To support searching for an equivalent frozenset, a temporary one is created from elem

Mapping Types —

A object maps 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 , , and classes, and the module. ]

A dictionary’s keys are almost arbitrary values. Values that are not , 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

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
55,
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
163, and
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
56] can be used interchangeably to index the same dictionary entry

class dict[**kwargs]class dict[mapping , **kwargs]class dict[iterable , **kwargs]

Trả về một từ điển mới được khởi tạo từ một đối số vị trí tùy chọn và một bộ đối số từ khóa có thể trống

Từ điển có thể được tạo ra bằng nhiều cách

  • Use a comma-separated list of

    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
    
    165 pairs within braces.
    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
    
    166 or
    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
    
    167

  • Use a dict comprehension.

    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
    
    50,
    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
    
    169

  • Use the type constructor.

    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
    
    170,
    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
    
    171,
    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
    
    172

Nếu không có đối số vị trí nào được đưa ra, một từ điển trống sẽ được tạo. If a positional argument is given and it is a mapping object, a dictionary is created with the same key-value pairs as the mapping object. Otherwise, the positional argument must be an object. Each item in the iterable must itself be an iterable with exactly two objects. The first object of each item becomes a key in the new dictionary, and the second object the corresponding value. If a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary

Nếu các đối số từ khóa được đưa ra, thì các đối số từ khóa và giá trị của chúng sẽ được thêm vào từ điển được tạo từ đối số vị trí. 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

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
173

>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
9

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 if key is not in the map

If a subclass of dict defines a method

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
175 and key is not present, the
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
176 operation calls that method with the key key as argument. The
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
176 operation then returns or raises whatever is returned or raised by the
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
178 call. No other operations or methods invoke
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
175. If
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
175 is not defined, is raised.
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
175 must be a method; it cannot be an instance variable

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
00

The example above shows part of the implementation of . A different

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
184 method is used by

d[key] = value

Set

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
176 to value

del d[key]

Remove

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
176 from d. Raises a if key is not in the map

key in d

Return

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
56 if d has a key key, else
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
38

key not in d

Equivalent to

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
191

iter[d]

Return an iterator over the keys of the dictionary. This is a shortcut for

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
192

clear[]

Remove all items from the dictionary

copy[]

Return a shallow copy of the dictionary

classmethod fromkeys[iterable[ , value]]

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

is a class method that returns a new dictionary. value defaults to

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
31. 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 instead

get[key[ , default]]

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to

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
31, so that this method never raises a

items[]

Return a new view of the dictionary’s items [

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
197 pairs]. See the

keys[]

Return a new view of the dictionary’s keys. See the

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 is raised

popitem[]

Xóa và trả về cặp

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
197 từ từ điển. Pairs are returned in LIFO order

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

Changed in version 3. 7. LIFO order is now guaranteed. In prior versions, would return an arbitrary key/value pair.

reversed[d]

Return a reverse iterator over the keys of the dictionary. This is a shortcut for

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
204

Mới trong phiên bản 3. 8

setdefault[key[ , default]]

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

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
31

update[[other]]

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

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
31

accepts either another dictionary object 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.

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
208

values[]

Return a new view of the dictionary’s values. See the

An equality comparison between one

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
209 view and another will always return
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
38. This also applies when comparing
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
209 to itself

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
01

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

Mới trong phiên bản 3. 9

d . = other

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

Mới trong phiên bản 3. 9

Dictionaries compare equal if and only if they have the same

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
197 pairs [regardless of ordering]. Order comparisons [‘’] raise .

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

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
02

Changed in version 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

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
03

Changed in version 3. 8. Dictionaries are now reversible.

Xem thêm

can be used to create a read-only view of a

Các đối tượng xem từ điển

Các đối tượng được trả về và là các đối tượng xem. Chúng cung cấp chế độ xem động cho các mục nhập của từ điển, có nghĩa là khi từ điển thay đổi, chế độ xem sẽ phản ánh những thay đổi này

Chế độ xem từ điển có thể được lặp đi lặp lại để mang lại dữ liệu tương ứng và hỗ trợ kiểm tra tư cách thành viên

len[dictview]

Trả về số mục trong từ điển

lặp đi lặp lại [dictview]

Trả về một trình vòng lặp trên các khóa, giá trị hoặc mục [được biểu thị dưới dạng bộ dữ liệu của

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
197] trong từ điển

Các khóa và giá trị được lặp lại theo thứ tự chèn. Điều này cho phép tạo ra các cặp

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
220 bằng cách sử dụng. ______________222. Một cách khác để tạo danh sách tương tự là
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
223

Lặp lại các dạng xem trong khi thêm hoặc xóa các mục trong từ điển có thể gây ra hoặc không thể lặp lại trên tất cả các mục

Đã thay đổi trong phiên bản 3. 7. Thứ tự từ điển được đảm bảo là thứ tự chèn.

x in dictview

Return

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
56 if x is in the underlying dictionary’s keys, values or items [in the latter case, x should be a
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
197 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

Changed in version 3. 8. Dictionary views are now reversible.

dictview. mapping

Return a that wraps the original dictionary to which the view refers

Mới trong phiên bản 3. 10

Keys views are set-like since their entries are unique and hashable. If all values are hashable, so that

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
197 pairs are unique and hashable, then the items view is also set-like. [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 are available [for example,
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
78,
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
74, or
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
232]

An example of dictionary view usage

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
04

Context Manager Types

Python’s statement supports the concept of a runtime context defined by a context manager. This is implemented using a pair of methods that allow user-defined classes to define a runtime context that is entered before the statement body is executed and exited when the statement ends

contextmanager. __enter__[]

Enter the runtime context and return either this object or another object related to the runtime context. The value returned by this method is bound to the identifier in the

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
234 clause of statements using this context manager

An example of a context manager that returns itself is a . File objects return themselves from __enter__[] to allow to be used as the context expression in a statement

An example of a context manager that returns a related object is the one returned by . These managers set the active decimal context to a copy of the original decimal context and then return the copy. This allows changes to be made to the current decimal context in the body of the statement without affecting code outside the

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
081 statement

contextmanager. __exit__[exc_type , exc_val , exc_tb]

Exit the runtime context and return a Boolean flag indicating if any exception that occurred should be suppressed. If an exception occurred while executing the body of the statement, the arguments contain the exception type, value and traceback information. Otherwise, all three arguments are

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
31

Returning a true value from this method will cause the statement to suppress the exception and continue execution with the statement immediately following the

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
081 statement. Otherwise the exception continues propagating after this method has finished executing. Exceptions that occur during execution of this method will replace any exception that occurred in the body of the
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
081 statement

The exception passed in should never be reraised explicitly - instead, this method should return a false value to indicate that the method completed successfully and does not want to suppress the raised exception. This allows context management code to easily detect whether or not an method has actually failed

Python defines several context managers to support easy thread synchronisation, prompt closure of files or other objects, and simpler manipulation of the active decimal arithmetic context. The specific types are not treated specially beyond their implementation of the context management protocol. See the module for some examples

Python’s s and the decorator provide a convenient way to implement these protocols. If a generator function is decorated with the decorator, it will return a context manager implementing the necessary and methods, rather than the iterator produced by an undecorated generator function

Note that there is no specific slot for any of these methods in the type structure for Python objects in the Python/C API. Extension types wanting to define these methods must provide them as a normal Python accessible method. Compared to the overhead of setting up the runtime context, the overhead of a single class dictionary lookup is negligible

Type Annotation Types — ,

The core built-in types for are and

Generic Alias Type

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
252 objects are generally created by a class. They are most often used with , such as or . Ví dụ:
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
255 là một đối tượng
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
252 được tạo bằng cách đăng ký lớp
def bit_count[self]:
    return bin[self].count["1"]
93 với đối số.
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
252 objects are intended primarily for use with

Ghi chú

Nói chung, chỉ có thể đăng ký một lớp nếu lớp đó thực hiện phương thức đặc biệt

A

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
252 object acts as a proxy for a , implementing parameterized generics

For a container class, the argument[s] supplied to a of the class may indicate the type[s] of the elements an object contains. For example,

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
262 can be used in type annotations to signify a in which all the elements are of type

For a class which defines but is not a container, the argument[s] supplied to a subscription of the class will often indicate the return type[s] of one or more methods defined on an object. For example, can be used on both the data type and the data type

  • If

    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
    
    269,
    >>> n = 19
    >>> bin[n]
    '0b10011'
    >>> n.bit_count[]
    3
    >>> [-n].bit_count[]
    3
    
    82 will be a object where the return values of
    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
    
    271 and
    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
    
    272 will both be of type . We can represent this kind of object in type annotations with the
    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
    
    252
    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
    
    275

  • If

    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
    
    276, [note the
    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  6
    
    281 and
    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
    
    282 will both be of type . In type annotations, we would represent this variety of objects with
    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
    
    284

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
252 objects are instances of the class , which can also be used to create
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
252 objects directly

T[X, Y, . ]

Creates a

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
252 representing a type
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
289 parameterized by types X, Y, and more depending on the
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
289 used. For example, a function expecting a containing elements

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
05

Another example for objects, using a , which is a generic type expecting two type parameters representing the key type and the value type. In this example, the function expects a

>>> [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'
68 with keys of type and values of type

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
06

The builtin functions and do not accept

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
252 types for their second argument

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
07

The Python runtime does not enforce . This extends to generic types and their type parameters. When creating a container object from a

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
252, the elements in the container are not checked against their type. For example, the following code is discouraged, but will run without errors

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
08

Furthermore, parameterized generics erase type parameters during object creation

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
09

Calling or on a generic shows the parameterized type

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
10

The method of generic containers will raise an exception to disallow mistakes like

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
304

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
11

However, such expressions are valid when are used. The index must have as many elements as there are type variable items in the

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
252 object’s

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
12

Standard Generic Classes

The following standard library classes support parameterized generics. This list is non-exhaustive

Special Attributes of
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
252 objects

All parameterized generics implement special read-only attributes

genericalias. __origin__

This attribute points at the non-parameterized generic class

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
13

genericalias. __args__

This attribute is a [possibly of length 1] of generic types passed to the original of the generic class

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
14

genericalias. __parameters__

This attribute is a lazily computed tuple [possibly empty] of unique type variables found in

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
306

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
15

Ghi chú

A

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
252 object with parameters may not have correct
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
365 after substitution because is intended primarily for static type checking

genericalias. __unpacked__

A boolean that is true if the alias has been unpacked using the

>>> [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'
00 operator [see ]

New in version 3. 11

Xem thêm

PEP 484 - Type Hints

Giới thiệu khung của Python cho các chú thích loại

PEP 585 - Nhập gợi ý Generics trong bộ sưu tập tiêu chuẩn

Introducing the ability to natively parameterize standard-library classes, provided they implement the special class method

, và

Documentation on how to implement generic classes that can be parameterized at runtime and understood by static type-checkers

Mới trong phiên bản 3. 9

Union Type

A union object holds the value of the

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
371 [bitwise or] operation on multiple . These types are intended primarily for . The union type expression enables cleaner type hinting syntax compared to

X . Y . .

Defines a union object which holds types X, Y, and so forth.

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
373 means either X or Y. It is equivalent to
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
374. For example, the following function expects an argument of type or

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
16

union_object == other

Union objects can be tested for equality with other union objects. Details

  • Unions of unions are flattened

    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
    
    17

  • Redundant types are removed

    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
    
    18

  • When comparing unions, the order is ignored

    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
    
    19

  • It is compatible with

    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
    
    20

  • Optional types can be spelled as a union with

    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
    
    31

    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
    
    21

isinstance[obj, union_object]issubclass[obj, union_object]

Calls to and are also supported with a union object

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
22

However, union objects containing cannot be used

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
23

The user-exposed type for the union object can be accessed from and used for checks. An object cannot be instantiated from the type

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
24

Ghi chú

The

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
383 method for type objects was added to support the syntax
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
373. If a metaclass implements
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
383, the Union may override it

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
25

Xem thêm

PEP 604 – PEP đề xuất cú pháp

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
373 và kiểu Union

Mới trong phiên bản 3. 10

Other Built-in Types

The interpreter supports several other kinds of objects. Most of these support only one or two operations

Modules

The only special operation on a module is attribute access.

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
387, 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 statement is not, strictly speaking, an operation on a module object;
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
389 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 . 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 attribute is not possible [you can write

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
392, which defines
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
393 to be
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
55, but you can’t write
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
395]. Modifying directly is not recommended

Modules built into the interpreter are written like this.

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
397. If loaded from a file, they are written as
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
398

Classes and Class Instances

See and for these

Functions

Function objects are created by function definitions. The only operation on a function object is to call it.

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
399

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

See for more information

Methods

Methods are functions that are called using the attribute notation. There are two flavors. built-in methods [such as

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
400 on lists] and class instance methods. 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

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
401 argument to the argument list. Bound methods have two special read-only attributes.
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
402 is the object on which the method operates, and
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
403 is the function implementing the method. Calling
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
404 is completely equivalent to calling
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
405

Like function objects, bound method objects support getting arbitrary attributes. However, since method attributes are actually stored on the underlying function object [

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
406], setting method attributes on bound methods is disallowed. Attempting to set an attribute on a method results in an being raised. In order to set a method attribute, you need to explicitly set it on the underlying function object

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
26

See for more information

Code Objects

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 function and can be extracted from function objects through their

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
409 attribute. See also the module

Accessing

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
409 raises an
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
412 with arguments
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
413 and
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
414

A code object can be executed or evaluated by passing it [instead of a source string] to the or built-in functions

See for more information

Type Objects

Type objects represent the various object types. Loại đối tượng được truy cập bởi chức năng tích hợp. There are no special operations on types. The standard module defines names for all standard built-in types

Types are written like this.

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
419

The Null Object

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

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
31 [a built-in name].
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
421 produces the same singleton

It is written as

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
31

Đối tượng Dấu chấm lửng

This object is commonly used by slicing [see ]. Nó không hỗ trợ các hoạt động đặc biệt. Có chính xác một đối tượng dấu chấm lửng, được đặt tên [tên tích hợp].

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
424 produces the singleton

It is written as

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
423 or
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
427

The NotImplemented Object

This object is returned from comparisons and binary operations when they are asked to operate on types they don’t support. See for more information. There is exactly one

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
428 object.
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
429 produces the singleton instance

It is written as

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
428

Boolean Values

Boolean values are the two constant objects

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
38 and
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
56. They are used to represent truth values [although other values can also be considered false or true]. In numeric contexts [for example when used as the argument to an arithmetic operator], they behave like the integers 0 and 1, respectively. The built-in function can be used to convert any value to a Boolean, if the value can be interpreted as a truth value [see section above]

They are written as

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
38 and
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
56, respectively

Internal Objects

See for this information. It describes stack frame objects, traceback objects, and slice objects

Special Attributes

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 built-in function

object. __dict__

A dictionary or other mapping object used to store an object’s [writable] attributes

instance. __class__

The class to which a class instance belongs

class. __bases__

The tuple of base classes of a class object

definition. __name__

The name of the class, function, method, descriptor, or generator instance

definition. __qualname__

The of the class, function, method, descriptor, or generator instance

Mới trong phiên bản 3. 3

class. __mro__

This attribute is a tuple of classes that are considered when looking for base classes during method resolution

class. mro[]

This method can be overridden by a metaclass to customize the method resolution order for its instances. It is called at class instantiation, and its result is stored in

class. __subclasses__[]

Each class keeps a list of weak references to its immediate subclasses. This method returns a list of all those references still alive. The list is in definition order. Example

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
27

Giới hạn độ dài chuyển đổi chuỗi số nguyên

CPython has a global limit for converting between and 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 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

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
441 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 is raised

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
28

The default limit is 4300 digits as provided in . The lowest limit that can be configured is 640 digits as provided in

Verification

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
29

New in version 3. 11

Affected APIs

The limitation only applies to potentially slow conversions between and or

  • 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
    
    448 with default base 10

  • 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
    
    449 for all bases that are not a power of 2

  • 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
    
    450

  • 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
    
    451

  • any other string conversion to base 10, for example

    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
    
    452,
    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
    
    453, or
    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
    
    454

The limitations do not apply to functions with a linear algorithm

  • 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
    
    449 with base 2, 4, 8, 16, or 32

  • and

  • , ,

  • for hex, octal, and binary numbers

  • to

  • to

Configuring the limit

Before Python starts up you can use an environment variable or an interpreter command line flag to configure the limit

  • , e. g.

    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
    
    466 to set the limit to 640 or
    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
    
    467 to disable the limitation

  • , e. g.

    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
    
    469

  • 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
    
    470 contains the value of or . If both the env var and the
    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
    
    473 option are set, the
    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
    
    473 option takes precedence. A value of -1 indicates that both were unset, thus a value of
    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
    
    443 was used during initialization

Từ mã, bạn có thể kiểm tra giới hạn hiện tại và đặt giới hạn mới bằng các API này

  • và là một getter và setter cho giới hạn trên toàn trình thông dịch. Phiên dịch viên phụ có giới hạn riêng của họ

Thông tin về mặc định và tối thiểu có thể được tìm thấy trong

  • là giới hạn mặc định được biên dịch

  • là giá trị thấp nhất được chấp nhận cho giới hạn [khác 0 sẽ vô hiệu hóa giới hạn đó]

New in version 3. 11

thận trọng

Đặt giới hạn thấp có thể dẫn đến sự cố. Mặc dù hiếm gặp, mã tồn tại chứa các hằng số nguyên ở dạng thập phân trong nguồn của chúng vượt quá ngưỡng tối thiểu. Hậu quả của việc đặt giới hạn là mã nguồn Python chứa các số nguyên thập phân dài hơn giới hạn sẽ gặp lỗi trong quá trình phân tích cú pháp, thường là tại thời điểm khởi động hoặc thời điểm nhập hoặc thậm chí tại thời điểm cài đặt - bất kỳ lúc nào bản cập nhật

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
482 chưa tồn tại cho . Một giải pháp thay thế cho nguồn chứa các hằng số lớn như vậy là chuyển đổi chúng sang dạng thập lục phân
def bit_count[self]:
    return bin[self].count["1"]
12 vì nó không có giới hạn

Kiểm tra ứng dụng của bạn kỹ lưỡng nếu bạn sử dụng giới hạn thấp. Đảm bảo các thử nghiệm của bạn chạy với giới hạn được đặt sớm thông qua môi trường hoặc cờ để nó áp dụng trong quá trình khởi động và thậm chí trong bất kỳ bước cài đặt nào có thể gọi Python để biên dịch trước các nguồn

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
484 thành tệp
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
482

Cấu hình đề xuất

Giá trị mặc định

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
443 dự kiến ​​sẽ hợp lý cho hầu hết các ứng dụng. Nếu ứng dụng của bạn yêu cầu một giới hạn khác, hãy đặt giới hạn đó từ điểm vào chính của bạn bằng cách sử dụng mã bất khả tri của phiên bản Python vì các API này đã được thêm vào trong các bản phát hành bản vá bảo mật trong các phiên bản trước 3. 11

Thí dụ

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
30

Nếu bạn cần tắt hoàn toàn, hãy đặt thành

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
42

chú thích

Thông tin bổ sung về các phương pháp đặc biệt này có thể được tìm thấy trong Python Reference Manual []

Kết quả là, danh sách

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
488 được coi là bằng với
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
489, và tương tự đối với các bộ dữ liệu

Chúng phải có vì trình phân tích cú pháp không thể cho biết loại toán hạng

4[,,,]

Các ký tự viết hoa là những ký tự có thuộc tính danh mục chung là một trong số “Lu” [Chữ cái, chữ hoa], “Ll” [Chữ cái, chữ thường] hoặc “Lt” [Chữ cái, chữ hoa tiêu đề]

5[,]

Do đó, để chỉ định dạng một bộ dữ liệu, bạn nên cung cấp một bộ dữ liệu đơn có phần tử duy nhất là bộ dữ liệu được định dạng

Kiểu trong kiểu dữ liệu là gì?

Kiểu dữ liệu, trong lập trình, là phân loại xác định loại giá trị mà một biến có và loại phép toán, quan hệ hoặc logic nào có thể được áp dụng cho nó mà không gây ra . .

5 kiểu dữ liệu trong Python là gì?

Python có 5 kiểu dữ liệu tiêu chuẩn. .
Số
Chuỗi
Tuple
Từ điển

3 loại dữ liệu trong Python là gì?

Bạn sẽ tìm hiểu về một số loại số, chuỗi và Boolean cơ bản được tích hợp sẵn trong Python.

3 kiểu dữ liệu là gì?

Hầu hết các ngôn ngữ lập trình đều hỗ trợ các kiểu dữ liệu cơ bản của số nguyên [có kích thước khác nhau], số dấu phẩy động [xấp xỉ số thực], ký tự và Booleans.

Chủ Đề