Python dict ke format string

Beberapa kelas koleksi bisa berubah. Metode yang menambah, mengurangi, atau mengatur ulang anggotanya pada tempatnya, dan tidak mengembalikan item tertentu, tidak pernah mengembalikan instance koleksi itu sendiri tetapi

def bit_length[self]:
    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

Beberapa operasi didukung oleh beberapa tipe objek; . Fungsi yang terakhir secara implisit digunakan ketika sebuah objek ditulis oleh fungsi tersebut

Pengujian Nilai Kebenaran

Objek apa pun dapat diuji untuk nilai kebenaran, untuk digunakan dalam kondisi atau atau sebagai operan dari operasi Boolean di bawah ini

Secara default, sebuah objek dianggap benar kecuali kelasnya mendefinisikan metode

def bit_length[self]:
    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 yang mengembalikan
def bit_length[self]:
    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 atau metode
def bit_length[self]:
    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 yang mengembalikan nol, saat dipanggil dengan objek. Berikut adalah sebagian besar objek bawaan yang dianggap salah

  • konstanta yang didefinisikan sebagai salah.

    def bit_length[self]:
        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 dan
    def bit_length[self]:
        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

  • nol dari jenis numerik apa pun.

    def bit_length[self]:
        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

  • urutan dan koleksi kosong.

    def bit_length[self]:
        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

Operasi dan fungsi bawaan yang memiliki hasil Boolean selalu mengembalikan

def bit_length[self]:
    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 atau
def bit_length[self]:
    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 untuk false dan
def bit_length[self]:
    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 atau
def bit_length[self]:
    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 untuk true, kecuali dinyatakan lain. [Pengecualian penting. operasi 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 dan
def bit_length[self]:
    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 selalu mengembalikan salah satu operannya. ]

Operasi 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

Ini adalah operasi Boolean, diurutkan berdasarkan prioritas menaik

Operasi

Hasil

Catatan

def bit_length[self]:
    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

jika x salah, maka y, selain itu 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

jika x salah, maka x, jika tidak 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

jika x salah, maka

def bit_length[self]:
    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, selain itu
def bit_length[self]:
    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]

Catatan

  1. Ini adalah operator hubung singkat, sehingga hanya mengevaluasi argumen kedua jika yang pertama salah

  2. Ini adalah operator hubung singkat, sehingga hanya mengevaluasi argumen kedua jika yang pertama benar

  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 memiliki prioritas lebih rendah daripada operator non-Boolean, jadi
    def bit_length[self]:
        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 ditafsirkan sebagai
    def bit_length[self]:
        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, dan
    def bit_length[self]:
        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 adalah kesalahan sintaksis

Perbandingan

Ada delapan operasi perbandingan di Python. Mereka semua memiliki prioritas yang sama [yang lebih tinggi daripada operasi Boolean]. Perbandingan dapat dirantai secara acak;

Tabel ini merangkum operasi perbandingan

Operasi

Arti

def bit_length[self]:
    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

ketat kurang dari

def bit_length[self]:
    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

kurang dari atau sama

def bit_length[self]:
    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

ketat lebih besar dari

def bit_length[self]:
    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

lebih besar atau sama

def bit_length[self]:
    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

setara

def bit_length[self]:
    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

tidak sama

def bit_length[self]:
    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

identitas objek

def bit_length[self]:
    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

identitas objek yang dinegasikan

Objek dari tipe yang berbeda, kecuali tipe numerik yang berbeda, tidak pernah sebanding. Operator

def bit_length[self]:
    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 selalu didefinisikan tetapi untuk beberapa tipe objek [misalnya, objek kelas] setara dengan. Operator
def bit_length[self]:
    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 dan
def bit_length[self]:
    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 hanya didefinisikan jika masuk akal;

Contoh kelas yang tidak identik biasanya dibandingkan sebagai tidak sama kecuali kelas tersebut mendefinisikan metodenya

Instance suatu kelas tidak dapat diurutkan sehubungan dengan instance lain dari kelas yang sama, atau jenis objek lain, kecuali jika kelas tersebut cukup mendefinisikan metode , , , dan [secara umum, dan cukup, jika Anda menginginkan arti konvensional dari

Perilaku dan operator tidak dapat disesuaikan;

Dua operasi lagi dengan prioritas sintaksis yang sama, dan , didukung oleh tipe yang mengimplementasikan metode

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

Jenis Numerik — , ,

Ada tiga tipe numerik yang berbeda. integers, floating point numbers, and complex numbers. In addition, Booleans are a subtype of integers. Integers have unlimited precision. Floating point numbers are usually implemented using double in C; information about the precision and internal representation of floating point numbers for the machine on which your program is running is available in . Complex numbers have a real and imaginary part, which are each a floating point number. To extract these parts from a complex number z, use

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
05 and
>>> 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. ]

Numbers are created by numeric literals or as the result of built-in functions and operators. Unadorned integer literals [including hex, octal and binary numbers] yield integers. Numeric literals containing a decimal point or an exponent sign yield floating point numbers. Appending

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
09 or
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
10 to a numeric literal yields an imaginary number [a complex number with a zero real part] which you can add to an integer or float to get a complex number with real and imaginary parts

Python fully supports mixed arithmetic. when a binary arithmetic operator has operands of different numeric types, the operand with the “narrower” type is widened to that of the other, where integer is narrower than floating point, which is narrower than complex. A comparison between numbers of different types behaves as though the exact values of those numbers were being compared.

The constructors , , and can be used to produce numbers of a specific type

All numeric types [except complex] support the following operations [for priorities of the operations, see ]

Operasi

Hasil

Catatan

Full documentation

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

sum of x and y

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

difference of x and y

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

product of x and y

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

hasil bagi x dan y

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

floored quotient of x and y

[1]

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

remainder of

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

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

x unchanged

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

absolute value or magnitude of x

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

x converted to integer

[3][6]

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

x converted to floating point

[4][6]

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

a complex number with real part re, imaginary part im. im defaults to zero

[6]

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

conjugate of the complex number c

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

the pair

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

[5]

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

x pangkat y

[5]

Catatan

  1. Juga disebut sebagai pembagian bilangan bulat. Nilai yang dihasilkan adalah bilangan bulat utuh, meskipun tipe hasilnya belum tentu int. Hasilnya selalu dibulatkan menuju minus tak terhingga.

    >>> n = 19
    >>> bin[n]
    '0b10011'
    >>> n.bit_count[]
    3
    >>> [-n].bit_count[]
    3
    
    38 adalah
    def bit_length[self]:
        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 = 19
    >>> bin[n]
    '0b10011'
    >>> n.bit_count[]
    3
    >>> [-n].bit_count[]
    3
    
    40 adalah
    >>> n = 19
    >>> bin[n]
    '0b10011'
    >>> n.bit_count[]
    3
    >>> [-n].bit_count[]
    3
    
    41,
    >>> n = 19
    >>> bin[n]
    '0b10011'
    >>> n.bit_count[]
    3
    >>> [-n].bit_count[]
    3
    
    42 adalah
    >>> n = 19
    >>> bin[n]
    '0b10011'
    >>> n.bit_count[]
    3
    >>> [-n].bit_count[]
    3
    
    41, dan
    >>> n = 19
    >>> bin[n]
    '0b10011'
    >>> n.bit_count[]
    3
    >>> [-n].bit_count[]
    3
    
    44 adalah
    def bit_length[self]:
        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

  2. Bukan untuk bilangan kompleks. Alih-alih, konversikan ke pelampung menggunakan jika sesuai

  3. Konversi dari floating point ke bilangan bulat dapat membulatkan atau memotong seperti pada C;

  4. float juga menerima string "nan" dan "inf" dengan awalan opsional "+" atau "-" untuk Bukan Angka [NaN] dan infinity positif atau negatif

  5. Python mendefinisikan

    >>> n = 19
    >>> bin[n]
    '0b10011'
    >>> n.bit_count[]
    3
    >>> [-n].bit_count[]
    3
    
    49 dan
    >>> n = 19
    >>> bin[n]
    '0b10011'
    >>> n.bit_count[]
    3
    >>> [-n].bit_count[]
    3
    
    50 menjadi
    def bit_length[self]:
        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, seperti yang umum untuk bahasa pemrograman

  6. Literal numerik yang diterima mencakup digit

    def bit_length[self]:
        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 hingga
    >>> n = 19
    >>> bin[n]
    '0b10011'
    >>> n.bit_count[]
    3
    >>> [-n].bit_count[]
    3
    
    53 atau Unicode yang setara [poin kode dengan properti
    >>> n = 19
    >>> bin[n]
    '0b10011'
    >>> n.bit_count[]
    3
    >>> [-n].bit_count[]
    3
    
    54]

    Lihat https. // www. unicode. org/Publik/14. 0. 0/ucd/extracted/DerivedNumericType. txt untuk daftar lengkap poin kode dengan properti

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

Semua tipe [ dan ] juga menyertakan operasi berikut

Operasi

Hasil

x dipotong menjadi

x dibulatkan menjadi n digit, dibulatkan setengah menjadi genap. Jika n dihilangkan, defaultnya adalah 0

terbesar = x

For additional numeric operations see the and modules

Bitwise Operations on Integer Types

Bitwise operations only make sense for integers. The result of bitwise operations is calculated as though carried out in two’s complement with an infinite number of sign bits

The priorities of the binary bitwise operations are all lower than the numeric operations and higher than the comparisons; the unary operation

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
68 has the same priority as the other unary numeric operations [
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
69 and
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
70]

Tabel ini mencantumkan operasi bitwise yang diurutkan dalam prioritas menaik

Operasi

Hasil

Catatan

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

bitwise atau dari x dan y

[4]

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

eksklusif bitwise atau dari x dan y

[4]

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

bitwise dan dari x dan y

[4]

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

x digeser ke kiri sebanyak n bit

[1][2]

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

x digeser ke kanan sebanyak n bit

[1][3]

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

bit x terbalik

Catatan

  1. Hitungan shift negatif adalah ilegal dan menyebabkan a dinaikkan

  2. Pergeseran ke kiri sebesar n bit sama dengan perkalian dengan

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

  3. Pergeseran ke kanan sebanyak n bit sama dengan pembagian lantai oleh

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

  4. Melakukan perhitungan ini dengan setidaknya satu bit ekstensi tanda tambahan dalam representasi komplemen dua hingga [lebar bit kerja

    >>> n = 19
    >>> bin[n]
    '0b10011'
    >>> n.bit_count[]
    3
    >>> [-n].bit_count[]
    3
    
    80 atau lebih] cukup untuk mendapatkan hasil yang sama seolah-olah ada jumlah bit tanda yang tak terbatas

Metode Tambahan pada Tipe Integer

Tipe int mengimplementasikan. Selain itu, ini menyediakan beberapa metode lagi

int. bit_length[]

Kembalikan jumlah bit yang diperlukan untuk mewakili bilangan bulat dalam biner, tidak termasuk tanda dan angka nol di depan

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

Lebih tepatnya, jika

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
82 bukan nol, maka
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
83 adalah bilangan bulat positif unik
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
84 sehingga
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
85. Sama halnya, ketika
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
_23 cukup kecil untuk memiliki logaritma yang dibulatkan dengan benar, maka
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
87. Jika
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
_82 adalah nol, maka ________51______83 mengembalikan
def bit_length[self]:
    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

Setara dengan

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

Baru di versi 3. 1

int. bit_count[]

Kembalikan jumlah satu dalam representasi biner dari nilai absolut bilangan bulat. Ini juga dikenal sebagai jumlah populasi. Contoh

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

Setara dengan

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

Baru di versi 3. 10

int. to_bytes[panjang=1, byteorder='big', *, signed=False]

Mengembalikan array byte yang mewakili bilangan bulat

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

Bilangan bulat direpresentasikan menggunakan byte panjang, dan standarnya adalah 1. An dimunculkan jika bilangan bulat tidak dapat diwakili dengan jumlah byte yang diberikan

Argumen byteorder menentukan urutan byte yang digunakan untuk mewakili bilangan bulat, dan standarnya adalah

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
92. Jika byteorder adalah
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
_92, byte paling signifikan ada di awal array byte. Jika byteorder adalah
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
_94, byte paling signifikan ada di akhir array byte

Argumen yang ditandatangani menentukan apakah komplemen dua digunakan untuk mewakili bilangan bulat. Jika ditandatangani adalah

def bit_length[self]:
    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 dan bilangan bulat negatif diberikan, an dinaikkan. Nilai default untuk ditandatangani adalah
def bit_length[self]:
    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

Nilai default dapat digunakan untuk dengan mudah mengubah bilangan bulat menjadi objek byte tunggal. Namun, saat menggunakan argumen default, jangan mencoba mengonversi nilai yang lebih besar dari 255 atau Anda akan mendapatkan

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

Setara dengan

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]

Baru di versi 3. 2

Berubah di versi 3. 11. Menambahkan nilai argumen default untuk

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

metode kelas int. from_bytes[byte , byteorder='big', *, signed=False]

Kembalikan bilangan bulat yang diwakili oleh larik byte yang diberikan

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

Byte argumen harus berupa byte penghasil a atau iterable

Argumen byteorder menentukan urutan byte yang digunakan untuk mewakili bilangan bulat, dan standarnya adalah

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
92. Jika byteorder adalah
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
_92, byte paling signifikan ada di awal array byte. Jika byteorder adalah
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
_94, byte paling signifikan ada di akhir array byte. Untuk meminta urutan byte asli dari sistem host, gunakan sebagai nilai urutan byte

Argumen yang ditandatangani menunjukkan apakah komplemen dua digunakan untuk mewakili bilangan bulat

Setara dengan

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 jika instance float terbatas dengan nilai integral, dan
def bit_length[self]:
    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 sebaliknya

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

Dua metode mendukung konversi ke dan dari string heksadesimal. Karena pelampung Python disimpan secara internal sebagai bilangan biner, mengonversi pelampung ke atau dari string desimal biasanya melibatkan kesalahan pembulatan kecil. Sebaliknya, string heksadesimal memungkinkan representasi yang tepat dan spesifikasi angka floating-point. Ini dapat berguna saat melakukan debug, dan dalam pekerjaan numerik

mengambang. hex[]

Mengembalikan representasi angka floating-point sebagai string heksadesimal. Untuk bilangan floating-point terbatas, representasi ini akan selalu menyertakan

def bit_count[self]:
    return bin[self].count["1"]
12 di depan dan
def bit_count[self]:
    return bin[self].count["1"]
13 di belakang dan eksponen

metode kelas float. fromhex[s]

Metode kelas untuk mengembalikan float yang diwakili oleh string heksadesimal s. String s mungkin memiliki spasi putih di depan dan di belakang

Perhatikan bahwa itu adalah metode instan, sementara itu adalah metode kelas

Sebuah string heksadesimal mengambil bentuk

def bit_length[self]:
    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

di mana

def bit_count[self]:
    return bin[self].count["1"]
16 opsional dapat dengan ________51______69 atau
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
70,
def bit_count[self]:
    return bin[self].count["1"]
19 dan
def bit_count[self]:
    return bin[self].count["1"]
20 adalah string digit heksadesimal, dan
def bit_count[self]:
    return bin[self].count["1"]
21 adalah bilangan bulat desimal dengan tanda awal opsional. Huruf besar kecil tidak signifikan, dan harus ada setidaknya satu digit heksadesimal baik dalam bilangan bulat maupun pecahan. Sintaks ini mirip dengan sintaks yang ditentukan di bagian 6. 4. 4. 2 dari standar C99, dan juga sintaks yang digunakan di Java 1. 5 dan seterusnya. Secara khusus, output dari dapat digunakan sebagai literal floating-point heksadesimal dalam kode C atau Java, dan string heksadesimal yang dihasilkan oleh karakter format
def bit_count[self]:
    return bin[self].count["1"]
23 C atau
def bit_count[self]:
    return bin[self].count["1"]
24 Java diterima oleh

Perhatikan bahwa eksponen ditulis dalam desimal dan bukan heksadesimal, dan memberikan pangkat 2 untuk mengalikan koefisien. Misalnya, string heksadesimal

def bit_count[self]:
    return bin[self].count["1"]
26 mewakili bilangan floating-point
def bit_count[self]:
    return bin[self].count["1"]
27, atau
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

Menerapkan konversi terbalik ke

def bit_count[self]:
    return bin[self].count["1"]
_28 memberikan string heksadesimal berbeda yang mewakili angka yang sama

def bit_length[self]:
    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 tipe numerik

Untuk nomor

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
82 dan
def bit_count[self]:
    return bin[self].count["1"]
31, mungkin dari jenis yang berbeda, itu adalah persyaratan bahwa
def bit_count[self]:
    return bin[self].count["1"]
32 setiap kali
def bit_count[self]:
    return bin[self].count["1"]
33 [lihat dokumentasi metode untuk detail lebih lanjut]. Untuk kemudahan implementasi dan efisiensi di berbagai tipe numerik [termasuk , , dan ] hash Python untuk tipe numerik didasarkan pada fungsi matematika tunggal yang ditentukan untuk bilangan rasional apa pun, dan karenanya berlaku untuk semua instance dari and , dan semua instance terbatas . Pada dasarnya, fungsi ini diberikan oleh modulo reduksi
def bit_count[self]:
    return bin[self].count["1"]
43 untuk bilangan prima tetap
def bit_count[self]:
    return bin[self].count["1"]
43. Nilai
def bit_count[self]:
    return bin[self].count["1"]
_43 disediakan untuk Python sebagai atribut
def bit_count[self]:
    return bin[self].count["1"]
46 dari

Detail implementasi CPython. Saat ini, bilangan prima yang digunakan adalah

def bit_count[self]:
    return bin[self].count["1"]
_48 pada mesin dengan long C 32-bit dan
def bit_count[self]:
    return bin[self].count["1"]
49 pada mesin dengan long C 64-bit

Berikut aturannya secara detail

  • Jika

    def bit_count[self]:
        return bin[self].count["1"]
    
    _50 adalah bilangan rasional tak negatif dan
    def bit_count[self]:
        return bin[self].count["1"]
    
    _51 tidak habis dibagi
    def bit_count[self]:
        return bin[self].count["1"]
    
    43, tentukan
    def bit_count[self]:
        return bin[self].count["1"]
    
    53 sebagai
    def bit_count[self]:
        return bin[self].count["1"]
    
    54, di mana
    def bit_count[self]:
        return bin[self].count["1"]
    
    55 memberikan kebalikan dari
    def bit_count[self]:
        return bin[self].count["1"]
    
    5111o _______55

  • Jika

    def bit_count[self]:
        return bin[self].count["1"]
    
    50 adalah bilangan rasional nonnegatif dan
    def bit_count[self]:
        return bin[self].count["1"]
    
    _51 habis dibagi
    def bit_count[self]:
        return bin[self].count["1"]
    
    43 [tetapi
    def bit_count[self]:
        return bin[self].count["1"]
    
    61 bukan] maka
    def bit_count[self]:
        return bin[self].count["1"]
    
    51 tidak memiliki modulo terbalik
    def bit_count[self]:
        return bin[self].count["1"]
    
    43 dan aturan di atas tidak berlaku;

  • Jika

    def bit_count[self]:
        return bin[self].count["1"]
    
    _50 adalah bilangan rasional negatif, tentukan
    def bit_count[self]:
        return bin[self].count["1"]
    
    53 sebagai
    def bit_count[self]:
        return bin[self].count["1"]
    
    68. Jika hash yang dihasilkan adalah
    >>> n = 19
    >>> bin[n]
    '0b10011'
    >>> n.bit_count[]
    3
    >>> [-n].bit_count[]
    3
    
    _41, ganti dengan
    def bit_count[self]:
        return bin[self].count["1"]
    
    _70

  • Nilai tertentu

    def bit_count[self]:
        return bin[self].count["1"]
    
    65 dan
    def bit_count[self]:
        return bin[self].count["1"]
    
    72 digunakan sebagai nilai hash untuk infinity positif atau infinity negatif [masing-masing]

  • Untuk angka

    def bit_count[self]:
        return bin[self].count["1"]
    
    74, nilai hash dari bagian nyata dan imajiner digabungkan dengan menghitung
    def bit_count[self]:
        return bin[self].count["1"]
    
    75, mengurangi modulo
    def bit_count[self]:
        return bin[self].count["1"]
    
    76 sehingga terletak di
    def bit_count[self]:
        return bin[self].count["1"]
    
    77. Sekali lagi, jika hasilnya
    >>> n = 19
    >>> bin[n]
    '0b10011'
    >>> n.bit_count[]
    3
    >>> [-n].bit_count[]
    3
    
    _41, diganti dengan
    def bit_count[self]:
        return bin[self].count["1"]
    
    70

Untuk memperjelas aturan di atas, berikut adalah beberapa contoh kode Python, yang setara dengan hash bawaan, untuk menghitung hash bilangan rasional, , atau

def bit_length[self]:
    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

Jenis Iterator

Python mendukung konsep iterasi melalui kontainer. Ini diimplementasikan menggunakan dua metode berbeda; . Urutan, dijelaskan di bawah ini secara lebih rinci, selalu mendukung metode iterasi

Salah satu metode perlu didefinisikan untuk objek wadah untuk memberikan dukungan

wadah. __iter__[]

Mengembalikan objek. Objek diperlukan untuk mendukung protokol iterator yang dijelaskan di bawah ini. Jika wadah mendukung jenis iterasi yang berbeda, metode tambahan dapat disediakan untuk secara khusus meminta iterator untuk jenis iterasi tersebut. [Contoh objek yang mendukung berbagai bentuk iterasi adalah struktur pohon yang mendukung traversal pertama lebar dan kedalaman pertama. ] Metode ini sesuai dengan slot struktur tipe untuk objek Python di Python/C API

Objek iterator itu sendiri diperlukan untuk mendukung dua metode berikut, yang bersama-sama membentuk protokol iterator

iterator. __iter__[]

Kembalikan objek itu sendiri. Ini diperlukan agar container dan iterator dapat digunakan dengan pernyataan and. Metode ini sesuai dengan slot struktur tipe untuk objek Python di Python/C API

iterator. __selanjutnya__[]

Mengembalikan item berikutnya dari. Jika tidak ada item lebih lanjut, ajukan pengecualian. Metode ini sesuai dengan slot struktur tipe untuk objek Python di Python/C API

Python mendefinisikan beberapa objek iterator untuk mendukung iterasi pada tipe urutan umum dan spesifik, kamus, dan bentuk lain yang lebih khusus. Jenis spesifik tidak penting di luar penerapan protokol iterator

Setelah metode iterator raise , metode tersebut harus terus melakukannya pada panggilan berikutnya. Implementasi yang tidak mematuhi properti ini dianggap rusak

Jenis Pembangkit

Python menyediakan cara mudah untuk mengimplementasikan protokol iterator. Jika metode

def bit_count[self]:
    return bin[self].count["1"]
_90 objek kontainer diimplementasikan sebagai generator, ia akan secara otomatis mengembalikan objek iterator [secara teknis, objek generator] yang memasok
def bit_count[self]:
    return bin[self].count["1"]
90 dan metode. Informasi lebih lanjut tentang generator dapat ditemukan di

Jenis Urutan — , ,

Ada tiga jenis urutan dasar. list, tuple, dan range objek. Jenis urutan tambahan yang disesuaikan untuk pemrosesan dan dijelaskan dalam bagian khusus

Operasi Urutan Umum

Operasi dalam tabel berikut ini didukung oleh sebagian besar tipe urutan, baik yang dapat diubah maupun yang tidak dapat diubah. ABC disediakan untuk mempermudah penerapan operasi ini dengan benar pada tipe urutan kustom

Tabel ini mencantumkan operasi urutan yang diurutkan dalam prioritas menaik. Dalam tabel, s dan t adalah urutan dari tipe yang sama, n, i, j dan k adalah bilangan bulat dan x adalah objek arbitrer yang memenuhi batasan tipe dan nilai apa pun yang diberlakukan oleh s

Operasi

def bit_length[self]:
    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 dan
def bit_length[self]:
    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 memiliki prioritas yang sama dengan operasi pembanding. Operasi
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
_69 [penggabungan] dan
>>> [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 [pengulangan] memiliki prioritas yang sama dengan operasi numerik yang sesuai.

Operasi

Hasil

Catatan

>>> [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 jika item s sama dengan x, jika tidak
def bit_length[self]:
    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 jika item s sama dengan x, jika tidak
def bit_length[self]:
    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

gabungan dari s dan 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 atau
>>> [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

setara dengan menambahkan s ke dirinya sendiri sebanyak n kali

[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

item ke-i dari s, asal 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

potongan s dari i ke 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

potongan s dari i ke j dengan langkah 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

panjang 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

item terkecil dari 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

item terbesar dari 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

indeks kemunculan pertama x dalam s [pada atau setelah indeks i dan sebelum indeks j]

[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

jumlah total kemunculan x dalam s

Urutan dari jenis yang sama juga mendukung perbandingan. Secara khusus, tupel dan daftar dibandingkan secara leksikografis dengan membandingkan elemen yang sesuai. Ini berarti bahwa untuk membandingkan sama, setiap elemen harus membandingkan sama dan dua urutan harus dari jenis yang sama dan memiliki panjang yang sama. [Untuk perincian lengkap lihat di referensi bahasa. ]

Meneruskan dan membalikkan iterator melalui nilai akses urutan yang dapat diubah menggunakan indeks. Indeks itu akan terus bergerak maju [atau mundur] bahkan jika urutan yang mendasarinya dimutasi. Iterator berakhir hanya ketika atau ditemui [atau ketika indeks turun di bawah nol]

Catatan

  1. Sementara operasi

    def bit_length[self]:
        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 dan
    def bit_length[self]:
        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 hanya digunakan untuk pengujian penahanan sederhana dalam kasus umum, beberapa urutan khusus [seperti , dan ] juga menggunakannya untuk pengujian selanjutnya

    def bit_length[self]:
        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. Nilai n kurang dari

    def bit_length[self]:
        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 diperlakukan sebagai
    def bit_length[self]:
        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 [yang menghasilkan urutan kosong dari tipe yang sama dengan s]. Perhatikan bahwa item dalam urutan s tidak disalin; . Ini sering menghantui programmer Python baru;

    def bit_length[self]:
        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

    Apa yang terjadi adalah

    >>> [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 adalah daftar satu elemen yang berisi daftar kosong, jadi ketiga elemen dari
    >>> [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 adalah referensi ke daftar kosong tunggal ini. Memodifikasi salah satu elemen
    >>> [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 mengubah daftar tunggal ini. Anda dapat membuat daftar daftar yang berbeda dengan cara ini

    def bit_length[self]:
        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

    Penjelasan lebih lanjut tersedia di entri FAQ

  3. Jika i atau j negatif, indeks relatif terhadap akhir urutan 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 atau
    >>> [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 diganti. Tapi perhatikan bahwa
    >>> [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 masih
    def bit_length[self]:
        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. Irisan s dari i ke j didefinisikan sebagai urutan item dengan indeks k sehingga

    >>> [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. Jika i atau j lebih besar dari
    >>> [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, gunakan
    >>> [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. Jika saya dihilangkan atau
    def bit_length[self]:
        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, gunakan
    def bit_length[self]:
        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. Jika j dihilangkan atau
    def bit_length[self]:
        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, gunakan
    >>> [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. Jika i lebih besar dari atau sama dengan j, potongan tersebut kosong

  5. Irisan s dari i ke j dengan langkah k didefinisikan sebagai urutan item dengan indeks

    >>> [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 sehingga
    >>> [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. Dengan kata lain, indeksnya adalah
    >>> [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 dan seterusnya, berhenti ketika j tercapai [tetapi tidak pernah termasuk j]. Ketika k positif, i dan j direduksi menjadi
    >>> [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 jika lebih besar. Ketika k negatif, i dan j direduksi menjadi
    >>> [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 jika lebih besar. Jika i atau j dihilangkan atau
    def bit_length[self]:
        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, mereka menjadi nilai "akhir" [akhir yang bergantung pada tanda k]. Catatan, k tidak boleh nol. Jika k adalah
    def bit_length[self]:
        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, diperlakukan seperti
    def bit_length[self]:
        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. Menggabungkan urutan yang tidak dapat diubah selalu menghasilkan objek baru. Ini berarti bahwa membangun urutan dengan rangkaian berulang akan memiliki biaya waktu proses kuadrat dalam total panjang urutan. Untuk mendapatkan biaya runtime linier, Anda harus beralih ke salah satu alternatif di bawah ini

    • jika menggabungkan objek, Anda dapat membuat daftar dan menggunakan di bagian akhir atau menulis ke instance dan mengambil nilainya setelah selesai

    • jika menggabungkan objek, Anda juga dapat menggunakan or , atau Anda dapat melakukan penggabungan di tempat dengan objek. objek bisa berubah dan memiliki mekanisme alokasi berlebihan yang efisien

    • jika menggabungkan objek, perpanjang a sebagai gantinya

    • untuk tipe lain, selidiki dokumentasi kelas yang relevan

  7. Beberapa jenis urutan [seperti ] hanya mendukung urutan item yang mengikuti pola tertentu, dan karenanya tidak mendukung penggabungan atau pengulangan urutan

  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 muncul ketika x tidak ditemukan di s. Tidak semua implementasi mendukung penyampaian argumen tambahan i dan j. Argumen ini memungkinkan pencarian subbagian urutan secara efisien. Melewati argumen tambahan kira-kira setara dengan menggunakan
    >>> [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, hanya tanpa menyalin data apa pun dan dengan indeks yang dikembalikan relatif terhadap awal urutan daripada awal irisan

Jenis Urutan yang Tidak Dapat Diubah

Satu-satunya operasi yang umumnya diterapkan oleh tipe urutan yang tidak dapat diubah yang tidak juga diterapkan oleh tipe urutan yang dapat diubah adalah dukungan untuk built-in

Dukungan ini memungkinkan urutan yang tidak dapat diubah, seperti instans, untuk digunakan sebagai kunci dan disimpan di dalam dan instans

Mencoba untuk mem-hash urutan yang tidak dapat diubah yang berisi nilai yang tidak dapat di-hash akan menghasilkan

Jenis Urutan yang Dapat Diubah

Operasi dalam tabel berikut ditentukan pada jenis urutan yang dapat diubah. ABC disediakan untuk mempermudah penerapan operasi ini dengan benar pada tipe urutan kustom

Dalam tabel s adalah turunan dari tipe urutan yang dapat diubah, t adalah objek yang dapat diubah dan x adalah objek arbitrer yang memenuhi batasan tipe dan nilai apa pun yang diberlakukan oleh s [misalnya, hanya menerima bilangan bulat yang memenuhi batasan nilai

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

Operasi

Hasil

Catatan

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

butir i dari s diganti dengan 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

potongan s dari i ke j diganti dengan isi dari 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

sama dengan

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

elemen dari

>>> [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 diganti dengan 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

menghapus elemen

>>> [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 dari daftar

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

menambahkan x ke akhir urutan [sama seperti

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

menghapus semua item dari s [sama seperti

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

membuat salinan s yang dangkal [sama seperti

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

meluas s dengan isi t [sebagian besar sama dengan

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

perbarui s dengan isinya diulang n kali

[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

menyisipkan x ke s pada indeks yang diberikan oleh i [sama seperti

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

mengambil item di i dan juga menghapusnya dari 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

hapus item pertama dari s di mana

>>> [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 sama dengan 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

membalikkan item s di tempat

[4]

Catatan

  1. t harus memiliki panjang yang sama dengan irisan yang diganti

  2. Argumen opsional saya default ke

    >>> n = 19
    >>> bin[n]
    '0b10011'
    >>> n.bit_count[]
    3
    >>> [-n].bit_count[]
    3
    
    41, sehingga secara default item terakhir dihapus dan dikembalikan

  3. >>> [65].to_bytes[]
    b'A'
    
    _01 muncul ketika x tidak ditemukan di s

  4. Metode

    >>> [65].to_bytes[]
    b'A'
    
    _03 memodifikasi urutan di tempat untuk penghematan ruang saat membalikkan urutan besar. Untuk mengingatkan pengguna bahwa itu beroperasi dengan efek samping, itu tidak mengembalikan urutan terbalik

  5. >>> [65].to_bytes[]
    b'A'
    
    _04 dan
    >>> [65].to_bytes[]
    b'A'
    
    05 disertakan untuk konsistensi dengan antarmuka wadah yang dapat berubah yang tidak mendukung operasi pemotongan [seperti dan ].
    >>> [65].to_bytes[]
    b'A'
    
    _05 bukan bagian dari ABC, tetapi sebagian besar kelas urutan konkrit yang dapat diubah menyediakannya

    Baru di versi 3. 3.

    >>> [65].to_bytes[]
    b'A'
    
    04 dan
    >>> [65].to_bytes[]
    b'A'
    
    05 metode.

  6. Nilai n adalah bilangan bulat, atau implementasi objek. Nilai nol dan negatif dari n menghapus urutan. 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

Daftar

Daftar adalah urutan yang dapat diubah, biasanya digunakan untuk menyimpan koleksi item yang homogen [di mana tingkat kesamaan yang tepat akan bervariasi berdasarkan aplikasi]

kelas daftar[[dapat diubah]]

Daftar dapat dibangun dalam beberapa cara

  • Menggunakan sepasang tanda kurung siku untuk menunjukkan daftar kosong.

    def bit_length[self]:
        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

Banyak operasi lain juga menghasilkan daftar, termasuk bawaan

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

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]

accepts two arguments that can only be passed by keyword []

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]. The key corresponding to each item in the list is calculated once and then used for the entire sorting process. 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

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

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

For sorting examples and a brief sorting tutorial, see

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

Tuples

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

class tuple[[iterable]]

Tuples may be constructed in a number of ways

  • Using a pair of parentheses to denote the empty tuple.

    def bit_length[self]:
        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

  • Using a trailing comma for a singleton tuple.

    >>> [65].to_bytes[]
    b'A'
    
    40 or
    >>> [65].to_bytes[]
    b'A'
    
    41

  • Separating items with commas.

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

  • Using the built-in.

    >>> [65].to_bytes[]
    b'A'
    
    44 or
    >>> [65].to_bytes[]
    b'A'
    
    46

The constructor builds a tuple whose items are the same and in the same order as iterable’s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a tuple, it is returned unchanged. For example,

>>> [65].to_bytes[]
b'A'
47 returns
>>> [65].to_bytes[]
b'A'
48 and
>>> [65].to_bytes[]
b'A'
49 returns
>>> [65].to_bytes[]
b'A'
50. If no argument is given, the constructor creates a new empty tuple,
def bit_length[self]:
    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

Note that it is actually the comma which makes a tuple, not the parentheses. The parentheses are optional, except in the empty tuple case, or when they are needed to avoid syntactic ambiguity. For example,

>>> [65].to_bytes[]
b'A'
52 is a function call with three arguments, while
>>> [65].to_bytes[]
b'A'
53 is a function call with a 3-tuple as the sole argument

Tuples implement all of the sequence operations

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

Ranges

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

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

The arguments to the range constructor must be integers [either built-in or any object that implements the special method]. If the step argument is omitted, 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
55. If the start argument is omitted, 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
42. If step is zero, is raised

For a positive step, the contents of a range

>>> [65].to_bytes[]
b'A'
62 are determined by the formula
>>> [65].to_bytes[]
b'A'
63 where
>>> [65].to_bytes[]
b'A'
64 and
>>> [65].to_bytes[]
b'A'
65

For a negative step, the contents of the range are still determined by the formula

>>> [65].to_bytes[]
b'A'
63, but the constraints are
>>> [65].to_bytes[]
b'A'
64 and
>>> [65].to_bytes[]
b'A'
68

A range object will be empty if

>>> [65].to_bytes[]
b'A'
69 does not meet the value constraint. Ranges do support negative indices, but these are interpreted as indexing from the end of the sequence determined by the positive indices

Ranges containing absolute values larger than are permitted but some features [such as ] may raise

Range examples

def bit_length[self]:
    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

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

start

The value of the start parameter [or

def bit_length[self]:
    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 the parameter was not supplied]

stop

The value of the stop parameter

step

The value of the step parameter [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
55 if the parameter was not supplied]

The advantage of the type over a regular or is that a object will always take the same [small] amount of memory, no matter the size of the range it represents [as it only stores the

>>> [65].to_bytes[]
b'A'
79,
>>> [65].to_bytes[]
b'A'
80 and
>>> [65].to_bytes[]
b'A'
81 values, calculating individual items and subranges as needed]

Range objects implement the ABC, and provide features such as containment tests, element index lookup, slicing and support for negative indices [see ]

def bit_length[self]:
    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

Menguji objek rentang untuk kesetaraan dengan

def bit_length[self]:
    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 dan
def bit_length[self]:
    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 membandingkannya sebagai urutan. That is, two range objects are considered equal if they represent the same sequence of values. [Note that two range objects that compare equal might have different , and attributes, for example
>>> [65].to_bytes[]
b'A'
88 or
>>> [65].to_bytes[]
b'A'
89. ]

Changed in version 3. 2. Implement the Sequence ABC. Support slicing and negative indices. Uji objek untuk keanggotaan dalam waktu konstan alih-alih mengulangi semua item.

Changed in version 3. 3. Define ‘==’ and ‘. =’ to compare range objects based on the sequence of values they define [instead of comparing based on object identity].

New in version 3. 3. The , and attributes.

See also

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

Text Sequence Type —

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

  • Single quotes.

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

  • Double quotes.

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

  • Triple quoted.

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

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

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

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

See for more about the various forms of string literal, including supported escape sequences, and the

>>> [65].to_bytes[]
b'A'
62 [“raw”] prefix that disables most escape sequence processing

Strings may also be created from other objects using the constructor

Since there is no separate “character” type, indexing a string produces strings of length 1. That is, for a non-empty string 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

There is also no mutable string type, but or can be used to efficiently construct strings from multiple fragments

Changed in version 3. 3. For backwards compatibility with the Python 2 series, the

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 prefix is once again permitted on string literals. It has no effect on the meaning of string literals and cannot be combined with the
>>> [65].to_bytes[]
b'A'
62 prefix.

class str[object='']class str[object=b'' , encoding='utf-8' , errors='strict']

Return a version of object. If object is not provided, returns the empty string. Otherwise, the behavior 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
33 depends on whether encoding or errors is given, as follows

If neither encoding nor errors is given,

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 returns , which is the “informal” or nicely printable string representation of object. For string objects, this is the string itself. If object does not have a 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

Untuk informasi lebih lanjut tentang kelas

>>> [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 dan metodenya, lihat dan bagian di bawah ini. Untuk menghasilkan string yang diformat, lihat bagian dan. In addition, see the section

String Methods

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

Strings also support two styles of string formatting, one providing a large degree of flexibility and customization [see , and ] and the other based on 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 style formatting that handles a narrower range of types and is slightly harder to use correctly, but is often faster for the cases it can handle []

The section of the standard library covers a number of other modules that provide various text related utilities [including regular expression support in the module]

str. capitalize[]

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

Changed in version 3. 8. The first character is now put into titlecase rather than uppercase. This means that characters like digraphs will only have their first letter capitalized, instead of the full character.

str. casefold[]

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

Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter

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 is equivalent to
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. Since it is already lowercase, would do nothing to
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; converts it to
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

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

New in version 3. 3

str. center[width[ , fillchar]]

Return centered in a string of length width. Padding dilakukan menggunakan fillchar yang ditentukan [defaultnya adalah spasi ASCII]. The original string 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

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

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

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

str. encode[encoding='utf-8' , errors='strict']

Return the string encoded to

encoding defaults to

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; see for possible values

errors controls how encoding errors are handled. If

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 [the default], a exception is raised. Other possible values are
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 and any other name registered via . See for details

For performance reasons, the value of errors is not checked for validity unless an encoding error actually occurs, is enabled or a is used

Changed in version 3. 1. Added support for keyword arguments.

Changed in version 3. 9. The value of the errors argument is now checked in and in .

str. endswith[suffix[ , 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 string ends with the specified suffix, 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. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position

str. expandtabs[tabsize=8]

Return a copy of the string where all tab characters are replaced by one or more spaces, depending on the current column and the given tab size. Tab positions occur every tabsize characters [default is 8, giving tab positions at columns 0, 8, 16 and so on]. To expand the string, the current column is set to zero and the string is examined character by character. If the character is a tab [

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], one or more space characters are inserted in the result until the current column is equal to the next tab position. [The tab character itself is not copied. ] If the character is a newline [
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] or return [
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], it is copied and the current column is reset to zero. Any other character is copied unchanged and the current column is incremented by one regardless of how the character is represented when printed

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

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

Return the lowest index in the string where substring sub is found within the slice

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. Optional arguments start and end are interpreted as in slice notation. Return
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
41 if sub is not found

Note

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

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

str. format[*args , **kwargs]

Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces

def bit_length[self]:
    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. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument

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

See for a description of the various formatting options that can be specified in format strings

Note

When formatting a number [, , , and subclasses] with the

def bit_count[self]:
    return bin[self].count["1"]
51 type [ex.
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], the function temporarily sets the
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 locale to the
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 locale to decode
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 and
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 fields of
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 if they are non-ASCII or longer than 1 byte, and the
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 locale is different than the
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 locale. This temporary change affects other threads

Changed in version 3. 7. When formatting a number with the

def bit_count[self]:
    return bin[self].count["1"]
51 type, the function sets temporarily the
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 locale to the
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 locale in some cases.

str. format_map[mapping]

Similar to

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, except that
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 is used directly and not copied to a . This is useful if 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]
71 is a dict subclass

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

Baru di versi 3. 2

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

Like , but raise when the substring is not found

str. 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 characters in the string are alphanumeric and there is at least one character,
def bit_length[self]:
    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. A character
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 is alphanumeric if one of the following 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.
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, or
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[]

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 characters in the string are alphabetic and there is at least one character,
def bit_length[self]:
    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. Karakter abjad adalah karakter yang didefinisikan dalam database karakter Unicode sebagai "Surat", mis. e. , those with general category property being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is different from the “Alphabetic” property defined in the Unicode Standard

str. 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 string is empty or all characters in the string 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 characters have code points in the range U+0000-U+007F

New in version 3. 7

str. isdecimal[]

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 characters in the string are decimal characters and there is at least one character,
def bit_length[self]:
    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. Decimal characters are those that can be used to form numbers in base 10, e. g. U+0660, ARABIC-INDIC DIGIT ZERO. Formally a decimal character is a character in the Unicode General Category “Nd”

str. isdigit[]

Return

def bit_length[self]:
    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 characters in the string are digits and there is at least one character,
def bit_length[self]:
    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. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal

str. isidentifier[]

Return

def bit_length[self]:
    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 string is a valid identifier according to the language definition, section

Call to test whether string

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 is a reserved identifier, such as and

Example

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

str. 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 all cased characters in the string are lowercase and there is at least one cased character,
def bit_length[self]:
    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

str. isnumeric[]

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 characters in the string are numeric characters, and there is at least one character,
def bit_length[self]:
    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. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e. g. U+2155, VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric

str. isprintable[]

Return

def bit_length[self]:
    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 characters in the string are printable or the string is 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. Nonprintable characters are those characters defined in the Unicode character database as “Other” or “Separator”, excepting the ASCII space [0x20] which is considered printable. [Note that printable characters in this context are those which should not be escaped when is invoked on a string. It has no bearing on the handling of strings written to or . ]

str. isspace[]

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 are only whitespace characters in the string and there is at least one character,
def bit_length[self]:
    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

A character is whitespace if in the Unicode character database [see ], either its general category is

>>> 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 [“Separator, space”], or its bidirectional class is one of
>>> 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, 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
12

str. istitle[]

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 string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return
def bit_length[self]:
    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

str. 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 all cased characters in the string are uppercase and there is at least one cased character,
def bit_length[self]:
    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

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

str. join[iterable]

Mengembalikan string yang merupakan gabungan dari string di iterable. A will be raised if there are any non-string values in iterable, including objects. The separator between elements is the string providing this method

str. ljust[width[ , fillchar]]

Return the string left justified in a string of length width. Padding is done using the specified fillchar [default is an ASCII space]. String asli dikembalikan jika lebarnya kurang dari atau sama dengan

>>> [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. lower[]

Return a copy of the string with all the cased characters converted to lowercase

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

str. lstrip[[chars]]

Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or

def bit_length[self]:
    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; rather, all combinations of its values are stripped

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

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

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

static str. maketrans[x[ , y[ , z]]]

This static method returns a translation table usable for

If there is only one argument, it must be a dictionary mapping Unicode ordinals [integers] or characters [strings of length 1] to Unicode ordinals, strings [of arbitrary lengths] or

def bit_length[self]:
    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. Character keys will then be converted to ordinals

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

def bit_length[self]:
    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 in the result

str. partition[sep]

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

str. removeprefix[prefix , /]

If the string starts with the prefix string, return

>>> 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. Otherwise, return a copy of the original string

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

New in version 3. 9

str. removesuffix[suffix , /]

If the string ends with the suffix string and that suffix is not empty, 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
26. Otherwise, return a copy of the original string

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

New in version 3. 9

str. replace[old , new[ , count]]

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

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

Return the highest index in the string where substring sub is found, such that sub is contained within

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. Optional arguments start and end are interpreted as in slice notation. Return
>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
41 on failure

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

Like but raises when the substring sub is not found

str. rjust[width[ , fillchar]]

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

>>> [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. rpartition[sep]

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

str. rsplit[sep=None , maxsplit=- 1]

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or

def bit_length[self]:
    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[[chars]]

Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or

def bit_length[self]:
    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[]

Mengembalikan versi string dengan huruf judul di mana kata-kata dimulai dengan karakter huruf besar dan karakter yang tersisa adalah huruf kecil

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. translate[table]

Return a copy of the string in which each character has been mapped through the given translation table. The table must be an object that implements indexing via

>>> 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 . Saat diindeks oleh ordinal Unicode [bilangan bulat], objek tabel dapat melakukan salah satu dari berikut ini. 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

Anda dapat menggunakan untuk membuat peta terjemahan dari pemetaan karakter ke karakter dalam berbagai format

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

str. upper[]

Return a copy of the string with all the cased characters converted to uppercase. Note 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
74 might 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
38 if
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 contains uncased characters or if the Unicode category of the resulting character[s] is not “Lu” [Letter, uppercase], but e. g. “Lt” [Letter, titlecase]

The uppercasing algorithm used is described in section 3. 13 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. The original string 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

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

Note

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

Arti

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

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

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

Pemisah untuk mencari mungkin ada

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. Dengan start opsional, uji mulai pada posisi itu. With optional end, stop comparing at that position

Awalan yang akan dicari dapat berupa apa saja

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 sekarang didukung sebagai argumen kata kunci.

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

Note

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

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

Return a copy of the object left justified in a sequence of length width. Padding is done using the specified fillbyte [default is an ASCII space]. For 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

Note

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

bytes. lstrip[[chars]]bytearray. lstrip[[chars]]

Return a copy of the sequence with specified leading bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or

def bit_length[self]:
    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 . See for a method that will remove a single prefix string rather than all of a set of characters. For example

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

Note

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

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

Return a copy of the object right justified in a sequence of length width. Padding is done using the specified fillbyte [default is an ASCII space]. For 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

Note

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[[karakter] . ]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

Note

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

bytes. split[sep=None , maxsplit=- 1]bytearray. split[sep=None , maxsplit=- 1]

Split the binary sequence into subsequences of the same type, using sep as the delimiter string. If maxsplit is given and non-negative, at most maxsplit splits are done [thus, the list will have at most

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

Note

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

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

bytes. capitalize[]bytearray. capitalize[]

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

Note

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

Note

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

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

bytes. isspace[]bytearray. isspace[]

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 whitespace 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 whitespace characters are those byte values in the sequence
>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
57 [space, tab, newline, carriage return, vertical tab, form feed]

bytes. istitle[]bytearray. istitle[]

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 ASCII titlecase 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. See for more details on the definition of “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

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

Note

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. Jeda baris tidak disertakan dalam daftar yang dihasilkan kecuali keepends diberikan dan benar

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. Uppercase ASCII characters are those byte values in the sequence
>>> [-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

Note

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

Note

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

Note

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

bytes. zfill[width]bytearray. zfill[width]

Return a copy of the sequence left filled with ASCII

>>> [-2.0].is_integer[]
True
>>> [3.2].is_integer[]
False
76 digits to make a sequence of length width. 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

Note

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

Note

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. Kunci pemetaan memilih nilai yang akan diformat dari pemetaan. 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

Arti

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

New in version 3. 3

hanya bisa dibaca

Bool yang menunjukkan apakah memori hanya dapat dibaca

format

String berisi format [dalam gaya modul] untuk setiap elemen dalam tampilan. Tampilan memori dapat dibuat dari pengekspor dengan string format arbitrer, tetapi beberapa metode [mis. g. ] dibatasi untuk format elemen tunggal asli

Berubah di versi 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 sekarang ditangani sesuai dengan sintaks modul struct. Ini berarti bahwa
def bit_length[self]:
    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

Ukuran dalam byte dari setiap elemen tampilan memori

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

ndim

Bilangan bulat yang menunjukkan berapa banyak dimensi dari array multi-dimensi yang diwakili oleh memori

membentuk

Sebuah tupel bilangan bulat panjang memberikan bentuk memori sebagai array N-dimensi

Berubah di versi 3. 3. Tuple kosong bukan

def bit_length[self]:
    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 saat ndim = 0.

langkah

Tuple bilangan bulat dengan panjang pemberian ukuran dalam byte untuk mengakses setiap elemen untuk setiap dimensi array

Berubah di versi 3. 3. Tuple kosong bukan

def bit_length[self]:
    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 saat ndim = 0.

suboffset

Digunakan secara internal untuk array gaya PIL. Nilai hanya bersifat informasional

c_contiguous

Bool yang menunjukkan apakah memori adalah C-

New in version 3. 3

f_contiguous

Sebuah bool yang menunjukkan apakah memori tersebut adalah Fortran

New in version 3. 3

berdekatan

Bool yang menunjukkan apakah memori itu

New in version 3. 3

Jenis Setel — ,

Objek set adalah kumpulan objek berbeda yang tidak terurut. Penggunaan umum termasuk pengujian keanggotaan, menghapus duplikat dari suatu urutan, dan menghitung operasi matematika seperti persimpangan, penyatuan, perbedaan, dan perbedaan simetris. [Untuk container lain lihat built-in , , dan class, dan module. ]

Seperti koleksi lainnya, set dukungan

def bit_length[self]:
    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, dan
def bit_length[self]:
    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. Menjadi koleksi yang tidak terurut, himpunan tidak merekam posisi elemen atau urutan penyisipan. Dengan demikian, set tidak mendukung pengindeksan, pemotongan, atau perilaku seperti urutan lainnya

Saat ini ada dua tipe set bawaan, dan. Jenisnya bisa berubah — isinya bisa diubah menggunakan metode seperti

def bit_length[self]:
    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 dan
>>> [65].to_bytes[]
b'A'
01. Karena dapat diubah, ia tidak memiliki nilai hash dan tidak dapat digunakan baik sebagai kunci kamus atau sebagai elemen dari kumpulan lain. Jenisnya tidak dapat diubah dan — isinya tidak dapat diubah setelah dibuat;

Set yang tidak kosong [bukan set yang dibekukan] dapat dibuat dengan menempatkan daftar elemen yang dipisahkan koma di dalam kurung kurawal, misalnya.

def bit_length[self]:
    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, selain konstruktor

Konstruktor untuk kedua kelas bekerja sama

kelas set[[dapat diubah]]class frozenset[[iterable]]

Kembalikan set baru atau objek set beku yang elemennya diambil dari iterable. Unsur-unsur suatu himpunan harus. Untuk merepresentasikan himpunan dari himpunan, himpunan bagian dalam harus berupa objek. Jika iterable tidak ditentukan, set kosong baru dikembalikan

Set dapat dibuat dengan beberapa cara

  • Gunakan daftar elemen yang dipisahkan koma di dalam kurung kurawal.

    def bit_length[self]:
        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

  • Gunakan pemahaman yang ditetapkan.

    def bit_length[self]:
        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

  • Gunakan konstruktor tipe.

    def bit_length[self]:
        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

Contoh dari dan menyediakan operasi berikut

lensa]

Mengembalikan jumlah elemen dalam set s [kardinalitas s]

x dalam s

Uji x untuk keanggotaan dalam s

x tidak dalam s

Uji x untuk non-keanggotaan dalam s

terpisah[lainnya]

Kembalikan

def bit_length[self]:
    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 jika himpunan tidak memiliki elemen yang sama dengan yang lain. Himpunan-himpunan saling lepas jika dan hanya jika perpotongannya adalah himpunan kosong

subset[lainnya]diatur 6 120

issuperset[other]set >= other

Uji apakah setiap elemen lainnya ada di himpunan

setel > lainnya

Uji apakah himpunan tersebut merupakan superset yang tepat dari yang lain, yaitu,

def bit_length[self]:
    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

serikat[*lainnya]set | lainnya . .

Kembalikan set baru dengan elemen dari set dan yang lainnya

persimpangan[*lainnya]set & other & ...

Kembalikan set baru dengan elemen yang umum ke set dan yang lainnya

perbedaan[*lainnya]set - other - ...

Kembalikan set baru dengan elemen di set yang tidak ada di set lainnya

perbedaan_simetris[lainnya]set ^ other

Kembalikan set baru dengan elemen di set atau lainnya tetapi tidak keduanya

salin[]

Kembalikan salinan set yang dangkal

Perhatikan, versi non-operator dari , , , , , dan metode akan menerima iterable apa pun sebagai argumen. Sebaliknya, rekan berbasis operator mereka membutuhkan argumen mereka untuk ditetapkan. Ini mencegah konstruksi rawan kesalahan seperti

def bit_length[self]:
    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 demi
def bit_length[self]:
    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 yang lebih mudah dibaca

Keduanya dan dukungan diatur untuk mengatur perbandingan. Dua himpunan adalah sama jika dan hanya jika setiap elemen dari setiap himpunan terkandung dalam yang lain [masing-masing merupakan subhimpunan dari yang lain]. Himpunan kurang dari himpunan lain jika dan hanya jika himpunan pertama adalah himpunan bagian yang tepat dari himpunan kedua [adalah himpunan bagian, tetapi tidak sama]. Himpunan lebih besar dari himpunan lain jika dan hanya jika himpunan pertama adalah superset yang tepat dari himpunan kedua [adalah superset, tetapi tidak sama]

Contoh dibandingkan dengan contoh berdasarkan anggotanya. Misalnya,

def bit_length[self]:
    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 mengembalikan
def bit_length[self]:
    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 dan begitu juga
def bit_length[self]:
    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

Perbandingan subset dan kesetaraan tidak digeneralisasikan ke fungsi pengurutan total. Misalnya, dua himpunan disjoint tidak kosong mana pun tidak sama dan bukan subhimpunan satu sama lain, jadi semua hasil berikut

def bit_length[self]:
    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, atau
def bit_length[self]:
    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

Karena set hanya menentukan pengurutan parsial [hubungan subset], output dari metode ini tidak ditentukan untuk daftar set

Setel elemen, seperti kunci kamus, harus

Operasi biner yang menggabungkan instance dengan mengembalikan tipe operan pertama. Sebagai contoh.

def bit_length[self]:
    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 mengembalikan instance dari

Tabel berikut mencantumkan operasi yang tersedia untuk yang tidak berlaku untuk instance yang tidak dapat diubah

perbarui[*lainnya]set |= lainnya . .

Perbarui set, tambahkan elemen dari yang lainnya

intersection_update[*lainnya]set &= other & ...

Perbarui set, pertahankan hanya elemen yang ditemukan di dalamnya dan yang lainnya

difference_update[*lainnya]set -= other | .

Perbarui set, hapus elemen yang ditemukan di orang lain

symmetric_difference_update[other]set ^= other

Perbarui set, pertahankan hanya elemen yang ditemukan di salah satu set, tetapi tidak di keduanya

tambahkan[elem]

Tambahkan elemen elemen ke set

hapus[elem]

Hapus elemen elemen dari set. Menaikkan jika elem tidak terkandung dalam set

buang[elem]

Hapus elemen elemen dari set jika ada

pop[]

Hapus dan kembalikan elemen arbitrer dari set. Menaikkan jika set kosong

jelas[]

Hapus semua elemen dari set

Perhatikan, versi non-operator dari , , , dan metode akan menerima iterable apa pun sebagai argumen

Perhatikan, argumen elem ke

>>> n = 19
>>> bin[n]
'0b10011'
>>> n.bit_count[]
3
>>> [-n].bit_count[]
3
00, , dan metode mungkin satu set. Untuk mendukung pencarian frozenset yang setara, yang sementara dibuat dari elem

Jenis Pemetaan —

Objek memetakan nilai ke objek arbitrer. Pemetaan adalah objek yang bisa berubah. Saat ini hanya ada satu jenis pemetaan standar, kamus. [Untuk container lain lihat built-in , , dan class, dan module. ]

Kunci kamus adalah nilai yang hampir sewenang-wenang. Nilai yang bukan , yaitu nilai yang berisi daftar, kamus, atau tipe lain yang dapat diubah [yang dibandingkan dengan nilai, bukan dengan identitas objek] tidak boleh digunakan sebagai kunci. Nilai yang membandingkan sama [seperti

def bit_length[self]:
    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, dan
def bit_length[self]:
    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] dapat digunakan secara bergantian untuk mengindeks entri kamus yang sama

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

Mengembalikan kamus baru yang diinisialisasi dari argumen posisi opsional dan kumpulan argumen kata kunci yang mungkin kosong

Kamus dapat dibuat dengan beberapa cara

  • Gunakan daftar

    def bit_length[self]:
        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 pasangan yang dipisahkan koma di dalam kurung kurawal.
    def bit_length[self]:
        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 atau
    def bit_length[self]:
        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

  • Gunakan pemahaman dict.

    def bit_length[self]:
        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

  • Gunakan konstruktor tipe.

    def bit_length[self]:
        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

Jika tidak ada argumen posisi yang diberikan, kamus kosong akan dibuat. Jika argumen posisi diberikan dan itu adalah objek pemetaan, kamus dibuat dengan pasangan kunci-nilai yang sama dengan objek pemetaan. Jika tidak, argumen posisi harus berupa objek. Setiap item dalam iterable harus merupakan iterable dengan tepat dua objek. Objek pertama dari setiap item menjadi kunci dalam kamus baru, dan objek kedua menjadi nilai yang sesuai. If a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary

If keyword arguments are given, the keyword arguments and their values are added to the dictionary created from the positional argument. Jika kunci yang ditambahkan sudah ada, nilai dari argumen kata kunci menggantikan nilai dari argumen posisi

Sebagai ilustrasi, contoh berikut semua mengembalikan kamus sama dengan

def bit_length[self]:
    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

Memberikan argumen kata kunci seperti pada contoh pertama hanya berfungsi untuk kunci yang merupakan pengidentifikasi Python yang valid. Jika tidak, kunci apa pun yang valid dapat digunakan

Ini adalah operasi yang didukung kamus [dan oleh karena itu, jenis pemetaan khusus juga harus didukung]

daftar[d]

Mengembalikan daftar semua kunci yang digunakan dalam kamus d

meminjamkan]

Mengembalikan jumlah item dalam kamus d

d[kunci]

Kembalikan item d dengan key key. Menimbulkan jika kunci tidak ada di peta

Jika subkelas dict mendefinisikan metode

def bit_length[self]:
    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 dan kunci tidak ada, operasi
def bit_length[self]:
    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 memanggil metode itu dengan key kunci sebagai argumen. Operasi
def bit_length[self]:
    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 kemudian mengembalikan atau menaikkan apa pun yang dikembalikan atau dimunculkan oleh panggilan
def bit_length[self]:
    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. Tidak ada operasi atau metode lain yang memanggil
def bit_length[self]:
    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. Jika
def bit_length[self]:
    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 tidak ditentukan, dinaikkan.
def bit_length[self]:
    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 harus menjadi metode;

def bit_length[self]:
    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 . Metode

def bit_length[self]:
    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 yang berbeda digunakan oleh

d[key] = nilai

Tetapkan

def bit_length[self]:
    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 ke nilai

del d[key]

Hapus

def bit_length[self]:
    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 dari d. Menimbulkan jika kunci tidak ada di peta

kunci di d

Kembalikan

def bit_length[self]:
    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 jika d memiliki kunci kunci, selain itu
def bit_length[self]:
    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

kunci bukan di d

Setara dengan

def bit_length[self]:
    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]

Kembalikan iterator di atas kunci kamus. Ini adalah jalan pintas untuk

def bit_length[self]:
    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

jelas[]

Hapus semua item dari kamus

salin[]

Kembalikan salinan kamus yang dangkal

classmethod fromkeys[dapat diubah[, value]]

Buat kamus baru dengan kunci dari iterable dan nilai disetel ke nilai

adalah metode kelas yang mengembalikan kamus baru. nilai default ke

def bit_length[self]:
    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. Semua nilai merujuk hanya pada satu contoh, jadi umumnya tidak masuk akal jika nilai menjadi objek yang dapat diubah seperti daftar kosong. To get distinct values, use a instead

dapatkan[kunci[ , default]]

Kembalikan nilai untuk kunci jika kunci ada di kamus, kalau tidak default. Jika default tidak diberikan, defaultnya adalah

def bit_length[self]:
    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, sehingga metode ini tidak pernah memunculkan

item[]

Kembalikan tampilan baru item kamus [

def bit_length[self]:
    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 pasang]. Lihat

kunci[]

Kembalikan tampilan baru dari kunci kamus. Lihat

pop[key[ , default]]

Jika kunci ada di kamus, hapus dan kembalikan nilainya, jika tidak, kembalikan default. Jika default tidak diberikan dan kunci tidak ada dalam kamus, a dimunculkan

popitem[]

Hapus dan kembalikan pasangan

def bit_length[self]:
    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 dari kamus. Pasangan dikembalikan dalam urutan LIFO

berguna untuk mengulang kamus secara destruktif, seperti yang sering digunakan dalam algoritme set. Jika kamus kosong, pemanggilan memunculkan a

Berubah di versi 3. 7. Pesanan LIFO sekarang dijamin. In prior versions, would return an arbitrary key/value pair.

terbalik[d]

Kembalikan iterator terbalik di atas kunci kamus. Ini adalah jalan pintas untuk

def bit_length[self]:
    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

Baru di versi 3. 8

setdefault[kunci[ , default]]

Jika kunci ada di kamus, kembalikan nilainya. Jika tidak, masukkan kunci dengan nilai default dan kembalikan default. default default ke

def bit_length[self]:
    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

perbarui[[lainnya]]

Perbarui kamus dengan pasangan kunci/nilai dari yang lain, menimpa kunci yang sudah ada. Kembalikan

def bit_length[self]:
    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

menerima objek kamus lain atau iterable dari pasangan kunci/nilai [sebagai tupel atau iterable lainnya dengan panjang dua]. Jika argumen kata kunci ditentukan, kamus kemudian diperbarui dengan pasangan kunci/nilai tersebut.

def bit_length[self]:
    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

nilai[]

Kembalikan tampilan baru dari nilai kamus. Lihat

Perbandingan kesetaraan antara satu tampilan

def bit_length[self]:
    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 dan lainnya akan selalu mengembalikan
def bit_length[self]:
    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 . lainnya

Buat kamus baru dengan gabungan kunci dan nilai d dan lainnya, yang keduanya harus berupa kamus. Nilai-nilai lain diprioritaskan ketika d dan kunci berbagi lainnya

New in version 3. 9

d . = lainnya

Perbarui kamus d dengan kunci dan nilai dari yang lain, yang dapat berupa a atau an dari pasangan kunci/nilai. Nilai-nilai lain diprioritaskan ketika d dan kunci berbagi lainnya

New in version 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 .

Kamus mempertahankan urutan penyisipan. Perhatikan bahwa memperbarui kunci tidak memengaruhi urutan. Kunci yang ditambahkan setelah penghapusan dimasukkan di bagian akhir

def bit_length[self]:
    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

Berubah di versi 3. 7. Urutan kamus dijamin menjadi urutan penyisipan. Perilaku ini merupakan detail implementasi CPython dari 3. 6.

Tampilan kamus dan kamus dapat dibalik

def bit_length[self]:
    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

Berubah di versi 3. 8. Kamus sekarang dapat dibalik.

See also

dapat digunakan untuk membuat tampilan read-only dari a

Objek tampilan kamus

Objek yang dikembalikan oleh , dan adalah objek tampilan. Mereka memberikan tampilan dinamis pada entri kamus, yang berarti bahwa saat kamus berubah, tampilan mencerminkan perubahan ini

Tampilan kamus dapat diulangi untuk menghasilkan datanya masing-masing, dan mendukung pengujian keanggotaan

len[tampilan dikt]

Kembalikan jumlah entri dalam kamus

iter[dictview]

Mengembalikan iterator di atas kunci, nilai, atau item [diwakili sebagai tupel

def bit_length[self]:
    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] di kamus

Kunci dan nilai diulang dalam urutan penyisipan. Ini memungkinkan pembuatan

def bit_length[self]:
    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 pasang menggunakan.
def bit_length[self]:
    s = bin[self]       # binary representation:  bin[-37] --> '-0b100101'
    s = s.lstrip['-0b'] # remove leading zeros and minus sign
    return len[s]       # len['100101'] --> 6
_222. Cara lain untuk membuat daftar yang sama adalah
def bit_length[self]:
    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

Mengulangi tampilan sambil menambahkan atau menghapus entri dalam kamus dapat meningkatkan atau gagal mengulang semua entri

Berubah di versi 3. 7. Dictionary order is guaranteed to be insertion order.

x di dictview

Kembalikan

def bit_length[self]:
    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 jika x ada di kunci, nilai, atau item kamus yang mendasarinya [dalam kasus terakhir, x harus berupa tuple
def bit_length[self]:
    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]

terbalik [dictview]

Mengembalikan iterator terbalik di atas kunci, nilai, atau item kamus. Tampilan akan diulang dalam urutan terbalik dari penyisipan

Berubah di versi 3. 8. Tampilan kamus kini dapat dibalik.

dictview. pemetaan

Kembalikan a yang membungkus kamus asli yang dirujuk oleh tampilan

Baru di versi 3. 10

Tampilan kunci seperti set karena entri mereka unik dan dapat di-hash. Jika semua nilai dapat di-hash, sehingga

def bit_length[self]:
    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 pasangan unik dan dapat di-hash, maka tampilan item juga seperti set. [Tampilan nilai tidak diperlakukan sebagai set-like karena entri umumnya tidak unik. ] Untuk tampilan set-like, semua operasi yang ditentukan untuk kelas dasar abstrak tersedia [misalnya,
def bit_length[self]:
    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, atau
def bit_length[self]:
    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]

Contoh penggunaan tampilan kamus

def bit_length[self]:
    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

Jenis Manajer Konteks

Pernyataan Python mendukung konsep konteks runtime yang ditentukan oleh pengelola konteks. 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

pengelola konteks. __masuk__[]

Masukkan konteks runtime dan kembalikan objek ini atau objek lain yang terkait dengan konteks runtime. Nilai yang dikembalikan oleh metode ini terikat pada pengidentifikasi dalam klausa

def bit_length[self]:
    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 menggunakan manajer konteks ini

Contoh manajer konteks yang mengembalikan dirinya sendiri adalah a. Objek file mengembalikan dirinya sendiri dari __enter__[] agar dapat digunakan sebagai ekspresi konteks dalam pernyataan

Contoh pengelola konteks yang mengembalikan objek terkait adalah yang dikembalikan oleh. Manajer ini menyetel konteks desimal aktif ke salinan konteks desimal asli dan kemudian mengembalikan salinannya. Ini memungkinkan perubahan dilakukan pada konteks desimal saat ini di badan pernyataan tanpa memengaruhi kode di luar pernyataan

def bit_length[self]:
    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

pengelola konteks. __exit__[exc_type , exc_val, exc_tb]

Keluar dari konteks runtime dan kembalikan flag Boolean yang menunjukkan jika ada pengecualian yang terjadi harus ditekan. Jika pengecualian terjadi saat menjalankan isi pernyataan, argumen berisi jenis pengecualian, nilai, dan informasi traceback. Jika tidak, ketiga argumen tersebut adalah

def bit_length[self]:
    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

Mengembalikan nilai sebenarnya dari metode ini akan menyebabkan pernyataan menekan pengecualian dan melanjutkan eksekusi dengan pernyataan segera setelah pernyataan

def bit_length[self]:
    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. Kalau tidak, pengecualian terus menyebar setelah metode ini selesai dieksekusi. 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

Pengecualian yang diteruskan tidak boleh dimunculkan kembali secara eksplisit - sebagai gantinya, metode ini harus mengembalikan nilai yang salah untuk menunjukkan bahwa metode tersebut berhasil diselesaikan dan tidak ingin menekan pengecualian yang dimunculkan. Ini memungkinkan kode manajemen konteks untuk dengan mudah mendeteksi apakah suatu metode benar-benar gagal atau tidak

Python mendefinisikan beberapa manajer konteks untuk mendukung sinkronisasi utas yang mudah, penutupan cepat file atau objek lain, dan manipulasi yang lebih sederhana dari konteks aritmatika desimal aktif. Jenis spesifik tidak diperlakukan secara khusus di luar penerapan protokol manajemen konteksnya. Lihat modul untuk beberapa contoh

Python dan dekorator menyediakan cara mudah untuk mengimplementasikan protokol ini. Jika fungsi generator didekorasi dengan dekorator, itu akan mengembalikan manajer konteks yang mengimplementasikan metode yang diperlukan dan, daripada iterator yang dihasilkan oleh fungsi generator yang tidak didekorasi

Perhatikan bahwa tidak ada slot khusus untuk salah satu metode ini dalam struktur tipe untuk objek Python di Python/C API. Jenis ekstensi yang ingin mendefinisikan metode ini harus menyediakannya sebagai metode normal yang dapat diakses Python. Dibandingkan dengan biaya tambahan untuk menyiapkan konteks runtime, biaya tambahan dari pencarian kamus kelas tunggal dapat diabaikan

Ketik Jenis Anotasi — ,

Tipe bawaan inti untuk adalah dan

Tipe Alias ​​Generik

def bit_length[self]:
    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 objek umumnya dibuat oleh sebuah kelas. Mereka paling sering digunakan dengan , seperti atau. Misalnya,
def bit_length[self]:
    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 adalah objek
def bit_length[self]:
    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 yang dibuat dengan mensubskrip kelas
def bit_count[self]:
    return bin[self].count["1"]
93 dengan argumen.
def bit_length[self]:
    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 objek dimaksudkan terutama untuk digunakan bersama

Note

Biasanya hanya mungkin untuk membuat subskrip kelas jika kelas tersebut mengimplementasikan metode khusus

Objek

def bit_length[self]:
    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 bertindak sebagai proxy untuk a , mengimplementasikan generik berparameter

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

def bit_length[self]:
    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 dapat digunakan dalam anotasi tipe untuk menandakan a yang semua elemennya bertipe

Untuk kelas yang mendefinisikan tetapi bukan wadah, argumen yang diberikan ke langganan kelas akan sering menunjukkan tipe kembalian dari satu atau lebih metode yang didefinisikan pada objek. Misalnya, dapat digunakan pada tipe data dan tipe data

  • Jika

    def bit_length[self]:
        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 akan menjadi objek di mana nilai pengembalian
    def bit_length[self]:
        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 dan
    def bit_length[self]:
        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 keduanya akan bertipe. Kita dapat merepresentasikan objek semacam ini dalam anotasi tipe dengan
    def bit_length[self]:
        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

  • Jika

    def bit_length[self]:
        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, [perhatikan
    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 dan
    def bit_length[self]:
        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 akan bertipe. Dalam anotasi tipe, kami akan mewakili variasi objek ini dengan
    def bit_length[self]:
        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 objek adalah turunan dari kelas, yang juga dapat digunakan untuk membuat objek
def bit_length[self]:
    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 secara langsung

T[X, Y, . ]

Membuat

def bit_length[self]:
    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 yang mewakili tipe
def bit_length[self]:
    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 yang diparameterisasi oleh tipe X, Y, dan lainnya bergantung pada
def bit_length[self]:
    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 yang digunakan. Misalnya, sebuah fungsi mengharapkan elemen yang mengandung

def bit_length[self]:
    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

Contoh lain untuk objek, menggunakan a , yang merupakan tipe generik yang mengharapkan dua parameter tipe yang mewakili tipe kunci dan tipe nilai. Dalam contoh ini, fungsi mengharapkan

>>> [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 dengan kunci tipe dan nilai tipe

def bit_length[self]:
    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

Fungsi bawaan dan tidak menerima tipe

def bit_length[self]:
    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 untuk argumen kedua mereka

def bit_length[self]:
    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

Runtime Python tidak berlaku. Ini meluas ke tipe generik dan parameter tipenya. 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. Misalnya, kode berikut tidak dianjurkan, tetapi akan berjalan tanpa kesalahan

def bit_length[self]:
    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

Selanjutnya, parameter generik menghapus parameter tipe selama pembuatan objek

def bit_length[self]:
    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

Memanggil atau pada generik menunjukkan tipe parameter

def bit_length[self]:
    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

Metode wadah umum akan memunculkan pengecualian untuk melarang kesalahan seperti

def bit_length[self]:
    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

Namun, ekspresi seperti itu valid saat digunakan. Indeks harus memiliki elemen sebanyak item variabel tipe dalam objek

def bit_length[self]:
    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
_12

Kelas Generik Standar

Kelas pustaka standar berikut mendukung generik berparameter. Daftar ini tidak lengkap

Atribut Khusus dari
def bit_length[self]:
    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 objek

Semua obat generik berparameter mengimplementasikan atribut read-only khusus

generikal. __origin__

Atribut ini menunjuk pada kelas generik non-parameter

def bit_length[self]:
    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

generikal. __args__

Atribut ini adalah [mungkin dengan panjang 1] dari tipe generik yang diteruskan ke kelas generik asli

def bit_length[self]:
    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

generikal. __parameters__

Atribut ini adalah tuple yang dihitung dengan malas [mungkin kosong] dari variabel tipe unik yang ditemukan di

def bit_length[self]:
    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

Note

Objek

def bit_length[self]:
    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 dengan parameter mungkin tidak benar
def bit_length[self]:
    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 setelah substitusi karena dimaksudkan terutama untuk pemeriksaan tipe statis

generikal. __unpacked__

Boolean yang benar jika alias telah dibongkar menggunakan operator

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

Baru di versi 3. 11

See also

PEP 484 - Ketik Petunjuk

Memperkenalkan kerangka kerja Python untuk anotasi tipe

PEP 585 - Ketik Generik Petunjuk Dalam Koleksi Standar

Memperkenalkan kemampuan untuk membuat parameter kelas perpustakaan standar secara native, asalkan mereka menerapkan metode kelas khusus

, dan

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

New in version 3. 9

Tipe Serikat

Objek gabungan memegang nilai operasi

def bit_length[self]:
    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 atau] pada banyak. Jenis ini dimaksudkan terutama untuk. Ekspresi tipe gabungan memungkinkan sintaks petunjuk tipe yang lebih bersih dibandingkan dengan

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 berarti X atau Y. Ini setara dengan
def bit_length[self]:
    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. Misalnya, fungsi berikut mengharapkan argumen bertipe 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 == lainnya

Objek gabungan dapat diuji kesetaraannya dengan objek gabungan lainnya. Detail

  • Serikat pekerja diratakan

    def bit_length[self]:
        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

  • Jenis redundan dihapus

    def bit_length[self]:
        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

  • Saat membandingkan serikat pekerja, pesanan diabaikan

    def bit_length[self]:
        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

  • Ini kompatibel dengan

    def bit_length[self]:
        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

  • Jenis opsional dapat dieja sebagai gabungan dengan

    def bit_length[self]:
        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]

Panggilan ke dan juga didukung dengan objek gabungan

def bit_length[self]:
    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

Note

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. Jika metaclass mengimplementasikan
def bit_length[self]:
    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, Union dapat menimpanya

def bit_length[self]:
    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

See also

PEP 604 – PEP proposing 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
373 syntax and the Union type

Baru di versi 3. 10

Jenis Bawaan Lainnya

Penerjemah mendukung beberapa jenis objek lainnya. Sebagian besar hanya mendukung satu atau dua operasi

Modul

Satu-satunya operasi khusus pada modul adalah akses atribut.

def bit_length[self]:
    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, di mana m adalah modul dan nama mengakses nama yang didefinisikan dalam tabel simbol m. Module attributes can be assigned to. [Perhatikan bahwa pernyataan tersebut bukan, sebenarnya, operasi pada objek modul;
def bit_length[self]:
    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 tidak memerlukan objek modul bernama foo untuk ada, melainkan membutuhkan definisi [eksternal] untuk modul bernama foo di suatu tempat. ]

Atribut khusus dari setiap modul adalah. Ini adalah kamus yang berisi tabel simbol modul. Memodifikasi kamus ini sebenarnya akan mengubah tabel simbol modul, tetapi penugasan langsung ke atribut tidak dimungkinkan [Anda dapat menulis

def bit_length[self]:
    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, yang mendefinisikan
def bit_length[self]:
    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 menjadi
def bit_length[self]:
    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, tetapi Anda tidak dapat menulis
def bit_length[self]:
    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]. Memodifikasi secara langsung tidak disarankan

Modul yang dibangun ke dalam juru bahasa ditulis seperti ini.

def bit_length[self]:
    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

Kelas dan Contoh Kelas

See and for these

Fungsi

Objek fungsi dibuat dengan definisi fungsi. 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

Sebenarnya ada dua jenis objek fungsi. fungsi bawaan dan fungsi yang ditentukan pengguna. Keduanya mendukung operasi yang sama [untuk memanggil fungsi], tetapi implementasinya berbeda, maka jenis objeknya berbeda

Lihat untuk informasi lebih lanjut

Metode

Metode adalah fungsi yang dipanggil menggunakan notasi atribut. Ada dua rasa. metode bawaan [seperti

def bit_length[self]:
    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 pada daftar] dan metode instance kelas. Metode bawaan dijelaskan dengan tipe yang mendukungnya

Jika Anda mengakses metode [fungsi yang didefinisikan dalam ruang nama kelas] melalui sebuah instance, Anda mendapatkan objek khusus. objek metode terikat [juga disebut metode instan]. 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 adalah objek tempat metode beroperasi, dan
def bit_length[self]:
    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 adalah fungsi yang mengimplementasikan metode. 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. Mencoba untuk mengatur atribut pada hasil metode dimunculkan. Untuk menyetel atribut metode, Anda perlu menyetelnya secara eksplisit pada objek fungsi yang mendasarinya

def bit_length[self]:
    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

Lihat untuk informasi lebih lanjut

Objek Kode

Objek kode digunakan oleh implementasi untuk mewakili kode Python yang dapat dieksekusi “pseudo-compiled” seperti badan fungsi. Mereka berbeda dari objek fungsi karena tidak berisi referensi ke lingkungan eksekusi globalnya. 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. Lihat juga modul

Mengakses

def bit_length[self]:
    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 memunculkan
def bit_length[self]:
    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 dengan argumen
def bit_length[self]:
    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 dan
def bit_length[self]:
    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

Objek kode dapat dieksekusi atau dievaluasi dengan meneruskannya [alih-alih string sumber] ke atau fungsi bawaan

Lihat untuk informasi lebih lanjut

Ketik Objek

Jenis objek mewakili berbagai jenis objek. Jenis objek diakses oleh fungsi bawaan. Tidak ada operasi khusus pada tipe. Modul standar menentukan nama untuk semua tipe bawaan standar

Jenis ditulis seperti ini.

def bit_length[self]:
    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

Objek Null

Objek ini dikembalikan oleh fungsi yang tidak mengembalikan nilai secara eksplisit. Ini tidak mendukung operasi khusus. 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 menghasilkan singleton yang sama

Itu ditulis sebagai

def bit_length[self]:
    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

Objek Ellipsis

Objek ini biasa digunakan dengan mengiris [lihat ]. Ini tidak mendukung operasi khusus. Tepatnya ada satu objek elipsis, bernama [nama bawaan].

def bit_length[self]:
    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 menghasilkan singleton

Itu ditulis sebagai

def bit_length[self]:
    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 atau
def bit_length[self]:
    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

Objek NotImplemented

Objek ini dikembalikan dari perbandingan dan operasi biner ketika mereka diminta untuk beroperasi pada jenis yang tidak mereka dukung. Lihat untuk informasi lebih lanjut. Tepatnya ada satu objek

def bit_length[self]:
    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.
def bit_length[self]:
    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 menghasilkan instance tunggal

Itu ditulis sebagai

def bit_length[self]:
    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

Nilai Boolean

Nilai Boolean adalah dua objek konstan

def bit_length[self]:
    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 dan
def bit_length[self]:
    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. Mereka digunakan untuk mewakili nilai kebenaran [walaupun nilai lain juga dapat dianggap salah atau benar]. Dalam konteks numerik [misalnya ketika digunakan sebagai argumen untuk operator aritmatika], masing-masing berperilaku seperti bilangan bulat 0 dan 1. Fungsi bawaan dapat digunakan untuk mengonversi nilai apa pun menjadi Boolean, jika nilainya dapat diartikan sebagai nilai kebenaran [lihat bagian di atas]

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

Lihat untuk informasi ini. Ini menggambarkan objek bingkai tumpukan, objek traceback, dan objek irisan

Atribut Khusus

Implementasinya menambahkan beberapa atribut read-only khusus ke beberapa tipe objek, jika relevan. Beberapa di antaranya tidak dilaporkan oleh fungsi bawaan

objek. __dict__

Kamus atau objek pemetaan lain yang digunakan untuk menyimpan atribut objek [dapat ditulis].

contoh. __kelas__

Kelas tempat instance kelas berada

kelas. __basis__

Tuple kelas dasar dari objek kelas

definisi. __nama__

Nama kelas, fungsi, metode, deskriptor, atau instance generator

definisi. __qualname__

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

New in version 3. 3

kelas. __mro__

Atribut ini adalah kumpulan kelas yang dipertimbangkan saat mencari kelas dasar selama resolusi metode

kelas. mro[]

Metode ini dapat diganti oleh metaclass untuk menyesuaikan urutan resolusi metode untuk instansnya. Ini disebut pada instantiasi kelas, dan hasilnya disimpan di

kelas. __subkelas__[]

Setiap kelas menyimpan daftar referensi lemah ke subkelas langsungnya. Metode ini mengembalikan daftar semua referensi yang masih hidup. Daftar ini dalam urutan definisi. Contoh

def bit_length[self]:
    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

Batasan panjang konversi string bilangan bulat

CPython memiliki batas global untuk mengonversi antara dan untuk memitigasi penolakan serangan layanan. Batasan ini hanya berlaku untuk basis angka desimal atau non-pangkat-dua lainnya. Konversi heksadesimal, oktal, dan biner tidak terbatas. Batasnya dapat dikonfigurasi

Jenis dalam Python adalah angka panjang acak yang disimpan dalam bentuk biner [umumnya dikenal sebagai "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. Bahkan algoritma paling terkenal untuk basis 10 memiliki kompleksitas sub-kuadrat. Mengonversi nilai besar seperti

def bit_length[self]:
    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 dapat memakan waktu lebih dari satu detik pada CPU yang cepat

Membatasi ukuran konversi menawarkan cara praktis untuk menghindari CVE-2020-10735

Batas diterapkan pada jumlah karakter digit dalam string input atau output ketika algoritma konversi non-linear akan dilibatkan. Garis bawah dan tanda tidak dihitung terhadap batas

Ketika suatu operasi akan melebihi batas, a dinaikkan

def bit_length[self]:
    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

Batas default adalah 4300 digit seperti yang disediakan di. Batas terendah yang dapat dikonfigurasi adalah 640 digit seperti yang disediakan di

Verifikasi

def bit_length[self]:
    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

Baru di versi 3. 11

API yang terpengaruh

Pembatasan hanya berlaku untuk konversi yang berpotensi lambat antara dan atau

  • def bit_length[self]:
        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 dengan basis default 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 untuk semua basis yang bukan pangkat 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

  • konversi string lainnya ke basis 10, misalnya

    def bit_length[self]:
        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, atau
    def bit_length[self]:
        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

Batasan tidak berlaku untuk fungsi dengan algoritme linier

  • def bit_length[self]:
        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 dengan basis 2, 4, 8, 16, atau 32

  • dan

  • , ,

  • untuk bilangan hex, oktal, dan biner

  • ke

  • ke

Konfigurasi batas

Sebelum Python dimulai, Anda dapat menggunakan variabel lingkungan atau tanda baris perintah juru bahasa untuk mengonfigurasi batas

  • , 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 untuk menetapkan batas ke 640 atau
    def bit_length[self]:
        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 untuk menonaktifkan batasan

  • , 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 berisi nilai atau. Jika env var dan opsi
    def bit_length[self]:
        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 disetel, opsi
    def bit_length[self]:
        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 diutamakan. Nilai -1 menunjukkan bahwa keduanya tidak disetel, sehingga nilai
    def bit_length[self]:
        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 digunakan selama inisialisasi

Dari kode, Anda dapat memeriksa batas saat ini dan menetapkan batas baru menggunakan API ini

  • dan merupakan pengambil dan penyetel untuk batas lebar juru bahasa. Subinterpreter memiliki batasnya sendiri

Informasi tentang default dan minimum dapat ditemukan di

  • adalah batas default yang dikompilasi

  • adalah nilai terendah yang diterima untuk batas [selain 0 yang menonaktifkannya]

Baru di versi 3. 11

Hati-hati

Menetapkan batas rendah dapat menyebabkan masalah. Meskipun jarang, ada kode yang berisi konstanta integer dalam desimal di sumbernya yang melebihi ambang batas minimum. A consequence of setting the limit is that Python source code containing decimal integer literals longer than the limit will encounter an error during parsing, usually at startup time or import time or even at installation time - anytime an up to date

def bit_length[self]:
    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 does not already exist for the code. Solusi untuk sumber yang berisi konstanta besar adalah dengan mengonversinya menjadi
def bit_count[self]:
    return bin[self].count["1"]
12 bentuk heksadesimal karena tidak memiliki batas

Uji aplikasi Anda secara menyeluruh jika Anda menggunakan batas rendah. Pastikan pengujian Anda berjalan dengan batas yang ditetapkan lebih awal melalui lingkungan atau tanda sehingga itu berlaku selama startup dan bahkan selama langkah instalasi apa pun yang dapat memanggil Python untuk melakukan prekompilasi

def bit_length[self]:
    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 sumber ke
def bit_length[self]:
    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 file

Konfigurasi yang disarankan

def bit_length[self]:
    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 default diharapkan wajar untuk sebagian besar aplikasi. Jika aplikasi Anda memerlukan batas yang berbeda, setel dari titik masuk utama Anda menggunakan kode agnostik versi Python karena API ini ditambahkan dalam rilis patch keamanan di versi sebelum 3. 11

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
_30

Jika Anda perlu menonaktifkannya sepenuhnya, setel ke

def bit_length[self]:
    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

Catatan kaki

Informasi tambahan tentang metode khusus ini dapat ditemukan di Manual Referensi Python []

Akibatnya, daftar

def bit_length[self]:
    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 dianggap sama dengan
def bit_length[self]:
    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, dan demikian pula untuk tupel

Mereka harus memilikinya karena parser tidak dapat mengetahui jenis operan

4[,,,]

Karakter huruf kapital adalah karakter dengan properti kategori umum menjadi salah satu dari "Lu" [Huruf, huruf besar], "Ll" [Huruf, huruf kecil], atau "Lt" [Huruf, huruf judul]

5[,]

Untuk memformat tuple saja, Anda harus menyediakan tuple tunggal yang satu-satunya elemennya adalah tuple yang akan diformat

Bagaimana cara memformat dict menjadi string dengan python?

Anda dapat dengan mudah mengonversi kamus Python menjadi string menggunakan fungsi str[] . Fungsi str[] mengambil objek [karena semua yang ada di Python adalah objek] sebagai parameter input dan mengembalikan varian string dari objek itu.

Bagaimana cara mengubah kunci dict menjadi string dengan python?

Berbagai cara untuk mengubah kamus menjadi string dengan Python .
Menggunakan fungsi str[]. .
Menggunakan json. .
Menggunakan string kosong dan untuk loop. .
Menggunakan string kosong, for loop, dan fungsi items[]. .
Menggunakan loop for, items[], dan str

Bagaimana Anda mencetak kamus dengan indah di python?

Menggunakan pprint[] . Output pprint[] jauh lebih mudah dibaca manusia karena memecah setiap elemen kamus bersarang dalam format array. Itu juga mengurutkan nilai kamus sehubungan dengan kunci kamus.

Apa dict ={} di python?

Struktur tabel hash kunci/nilai Python yang efisien disebut "dict". Isi dict dapat ditulis sebagai rangkaian kunci. pasangan nilai dalam kurung kurawal {}, e. g. dict = {key1. nilai1, kunci2. nilai2,. }. "Dict kosong" hanyalah sepasang kurung kurawal kosong {}.

Bài mới nhất

Chủ Đề