Bagaimana Anda memangkas nilai dalam daftar python?

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

Show

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. This is a short-circuit operator, so it only evaluates the second argument if the first one is true

  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 has a lower priority than non-Boolean operators, so
    def bit_length(self):
        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 is interpreted 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
    
    69, 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
    
    70 is a syntax error

Comparisons

Ada delapan operasi perbandingan di Python. They all have the same priority (which is higher than that of the Boolean operations). Comparisons can be chained arbitrarily; 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
71 is equivalent to
def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6
72, except that y is evaluated only once (but in both cases z is not evaluated at all when
def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6
73 is found to be false)

This table summarizes the comparison operations

Operasi

Meaning

def bit_length(self):
    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

less than or equal

def bit_length(self):
    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

not equal

def bit_length(self):
    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

object identity

def bit_length(self):
    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

negated object identity

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

Instances of a class cannot be ordered with respect to other instances of the same class, or other types of object, unless the class defines enough of the methods , , , and (in general, and are sufficient, if you want the conventional meanings of the comparison operators)

The behavior of the and operators cannot be customized; also they can be applied to any two objects and never raise an exception

Two more operations with the same syntactic priority, and , are supported by types that are or implement the

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

Jenis Numerik — , ,

Ada tiga tipe numerik yang berbeda. bilangan bulat, bilangan floating point, dan bilangan kompleks. Selain itu, Boolean adalah subtipe dari bilangan bulat. Bilangan bulat memiliki presisi tak terbatas. Angka floating point biasanya diimplementasikan menggunakan double di C; . Bilangan kompleks memiliki bagian nyata dan imajiner, yang masing-masing merupakan bilangan floating point. Untuk mengekstrak bagian ini dari bilangan kompleks z, gunakan

>>> n = 19
>>> bin(n)
'0b10011'
>>> n.bit_count()
3
>>> (-n).bit_count()
3
05 dan
>>> n = 19
>>> bin(n)
'0b10011'
>>> n.bit_count()
3
>>> (-n).bit_count()
3
06. (Pustaka standar menyertakan tipe numerik tambahan, untuk bilangan rasional, dan, untuk bilangan titik-mengambang dengan presisi yang dapat ditentukan pengguna. )

Angka dibuat oleh literal numerik atau sebagai hasil dari fungsi dan operator bawaan. Literal bilangan bulat tanpa hiasan (termasuk bilangan hex, oktal, dan biner) menghasilkan bilangan bulat. Literal numerik yang mengandung titik desimal atau tanda eksponen menghasilkan angka floating point. Menambahkan

>>> n = 19
>>> bin(n)
'0b10011'
>>> n.bit_count()
3
>>> (-n).bit_count()
3
09 atau
>>> n = 19
>>> bin(n)
'0b10011'
>>> n.bit_count()
3
>>> (-n).bit_count()
3
10 ke literal numerik menghasilkan bilangan imajiner (bilangan kompleks dengan bagian nyata nol) yang dapat Anda tambahkan ke bilangan bulat atau float untuk mendapatkan bilangan kompleks dengan bagian nyata dan imajiner

Python sepenuhnya mendukung aritmatika campuran. ketika operator aritmatika biner memiliki operan dari tipe numerik yang berbeda, operan dengan tipe "sempit" diperlebar ke yang lain, di mana bilangan bulat lebih sempit dari floating point, yang lebih sempit dari kompleks. Perbandingan antara angka-angka dari jenis yang berbeda berlaku seolah-olah nilai pasti dari angka-angka itu sedang dibandingkan.

Konstruktor , , dan dapat digunakan untuk menghasilkan angka dengan tipe tertentu

Semua tipe numerik (kecuali kompleks) mendukung operasi berikut (untuk prioritas operasi, lihat )

Operasi

Hasil

Catatan

Dokumentasi lengkap

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

jumlah x dan y

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

selisih x dan y

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

produk dari x dan 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

hasil bagi berlantai dari x dan 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 tidak berubah

>>> 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 dikonversi ke bilangan bulat

(3)(6)

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

x dikonversi ke floating point

(4)(6)

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

bilangan kompleks dengan bagian real re, bagian imajiner in. im defaults to zero

(6)

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

konjugasi bilangan kompleks 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. Also referred to as integer division. Nilai yang dihasilkan adalah bilangan bulat utuh, meskipun tipe hasilnya belum tentu int. The result is always rounded towards minus infinity.

    >>> n = 19
    >>> bin(n)
    '0b10011'
    >>> n.bit_count()
    3
    >>> (-n).bit_count()
    3
    
    38 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
    
    42,
    >>> n = 19
    >>> bin(n)
    '0b10011'
    >>> n.bit_count()
    3
    >>> (-n).bit_count()
    3
    
    40 is
    >>> 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 is
    >>> n = 19
    >>> bin(n)
    '0b10011'
    >>> n.bit_count()
    3
    >>> (-n).bit_count()
    3
    
    41, and
    >>> n = 19
    >>> bin(n)
    '0b10011'
    >>> n.bit_count()
    3
    >>> (-n).bit_count()
    3
    
    44 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
    
    42

  2. Not for complex numbers. 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/Public/14. 0. 0/ucd/extracted/DerivedNumericType. txt for a complete list of code points with the

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

All types ( and ) also include the following operations

Operasi

Hasil

x truncated to

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

terbesar <= x

minimal >= x

Untuk operasi numerik tambahan, lihat dan modul

Operasi Bitwise pada Jenis Integer

Operasi bitwise hanya masuk akal untuk bilangan bulat. Hasil operasi bitwise dihitung seolah-olah dilakukan dalam komplemen dua dengan jumlah bit tanda yang tak terhingga

Prioritas operasi bitwise biner semuanya lebih rendah dari operasi numerik dan lebih tinggi dari perbandingan;

This table lists the bitwise operations sorted in ascending priority

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

the bits of x inverted

Catatan

  1. Negative shift counts are illegal and cause a to be raised

  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. In addition, it provides a few more methods

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. Equivalently, when
>>> n = 19
>>> bin(n)
'0b10011'
>>> n.bit_count()
3
>>> (-n).bit_count()
3
23 is small enough to have a correctly rounded logarithm, then
>>> n = 19
>>> bin(n)
'0b10011'
>>> n.bit_count()
3
>>> (-n).bit_count()
3
87. If
>>> n = 19
>>> bin(n)
'0b10011'
>>> n.bit_count()
3
>>> (-n).bit_count()
3
82 is zero, then
>>> n = 19
>>> bin(n)
'0b10011'
>>> n.bit_count()
3
>>> (-n).bit_count()
3
83 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
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()

Return the number of ones in the binary representation of the absolute value of the integer. This is also known as the population count. 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. The default value for signed 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
38

The default values can be used to conveniently turn an integer into a single byte object. 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. Added default argument values for

>>> n = 19
>>> bin(n)
'0b10011'
>>> n.bit_count()
3
>>> (-n).bit_count()
3
99 and
def bit_count(self):
    return bin(self).count("1")
00.

classmethod 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. If byteorder is
>>> n = 19
>>> bin(n)
'0b10011'
>>> n.bit_count()
3
>>> (-n).bit_count()
3
94, the most significant byte is at the end of the byte array. 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 << i*8 for i, b in enumerate(little_ordered))
    if signed and little_ordered and (little_ordered[-1] & 0x80):
        n -= 1 << 8*len(little_ordered)

    return n

Baru di versi 3. 2

Changed in version 3. 11. Menambahkan nilai argumen default untuk

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

int. as_integer_ratio()

Kembalikan sepasang bilangan bulat yang rasionya persis sama dengan bilangan bulat asli dan dengan penyebut positif. Rasio bilangan bulat bilangan bulat (bilangan bulat) selalu bilangan bulat sebagai pembilang 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 sebagai penyebut

Baru di versi 3. 8

Metode Tambahan di Float

Tipe float mengimplementasikan. float also has the following additional methods

mengambang. as_integer_ratio()

Kembalikan sepasang bilangan bulat yang rasionya persis sama dengan float asli dan dengan penyebut positif. Menaikkan infinitas dan NaN

mengambang. is_integer()

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 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. If a container supports different types of iteration, additional methods can be provided to specifically request iterators for those iteration types. (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. If i or j are omitted or
    def bit_length(self):
        s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
        s = s.lstrip('-0b') # remove leading zeros and minus sign
        return len(s)       # len('100101') --> 6
    
    31, they become “end” values (which end depends on the sign of k). 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. To get a linear runtime cost, you must switch to one of the alternatives below

    • if concatenating objects, you can build a list and use at the end or else write to an instance and retrieve its value when complete

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

    • if concatenating objects, extend a instead

    • for other types, investigate the relevant class documentation

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

  8. >>> (1024).to_bytes(2, byteorder='big')
    b'\x04\x00'
    >>> (1024).to_bytes(10, byteorder='big')
    b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'
    >>> (-1024).to_bytes(10, byteorder='big', signed=True)
    b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
    >>> x = 1000
    >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little')
    b'\xe8\x03'
    
    63 raises when x is not found in s. Not all implementations support passing the additional arguments i and j. These arguments allow efficient searching of subsections of the sequence. Passing the extra arguments is roughly equivalent to using
    >>> (1024).to_bytes(2, byteorder='big')
    b'\x04\x00'
    >>> (1024).to_bytes(10, byteorder='big')
    b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'
    >>> (-1024).to_bytes(10, byteorder='big', signed=True)
    b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
    >>> x = 1000
    >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little')
    b'\xe8\x03'
    
    65, only without copying any data and with the returned index being relative to the start of the sequence rather than the start of the slice

Immutable Sequence Types

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

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

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

Mutable Sequence Types

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

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

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

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

item i of s is replaced by x

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

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

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

same as

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

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

the elements of

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

(1)

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

removes the elements of

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

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

appends x to the end of the sequence (same as

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

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

removes all items from s (same as

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

(5)

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

creates a shallow copy of s (same as

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

(5)

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

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

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

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

updates s with its contents repeated n times

(6)

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

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

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

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

retrieves the item at i and also removes it from s

(2)

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

remove the first item from s where

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

(3)

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

reverses the items of s in place

(4)

Catatan

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

  2. The optional argument i defaults to

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

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

  4. The

    >>> (65).to_bytes()
    b'A'
    
    03 method modifies the sequence in place for economy of space when reversing a large sequence. To remind users that it operates by side effect, it does not return the reversed sequence

  5. >>> (65).to_bytes()
    b'A'
    
    04 and
    >>> (65).to_bytes()
    b'A'
    
    05 are included for consistency with the interfaces of mutable containers that don’t support slicing operations (such as and ).
    >>> (65).to_bytes()
    b'A'
    
    _05 bukan bagian dari ABC, tetapi sebagian besar kelas urutan konkrit yang dapat diubah menyediakannya

    New in version 3. 3.

    >>> (65).to_bytes()
    b'A'
    
    04 and
    >>> (65).to_bytes()
    b'A'
    
    05 methods.

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

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

Lists

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

class list([iterable])

Lists may be constructed in several ways

  • Using a pair of square brackets to denote the empty list.

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

  • Using square brackets, separating items with commas.

    >>> (65).to_bytes()
    b'A'
    
    15,
    >>> (65).to_bytes()
    b'A'
    
    16

  • Using a list comprehension.

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

  • Using the type constructor.

    >>> (65).to_bytes()
    b'A'
    
    18 or
    >>> (65).to_bytes()
    b'A'
    
    19

The constructor builds a list whose items are the same and in the same order as iterable’s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a list, a copy is made and returned, similar to

>>> (65).to_bytes()
b'A'
20. For example,
>>> (65).to_bytes()
b'A'
21 returns
>>> (65).to_bytes()
b'A'
22 and
>>> (65).to_bytes()
b'A'
23 returns
>>> (65).to_bytes()
b'A'
24. If no argument is given, the constructor creates a new empty list,
def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6
49

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

Lists implement all of the and sequence operations. 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

Untuk langkah positif, isi rentang

>>> (65).to_bytes()
b'A'
62 ditentukan dengan rumus
>>> (65).to_bytes()
b'A'
63 di mana
>>> (65).to_bytes()
b'A'
64 dan
>>> (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)

Keuntungan dari tipe dibandingkan reguler atau adalah bahwa suatu objek akan selalu mengambil jumlah memori (kecil) yang sama, tidak peduli ukuran rentang yang diwakilinya (karena hanya menyimpan nilai

>>> (65).to_bytes()
b'A'
79,
>>> (65).to_bytes()
b'A'
80 dan
>>> (65).to_bytes()
b'A'
81, menghitung masing-masing item

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

Testing range objects for equality with

def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6
78 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
79 compares them as sequences. That is, two range objects are considered equal if they represent the same sequence of values. (Note that two range objects that compare equal might have different , 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

For more information on the

>>> (1024).to_bytes(2, byteorder='big')
b'\x04\x00'
>>> (1024).to_bytes(10, byteorder='big')
b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'
>>> (-1024).to_bytes(10, byteorder='big', signed=True)
b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
>>> x = 1000
>>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little')
b'\xe8\x03'
22 class and its methods, see and the section below. To output formatted strings, see the and sections. 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 ()

Bagian pustaka standar mencakup sejumlah modul lain yang menyediakan berbagai utilitas terkait teks (termasuk dukungan ekspresi reguler dalam modul)

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

Lakukan operasi pemformatan string. 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. Alphabetic characters are those characters defined in the Unicode character database as “Letter”, i. e. , those with general category property being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is different from the “Alphabetic” property defined in the 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)

Return a string which is the concatenation of the strings in 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). 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. 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)

Kembalikan daftar kata dalam string, gunakan sep sebagai string pembatas. 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. menjalankan spasi putih berurutan dianggap sebagai pemisah tunggal, dan hasilnya tidak akan berisi string kosong di awal atau akhir jika string memiliki spasi putih di depan atau di belakang. Akibatnya, memisahkan string kosong atau string yang hanya terdiri dari spasi kosong dengan pemisah
def bit_length(self):
    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
def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6
49

For example

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

str. splitlines(keepends=False)

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

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

Representation

Description

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

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

Line Feed

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

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

Carriage Return

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

Carriage Return + Line Feed

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

Line Tabulation

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

Form Feed

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

File Separator

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

Group Separator

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

Record Separator

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

Next Line (C1 Control Code)

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

Line Separator

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

Paragraph Separator

Changed in version 3. 2.

>>> int.from_bytes(b'\x00\x10', byteorder='big')
16
>>> int.from_bytes(b'\x00\x10', byteorder='little')
4096
>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)
-1024
>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False)
64512
>>> int.from_bytes([255, 0, 0], byteorder='big')
16711680
50 and
>>> int.from_bytes(b'\x00\x10', byteorder='big')
16
>>> int.from_bytes(b'\x00\x10', byteorder='little')
4096
>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)
-1024
>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False)
64512
>>> int.from_bytes([255, 0, 0], byteorder='big')
16711680
52 added to list of line boundaries.

For example

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

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

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

For comparison,

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

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

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

Return

def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6
56 if string starts with the prefix, otherwise return
def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6
38. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position

str. strip([chars])

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

def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6
31, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped

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

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

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

str. swapcase()

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

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

str. title()

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

For example

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

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

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

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

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

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

str. 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 . When indexed by a Unicode ordinal (an integer), the table object can do any of the following. return a Unicode ordinal or a string, to map the character to one or more other characters; return
def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6
31, to delete the character from the return string; or raise a exception, to map the character to itself

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

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

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

Meaning

>>> 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 << i*8 for i, b in enumerate(little_ordered))
    if signed and little_ordered and (little_ordered[-1] & 0x80):
        n -= 1 << 8*len(little_ordered)

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

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

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

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

    return n
04) may be present, but is ignored as it is not necessary for Python – so e. g.
def from_bytes(bytes, byteorder='big', signed=False):
    if byteorder == 'little':
        little_ordered = list(bytes)
    elif byteorder == 'big':
        little_ordered = list(reversed(bytes))
    else:
        raise ValueError("byteorder must be either 'little' or 'big'")

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

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

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

    return n
06

The conversion types are

Conversion

Meaning

Catatan

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

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

    return n
07

Signed integer decimal

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

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

    return n
08

Signed integer decimal

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

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

    return n
09

Signed octal value

(1)

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

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

    return n
10

Obsolete type – it is identical to

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

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

    return n
07

(6)

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

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

    return n
12

Signed hexadecimal (lowercase)

(2)

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

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

    return n
13

Heksadesimal bertanda (huruf besar)

(2)

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

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

    return n
14

Floating point exponential format (lowercase)

(3)

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

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

    return n
15

Floating point exponential format (uppercase)

(3)

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

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

    return n
16

Floating point decimal format

(3)

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

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

    return n
17

Floating point decimal format

(3)

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

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

    return n
_18

Format titik mengambang. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise

(4)

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

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

    return n
19

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

(4)

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

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

    return n
20

Single character (accepts integer or single character string)

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

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

    return n
21

String (converts any Python object using )

(5)

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

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

    return n
23

String (converts any Python object using )

(5)

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

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

    return n
25

String (converts any Python object using )

(5)

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

No argument is converted, results in 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
87 character in the result

Catatan

  1. The alternate form causes a leading octal specifier (

    def from_bytes(bytes, byteorder='big', signed=False):
        if byteorder == 'little':
            little_ordered = list(bytes)
        elif byteorder == 'big':
            little_ordered = list(reversed(bytes))
        else:
            raise ValueError("byteorder must be either 'little' or 'big'")
    
        n = sum(b << i*8 for i, b in enumerate(little_ordered))
        if signed and little_ordered and (little_ordered[-1] & 0x80):
            n -= 1 << 8*len(little_ordered)
    
        return n
    
    29) to be inserted before the first digit

  2. The alternate form causes a leading

    def from_bytes(bytes, byteorder='big', signed=False):
        if byteorder == 'little':
            little_ordered = list(bytes)
        elif byteorder == 'big':
            little_ordered = list(reversed(bytes))
        else:
            raise ValueError("byteorder must be either 'little' or 'big'")
    
        n = sum(b << i*8 for i, b in enumerate(little_ordered))
        if signed and little_ordered and (little_ordered[-1] & 0x80):
            n -= 1 << 8*len(little_ordered)
    
        return n
    
    30 or
    def from_bytes(bytes, byteorder='big', signed=False):
        if byteorder == 'little':
            little_ordered = list(bytes)
        elif byteorder == 'big':
            little_ordered = list(reversed(bytes))
        else:
            raise ValueError("byteorder must be either 'little' or 'big'")
    
        n = sum(b << i*8 for i, b in enumerate(little_ordered))
        if signed and little_ordered and (little_ordered[-1] & 0x80):
            n -= 1 << 8*len(little_ordered)
    
        return n
    
    31 (depending on whether the
    def from_bytes(bytes, byteorder='big', signed=False):
        if byteorder == 'little':
            little_ordered = list(bytes)
        elif byteorder == 'big':
            little_ordered = list(reversed(bytes))
        else:
            raise ValueError("byteorder must be either 'little' or 'big'")
    
        n = sum(b << i*8 for i, b in enumerate(little_ordered))
        if signed and little_ordered and (little_ordered[-1] & 0x80):
            n -= 1 << 8*len(little_ordered)
    
        return n
    
    12 or
    def from_bytes(bytes, byteorder='big', signed=False):
        if byteorder == 'little':
            little_ordered = list(bytes)
        elif byteorder == 'big':
            little_ordered = list(reversed(bytes))
        else:
            raise ValueError("byteorder must be either 'little' or 'big'")
    
        n = sum(b << i*8 for i, b in enumerate(little_ordered))
        if signed and little_ordered and (little_ordered[-1] & 0x80):
            n -= 1 << 8*len(little_ordered)
    
        return n
    
    13 format was used) to be inserted before the first digit

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

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

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

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

  5. If precision is

    def from_bytes(bytes, byteorder='big', signed=False):
        if byteorder == 'little':
            little_ordered = list(bytes)
        elif byteorder == 'big':
            little_ordered = list(reversed(bytes))
        else:
            raise ValueError("byteorder must be either 'little' or 'big'")
    
        n = sum(b << i*8 for i, b in enumerate(little_ordered))
        if signed and little_ordered and (little_ordered[-1] & 0x80):
            n -= 1 << 8*len(little_ordered)
    
        return n
    
    34, the output is truncated to
    def from_bytes(bytes, byteorder='big', signed=False):
        if byteorder == 'little':
            little_ordered = list(bytes)
        elif byteorder == 'big':
            little_ordered = list(reversed(bytes))
        else:
            raise ValueError("byteorder must be either 'little' or 'big'")
    
        n = sum(b << i*8 for i, b in enumerate(little_ordered))
        if signed and little_ordered and (little_ordered[-1] & 0x80):
            n -= 1 << 8*len(little_ordered)
    
        return n
    
    34 characters

  6. See PEP 237

Since Python strings have an explicit length,

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

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

    return n
36 conversions do not assume that
def from_bytes(bytes, byteorder='big', signed=False):
    if byteorder == 'little':
        little_ordered = list(bytes)
    elif byteorder == 'big':
        little_ordered = list(reversed(bytes))
    else:
        raise ValueError("byteorder must be either 'little' or 'big'")

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

    return n
37 is the end of the string

Changed in version 3. 1.

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

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

    return n
38 conversions for numbers whose absolute value is over 1e50 are no longer replaced by
def from_bytes(bytes, byteorder='big', signed=False):
    if byteorder == 'little':
        little_ordered = list(bytes)
    elif byteorder == 'big':
        little_ordered = list(reversed(bytes))
    else:
        raise ValueError("byteorder must be either 'little' or 'big'")

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

    return n
39 conversions.

Binary Sequence Types — , ,

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

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

Bytes Objects

Objek byte adalah urutan byte tunggal yang tidak dapat diubah. Since many major binary protocols are based on the ASCII text encoding, bytes objects offer several methods that are only valid when working with ASCII compatible data and are closely related to string objects in a variety of other ways

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

Firstly, the syntax for bytes literals is largely the same as that for string literals, except that a

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

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

    return n
47 prefix is added

  • Single quotes.

    def from_bytes(bytes, byteorder='big', signed=False):
        if byteorder == 'little':
            little_ordered = list(bytes)
        elif byteorder == 'big':
            little_ordered = list(reversed(bytes))
        else:
            raise ValueError("byteorder must be either 'little' or 'big'")
    
        n = sum(b << i*8 for i, b in enumerate(little_ordered))
        if signed and little_ordered and (little_ordered[-1] & 0x80):
            n -= 1 << 8*len(little_ordered)
    
        return n
    
    48

  • Double quotes.

    def from_bytes(bytes, byteorder='big', signed=False):
        if byteorder == 'little':
            little_ordered = list(bytes)
        elif byteorder == 'big':
            little_ordered = list(reversed(bytes))
        else:
            raise ValueError("byteorder must be either 'little' or 'big'")
    
        n = sum(b << i*8 for i, b in enumerate(little_ordered))
        if signed and little_ordered and (little_ordered[-1] & 0x80):
            n -= 1 << 8*len(little_ordered)
    
        return n
    
    49

  • Triple quoted.

    def from_bytes(bytes, byteorder='big', signed=False):
        if byteorder == 'little':
            little_ordered = list(bytes)
        elif byteorder == 'big':
            little_ordered = list(reversed(bytes))
        else:
            raise ValueError("byteorder must be either 'little' or 'big'")
    
        n = sum(b << i*8 for i, b in enumerate(little_ordered))
        if signed and little_ordered and (little_ordered[-1] & 0x80):
            n -= 1 << 8*len(little_ordered)
    
        return n
    
    50,
    def from_bytes(bytes, byteorder='big', signed=False):
        if byteorder == 'little':
            little_ordered = list(bytes)
        elif byteorder == 'big':
            little_ordered = list(reversed(bytes))
        else:
            raise ValueError("byteorder must be either 'little' or 'big'")
    
        n = sum(b << i*8 for i, b in enumerate(little_ordered))
        if signed and little_ordered and (little_ordered[-1] & 0x80):
            n -= 1 << 8*len(little_ordered)
    
        return n
    
    51

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

As with string literals, bytes literals may also use a

>>> (65).to_bytes()
b'A'
62 prefix to disable processing of escape sequences. See for more about the various forms of bytes literal, including supported escape sequences

While bytes literals and representations are based on ASCII text, bytes objects actually behave like immutable sequences of integers, with each value in the sequence restricted such that

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

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

    return n
53 (attempts to violate this restriction will trigger ). This is done deliberately to emphasise that while many binary formats include ASCII based elements and can be usefully manipulated with some text-oriented algorithms, this is not generally the case for arbitrary binary data (blindly applying text processing algorithms to binary data formats that are not ASCII compatible will usually lead to data corruption)

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

  • A zero-filled bytes object of a specified length.

    def from_bytes(bytes, byteorder='big', signed=False):
        if byteorder == 'little':
            little_ordered = list(bytes)
        elif byteorder == 'big':
            little_ordered = list(reversed(bytes))
        else:
            raise ValueError("byteorder must be either 'little' or 'big'")
    
        n = sum(b << i*8 for i, b in enumerate(little_ordered))
        if signed and little_ordered and (little_ordered[-1] & 0x80):
            n -= 1 << 8*len(little_ordered)
    
        return n
    
    55

  • From an iterable of integers.

    def from_bytes(bytes, byteorder='big', signed=False):
        if byteorder == 'little':
            little_ordered = list(bytes)
        elif byteorder == 'big':
            little_ordered = list(reversed(bytes))
        else:
            raise ValueError("byteorder must be either 'little' or 'big'")
    
        n = sum(b << i*8 for i, b in enumerate(little_ordered))
        if signed and little_ordered and (little_ordered[-1] & 0x80):
            n -= 1 << 8*len(little_ordered)
    
        return n
    
    56

  • Copying existing binary data via the buffer protocol.

    def from_bytes(bytes, byteorder='big', signed=False):
        if byteorder == 'little':
            little_ordered = list(bytes)
        elif byteorder == 'big':
            little_ordered = list(reversed(bytes))
        else:
            raise ValueError("byteorder must be either 'little' or 'big'")
    
        n = sum(b << i*8 for i, b in enumerate(little_ordered))
        if signed and little_ordered and (little_ordered[-1] & 0x80):
            n -= 1 << 8*len(little_ordered)
    
        return n
    
    57

Also see the built-in

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

classmethod fromhex(string)

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

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

Changed in version 3. 7. now skips all ASCII whitespace in the string, not just spaces.

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

hex([sep[ , bytes_per_sep]])

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

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

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

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

New in version 3. 5

Changed in version 3. 8. now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output.

Since bytes objects are sequences of integers (akin to a tuple), for a bytes object b,

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

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

    return n
61 will be an integer, while
def from_bytes(bytes, byteorder='big', signed=False):
    if byteorder == 'little':
        little_ordered = list(bytes)
    elif byteorder == 'big':
        little_ordered = list(reversed(bytes))
    else:
        raise ValueError("byteorder must be either 'little' or 'big'")

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

    return n
62 will be a bytes object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1)

The representation of bytes objects uses the literal format (

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

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

    return n
63) since it is often more useful than e. g.
def from_bytes(bytes, byteorder='big', signed=False):
    if byteorder == 'little':
        little_ordered = list(bytes)
    elif byteorder == 'big':
        little_ordered = list(reversed(bytes))
    else:
        raise ValueError("byteorder must be either 'little' or 'big'")

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

    return n
64. You can always convert a bytes object into a list of integers using
def from_bytes(bytes, byteorder='big', signed=False):
    if byteorder == 'little':
        little_ordered = list(bytes)
    elif byteorder == 'big':
        little_ordered = list(reversed(bytes))
    else:
        raise ValueError("byteorder must be either 'little' or 'big'")

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

    return n
65

Bytearray Objects

objects are a mutable counterpart to objects

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

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

  • Creating an empty instance.

    def from_bytes(bytes, byteorder='big', signed=False):
        if byteorder == 'little':
            little_ordered = list(bytes)
        elif byteorder == 'big':
            little_ordered = list(reversed(bytes))
        else:
            raise ValueError("byteorder must be either 'little' or 'big'")
    
        n = sum(b << i*8 for i, b in enumerate(little_ordered))
        if signed and little_ordered and (little_ordered[-1] & 0x80):
            n -= 1 << 8*len(little_ordered)
    
        return n
    
    68

  • Creating a zero-filled instance with a given length.

    def from_bytes(bytes, byteorder='big', signed=False):
        if byteorder == 'little':
            little_ordered = list(bytes)
        elif byteorder == 'big':
            little_ordered = list(reversed(bytes))
        else:
            raise ValueError("byteorder must be either 'little' or 'big'")
    
        n = sum(b << i*8 for i, b in enumerate(little_ordered))
        if signed and little_ordered and (little_ordered[-1] & 0x80):
            n -= 1 << 8*len(little_ordered)
    
        return n
    
    69

  • From an iterable of integers.

    def from_bytes(bytes, byteorder='big', signed=False):
        if byteorder == 'little':
            little_ordered = list(bytes)
        elif byteorder == 'big':
            little_ordered = list(reversed(bytes))
        else:
            raise ValueError("byteorder must be either 'little' or 'big'")
    
        n = sum(b << i*8 for i, b in enumerate(little_ordered))
        if signed and little_ordered and (little_ordered[-1] & 0x80):
            n -= 1 << 8*len(little_ordered)
    
        return n
    
    70

  • Copying existing binary data via the buffer protocol.

    def from_bytes(bytes, byteorder='big', signed=False):
        if byteorder == 'little':
            little_ordered = list(bytes)
        elif byteorder == 'big':
            little_ordered = list(reversed(bytes))
        else:
            raise ValueError("byteorder must be either 'little' or 'big'")
    
        n = sum(b << i*8 for i, b in enumerate(little_ordered))
        if signed and little_ordered and (little_ordered[-1] & 0x80):
            n -= 1 << 8*len(little_ordered)
    
        return n
    
    71

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

Also see the built-in

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

classmethod fromhex(string)

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

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

Changed in version 3. 7. now skips all ASCII whitespace in the string, not just spaces.

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

hex([sep[ , bytes_per_sep]])

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

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

New in version 3. 5

Changed in version 3. 8. Similar to , now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output.

Since bytearray objects are sequences of integers (akin to a list), for a bytearray object b,

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

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

    return n
61 will be an integer, while
def from_bytes(bytes, byteorder='big', signed=False):
    if byteorder == 'little':
        little_ordered = list(bytes)
    elif byteorder == 'big':
        little_ordered = list(reversed(bytes))
    else:
        raise ValueError("byteorder must be either 'little' or 'big'")

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

    return n
62 will be a bytearray object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1)

The representation of bytearray objects uses the bytes literal format (

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

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

    return n
78) since it is often more useful than e. g.
def from_bytes(bytes, byteorder='big', signed=False):
    if byteorder == 'little':
        little_ordered = list(bytes)
    elif byteorder == 'big':
        little_ordered = list(reversed(bytes))
    else:
        raise ValueError("byteorder must be either 'little' or 'big'")

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

    return n
_79. You can always convert a bytearray object into a list of integers using
def from_bytes(bytes, byteorder='big', signed=False):
    if byteorder == 'little':
        little_ordered = list(bytes)
    elif byteorder == 'big':
        little_ordered = list(reversed(bytes))
    else:
        raise ValueError("byteorder must be either 'little' or 'big'")

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

    return n
65

Bytes and Bytearray Operations

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

Note

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

>>> (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'
9

and

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

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

Note

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

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

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

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

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

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

Changed in version 3. 3. Also accept an integer in the range 0 to 255 as the subsequence.

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

If the binary data starts with the prefix string, return

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

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

    return n
81. Otherwise, return a copy of the original binary data

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

The prefix may be any

Note

Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan

New in version 3. 9

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

If the binary data ends with the suffix string and that suffix is not empty, return

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

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

    return n
82. Otherwise, return a copy of the original binary data

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

The suffix may be any

Note

Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan

New in version 3. 9

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

Return the bytes decoded to a

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 decoding 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, and any other name registered via . See for details

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

Note

Passing the encoding argument to allows decoding any directly, without needing to make a temporary

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

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 .

byte. endswith(suffix[ , start[ , end]])bytearray. 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 binary data 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

The suffix(es) to search for may be any

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

Return the lowest index in the data where the subsequence sub is found, such that sub is contained in the slice

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

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

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

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

Changed in version 3. 3. Also accept an integer in the range 0 to 255 as the subsequence.

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

Like , but raise when the subsequence 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. join(iterable)bytearray. join(iterable)

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

statis byte. maketrans(from , to)static bytearray. maketrans(from , to)

This static method returns a translation table usable for that will map each character in from into the character at the same position in to; from and to must both be and have the same length

Baru di versi 3. 1

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

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

The separator to search for may be any

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

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

The subsequence to search for and its replacement may be any

Note

Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan

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

Return the highest index in the sequence where the subsequence sub is found, such that sub is contained within

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

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

The separator to search for may be any

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

Return

def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6
56 if the binary data starts with the specified prefix, otherwise return
def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6
38. prefix can also be a tuple of prefixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position

The prefix(es) to search for may be any

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

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

You can use the method to create a translation table

Set the table argument to

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

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

Changed in version 3. 6. delete is now supported as a keyword argument.

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

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

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

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

Note

Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan

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

Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan

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

Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan

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

Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan

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

Split the binary sequence into subsequences of the same type, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or

def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6
31, any subsequence consisting solely of ASCII whitespace is a separator. Except for splitting from the right, behaves like which is described in detail below

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

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

def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6
31, the chars argument defaults to removing ASCII whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped

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

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

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

Note

Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan

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

Pisahkan urutan biner menjadi suburutan dengan jenis yang sama, menggunakan sep sebagai string pembatas. 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)

Jika sep diberikan, pembatas berurutan tidak dikelompokkan bersama dan dianggap membatasi urutan kosong (misalnya,

>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
27 mengembalikan
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
28). Argumen sep dapat terdiri dari urutan multibyte (misalnya,
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
29 mengembalikan
>>> (-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([karakter] . )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

Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan

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

Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan

bytes. perluas tab(ukuran tab=8 . )bytearray.expandtabs(ukuran tab=8)

Kembalikan salinan urutan di mana semua karakter tab ASCII diganti dengan satu atau lebih spasi ASCII, bergantung pada kolom saat ini dan ukuran tab yang diberikan. Posisi tab terjadi setiap byte tabsize (default adalah 8, memberikan posisi tab pada kolom 0, 8, 16 dan seterusnya). Untuk memperluas urutan, kolom saat ini diatur ke nol dan urutan diperiksa byte demi byte. Jika byte adalah karakter tab ASCII (

>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
36), satu atau lebih karakter spasi dimasukkan ke dalam hasil hingga kolom saat ini sama dengan posisi tab berikutnya. (Karakter tab itu sendiri tidak disalin. ) Jika byte saat ini adalah baris baru ASCII (
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
37) atau carriage return (
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
38), ini akan disalin dan kolom saat ini disetel ulang ke nol. Nilai byte lainnya disalin tidak berubah dan kolom saat ini bertambah satu terlepas dari bagaimana nilai byte direpresentasikan saat dicetak

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

Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan

byte. isalnum()bytearray. isalnum()

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 semua byte dalam urutan adalah karakter ASCII abjad atau angka desimal ASCII dan urutannya tidak 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
38 jika tidak. Karakter ASCII alfabetis adalah nilai byte dalam urutan
>>> (-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

byte. isalpha()bytearray. isalpha()

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 semua byte dalam urutan adalah karakter ASCII abjad dan urutannya tidak 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
38 jika tidak. Karakter ASCII alfabetis adalah nilai byte dalam urutan
>>> (-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

byte. isascii()bytearray. isascii()

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 urutan kosong atau semua byte dalam urutan adalah 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 sebaliknya. Byte ASCII berada dalam kisaran 0-0x7F

New in version 3. 7

byte. isdigit()bytearray. angka()

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. Digit desimal ASCII adalah nilai byte dalam urutan
>>> (-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

byte. lebih rendah()bytearray. lebih rendah()

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 setidaknya ada satu karakter ASCII huruf kecil dalam urutan dan tidak ada karakter ASCII huruf besar,
def bit_length(self):
    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 tidak

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

Karakter ASCII huruf kecil adalah nilai byte dalam urutan

>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
53. Karakter ASCII huruf besar adalah nilai byte dalam urutan
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
54

byte. isspace()bytearray. isspace()

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 semua byte dalam urutan adalah spasi putih ASCII dan urutannya tidak 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
38 jika tidak. Karakter spasi putih ASCII adalah nilai byte dalam urutan
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
57 (spasi, tab, baris baru, carriage return, tab vertikal, umpan formulir)

byte. istitle()bytearray. istitle()

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 urutannya adalah huruf judul ASCII dan urutannya tidak 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
38 jika tidak. Lihat untuk detail lebih lanjut tentang definisi "titlecase"

For example

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

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

byte. persediaan()bytearray. supper()

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 setidaknya ada satu karakter ASCII alfabet huruf besar dalam urutan dan tidak ada karakter ASCII huruf kecil,
def bit_length(self):
    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 tidak

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

Karakter ASCII huruf kecil adalah nilai byte dalam urutan

>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
53. Karakter ASCII huruf besar adalah nilai byte dalam urutan
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
54

byte. bawah()bytearray. lebih rendah()

Kembalikan salinan urutan dengan semua karakter ASCII huruf besar yang dikonversi ke pasangan huruf kecil yang sesuai

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

Karakter ASCII huruf kecil adalah nilai byte dalam urutan

>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
53. Karakter ASCII huruf besar adalah nilai byte dalam urutan
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
54

Note

Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan

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

Kembalikan daftar garis dalam urutan biner, putus pada batas garis ASCII. Metode ini menggunakan pendekatan pemisahan garis. 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

byte. swapcase()bytearray. swapcase()

Kembalikan salinan urutan dengan semua karakter ASCII huruf kecil yang dikonversi ke pasangan huruf besar yang sesuai dan sebaliknya

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

Karakter ASCII huruf kecil adalah nilai byte dalam urutan

>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
53. Karakter ASCII huruf besar adalah nilai byte dalam urutan
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
54

Tidak seperti , selalu demikian

>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
71 untuk versi biner. Konversi kasus bersifat simetris dalam ASCII, meskipun hal itu umumnya tidak berlaku untuk poin kode Unicode arbitrer

Note

Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan

byte. judul()bytearray. judul()

Mengembalikan versi huruf-huruf dari urutan biner di mana kata-kata dimulai dengan karakter ASCII huruf besar dan karakter yang tersisa adalah huruf kecil. Nilai byte tanpa huruf dibiarkan tidak dimodifikasi

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

Karakter ASCII huruf kecil adalah nilai byte dalam urutan

>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
53. Karakter ASCII huruf besar adalah nilai byte dalam urutan
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
54. Semua nilai byte lainnya tidak di-uncase

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

Solusi untuk apostrof dapat dibangun menggunakan ekspresi reguler

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

Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan

byte. atas()bytearray. atas()

Kembalikan salinan urutan dengan semua karakter ASCII huruf kecil yang dikonversi ke pasangan huruf besar yang sesuai

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

Karakter ASCII huruf kecil adalah nilai byte dalam urutan

>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
53. Karakter ASCII huruf besar adalah nilai byte dalam urutan
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
54

Note

Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan

byte. zisi(lebar)bytearray. zisi(lebar)

Mengembalikan salinan urutan kiri diisi dengan ASCII

>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
76 digit untuk membuat urutan panjang lebar. Prefiks tanda depan (
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
77/
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
78) ditangani dengan menyisipkan padding setelah karakter tanda, bukan sebelumnya. Untuk objek, urutan aslinya dikembalikan jika lebarnya kurang dari atau sama dengan
>>> (-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

Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan

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

Operasi pemformatan yang dijelaskan di sini menunjukkan berbagai keanehan yang menyebabkan sejumlah kesalahan umum (seperti gagal menampilkan tupel dan kamus dengan benar). Jika nilai yang dicetak mungkin berupa tupel atau kamus, bungkus dalam tuple

Objek byte (

>>> (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) memiliki satu operasi bawaan yang unik. operator
>>> 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 (modulo). Ini juga dikenal sebagai pemformatan byte atau operator interpolasi. 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
_84 (di mana format adalah objek byte),
>>> 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 spesifikasi konversi dalam format diganti dengan nol atau lebih elemen nilai. Efeknya mirip dengan menggunakan
>>> 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 dalam bahasa C

Jika format memerlukan argumen tunggal, nilai mungkin merupakan objek non-tupel tunggal. Jika tidak, nilai harus berupa tuple dengan jumlah persis item yang ditentukan oleh objek format byte, atau objek pemetaan tunggal (misalnya, kamus)

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

Ketika argumen yang tepat adalah kamus (atau tipe pemetaan lainnya), maka format dalam objek byte harus menyertakan kunci pemetaan dalam tanda kurung ke dalam kamus yang dimasukkan tepat setelah karakter

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

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

Meaning

>>> 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 << i*8 for i, b in enumerate(little_ordered))
    if signed and little_ordered and (little_ordered[-1] & 0x80):
        n -= 1 << 8*len(little_ordered)

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

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

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

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

    return n
04) may be present, but is ignored as it is not necessary for Python – so e. g.
def from_bytes(bytes, byteorder='big', signed=False):
    if byteorder == 'little':
        little_ordered = list(bytes)
    elif byteorder == 'big':
        little_ordered = list(reversed(bytes))
    else:
        raise ValueError("byteorder must be either 'little' or 'big'")

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

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

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

    return n
06

The conversion types are

Conversion

Meaning

Catatan

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

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

    return n
07

Signed integer decimal

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

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

    return n
08

Signed integer decimal

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

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

    return n
09

Signed octal value

(1)

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

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

    return n
10

Obsolete type – it is identical to

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

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

    return n
07

(8)

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

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

    return n
12

Signed hexadecimal (lowercase)

(2)

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

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

    return n
13

Heksadesimal bertanda (huruf besar)

(2)

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

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

    return n
14

Floating point exponential format (lowercase)

(3)

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

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

    return n
15

Floating point exponential format (uppercase)

(3)

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

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

    return n
16

Floating point decimal format

(3)

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

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

    return n
17

Floating point decimal format

(3)

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

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

    return n
_18

Format titik mengambang. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise

(4)

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

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

    return n
19

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

(4)

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

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

    return n
20

Single byte (menerima objek integer atau single byte)

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

Byte (objek apa pun yang mengikuti atau memiliki

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

(5)

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

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

    return n
23

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

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

    return n
_23 adalah alias 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
022 dan hanya boleh digunakan untuk basis kode Python2/3

(6)

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

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

    return n
25

Byte (mengonversi objek Python apa pun 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
028)

(5)

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

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

    return n
21

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

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

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

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

    return n
25 dan hanya boleh digunakan untuk basis kode Python2/3

(7)

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

No argument is converted, results in 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
87 character in the result

Catatan

  1. The alternate form causes a leading octal specifier (

    def from_bytes(bytes, byteorder='big', signed=False):
        if byteorder == 'little':
            little_ordered = list(bytes)
        elif byteorder == 'big':
            little_ordered = list(reversed(bytes))
        else:
            raise ValueError("byteorder must be either 'little' or 'big'")
    
        n = sum(b << i*8 for i, b in enumerate(little_ordered))
        if signed and little_ordered and (little_ordered[-1] & 0x80):
            n -= 1 << 8*len(little_ordered)
    
        return n
    
    29) to be inserted before the first digit

  2. The alternate form causes a leading

    def from_bytes(bytes, byteorder='big', signed=False):
        if byteorder == 'little':
            little_ordered = list(bytes)
        elif byteorder == 'big':
            little_ordered = list(reversed(bytes))
        else:
            raise ValueError("byteorder must be either 'little' or 'big'")
    
        n = sum(b << i*8 for i, b in enumerate(little_ordered))
        if signed and little_ordered and (little_ordered[-1] & 0x80):
            n -= 1 << 8*len(little_ordered)
    
        return n
    
    30 or
    def from_bytes(bytes, byteorder='big', signed=False):
        if byteorder == 'little':
            little_ordered = list(bytes)
        elif byteorder == 'big':
            little_ordered = list(reversed(bytes))
        else:
            raise ValueError("byteorder must be either 'little' or 'big'")
    
        n = sum(b << i*8 for i, b in enumerate(little_ordered))
        if signed and little_ordered and (little_ordered[-1] & 0x80):
            n -= 1 << 8*len(little_ordered)
    
        return n
    
    31 (depending on whether the
    def from_bytes(bytes, byteorder='big', signed=False):
        if byteorder == 'little':
            little_ordered = list(bytes)
        elif byteorder == 'big':
            little_ordered = list(reversed(bytes))
        else:
            raise ValueError("byteorder must be either 'little' or 'big'")
    
        n = sum(b << i*8 for i, b in enumerate(little_ordered))
        if signed and little_ordered and (little_ordered[-1] & 0x80):
            n -= 1 << 8*len(little_ordered)
    
        return n
    
    12 or
    def from_bytes(bytes, byteorder='big', signed=False):
        if byteorder == 'little':
            little_ordered = list(bytes)
        elif byteorder == 'big':
            little_ordered = list(reversed(bytes))
        else:
            raise ValueError("byteorder must be either 'little' or 'big'")
    
        n = sum(b << i*8 for i, b in enumerate(little_ordered))
        if signed and little_ordered and (little_ordered[-1] & 0x80):
            n -= 1 << 8*len(little_ordered)
    
        return n
    
    13 format was used) to be inserted before the first digit

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

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

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

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

  5. If precision is

    def from_bytes(bytes, byteorder='big', signed=False):
        if byteorder == 'little':
            little_ordered = list(bytes)
        elif byteorder == 'big':
            little_ordered = list(reversed(bytes))
        else:
            raise ValueError("byteorder must be either 'little' or 'big'")
    
        n = sum(b << i*8 for i, b in enumerate(little_ordered))
        if signed and little_ordered and (little_ordered[-1] & 0x80):
            n -= 1 << 8*len(little_ordered)
    
        return n
    
    34, the output is truncated to
    def from_bytes(bytes, byteorder='big', signed=False):
        if byteorder == 'little':
            little_ordered = list(bytes)
        elif byteorder == 'big':
            little_ordered = list(reversed(bytes))
        else:
            raise ValueError("byteorder must be either 'little' or 'big'")
    
        n = sum(b << i*8 for i, b in enumerate(little_ordered))
        if signed and little_ordered and (little_ordered[-1] & 0x80):
            n -= 1 << 8*len(little_ordered)
    
        return n
    
    34 characters

  6. def bit_length(self):
        s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
        s = s.lstrip('-0b') # remove leading zeros and minus sign
        return len(s)       # len('100101') --> 6
    
    041 is deprecated, but will not be removed during the 3. seri x

  7. def bit_length(self):
        s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
        s = s.lstrip('-0b') # remove leading zeros and minus sign
        return len(s)       # len('100101') --> 6
    
    _042 sudah usang, tetapi tidak akan dihapus selama 3. seri x

  8. See PEP 237

Note

Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan

See also

PEP 461 - Menambahkan % pemformatan ke byte dan bytearray

New in version 3. 5

Tampilan Memori

objek memungkinkan kode Python untuk mengakses data internal objek yang mendukung tanpa menyalin

kelas memoryview(objek)

Buat objek referensi itu. objek harus mendukung protokol buffer. Objek bawaan yang mendukung protokol buffer termasuk dan

A memiliki gagasan tentang elemen, yang merupakan unit memori atom yang ditangani oleh objek asal. Untuk banyak tipe sederhana seperti and , sebuah elemen berukuran satu byte, tetapi tipe lain seperti mungkin memiliki elemen yang lebih besar

def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6
_051 sama dengan panjang. 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
_053, panjangnya 1. 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
_054, panjangnya sama dengan jumlah elemen dalam tampilan. Untuk dimensi yang lebih tinggi, panjangnya sama dengan panjang representasi daftar bersarang dari tampilan. Atribut akan memberi Anda jumlah byte dalam satu elemen

A mendukung pemotongan dan pengindeksan untuk mengekspos datanya. Pemotongan satu dimensi akan menghasilkan subview

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

Jika adalah salah satu penentu format asli dari modul, pengindeksan dengan bilangan bulat atau tupel bilangan bulat juga didukung dan mengembalikan satu elemen dengan tipe yang benar. Tampilan memori satu dimensi dapat diindeks dengan integer atau tuple satu integer. Tampilan memori multi-dimensi dapat diindeks dengan tupel bilangan bulat ndim yang tepat di mana ndim adalah jumlah dimensi. Tampilan memori nol dimensi dapat diindeks dengan tuple kosong

Berikut adalah contoh dengan format non-byte

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

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

    return n
_0

Jika objek yang mendasarinya dapat ditulisi, tampilan memori mendukung penugasan irisan satu dimensi. Resizing is not allowed

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

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

    return n
1

Tampilan memori satu dimensi dari tipe hashable (read-only) dengan format 'B', 'b' atau 'c' juga hashable. Hash didefinisikan 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
_059

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

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

    return n
_2

Berubah di versi 3. 3. Tampilan memori satu dimensi sekarang dapat dipotong. Tampilan memori satu dimensi dengan format 'B', 'b' atau 'c' kini dapat di-hash.

Berubah di versi 3. 4. memoryview sekarang terdaftar secara otomatis dengan

Berubah di versi 3. 5. memoryview sekarang dapat diindeks dengan tuple bilangan bulat.

memiliki beberapa metode

__eq__(eksportir)

Tampilan memori dan pengekspor PEP 3118 sama jika bentuknya sama dan jika semua nilai yang sesuai sama ketika kode format masing-masing operan ditafsirkan menggunakan sintaks

Untuk subset string format yang saat ini didukung oleh ,

def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6
065 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
066 sama 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
067

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

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

    return n
_3

Jika salah satu string format tidak didukung oleh modul, maka objek akan selalu dibandingkan sebagai tidak sama (bahkan jika string format dan konten buffer identik)

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

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

    return n
_4

Note that, as with floating point numbers,

def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6
069 does not imply
def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6
070 for memoryview objects

Berubah di versi 3. 3. Versi sebelumnya membandingkan memori mentah dengan mengabaikan format item dan struktur array logis.

tobyte(pesanan='C')

Kembalikan data dalam buffer sebagai bytestring. Ini sama dengan memanggil konstruktor pada tampilan memori

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

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

    return n
_5

Untuk array yang tidak bersebelahan, hasilnya sama dengan representasi daftar yang diratakan dengan semua elemen dikonversi menjadi byte. mendukung semua string format, termasuk yang tidak ada dalam sintaks modul

Baru di versi 3. 8. pesanan bisa {‘C’, ‘F’, ‘A’}. Ketika pesanan adalah 'C' atau 'F', data dari larik asli diubah menjadi pesanan C atau Fortran. Untuk tampilan yang berdekatan, 'A' mengembalikan salinan persis dari memori fisik. Secara khusus, urutan Fortran dalam memori dipertahankan. Untuk tampilan yang tidak bersebelahan, data dikonversi ke C terlebih dahulu. order=None sama dengan order=’C’.

hex([sep[ , bytes_per_sep]])

Mengembalikan objek string yang berisi dua digit heksadesimal untuk setiap byte dalam buffer

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

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

    return n
_6

New in version 3. 5

Changed in version 3. 8. Similar to , now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output.

daftar()

Return the data in the buffer as a list of elements

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

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

    return n
_7

Berubah di versi 3. 3. sekarang mendukung semua format asli karakter tunggal dalam sintaks modul serta representasi multidimensi.

hanya untuk dibaca()

Mengembalikan versi readonly dari objek memoryview. Objek memoryview asli tidak berubah

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

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

    return n
_8

Baru di versi 3. 8

rilis()

Lepaskan buffer dasar yang diekspos oleh objek memoryview. Banyak objek mengambil tindakan khusus saat tampilan diadakan padanya (misalnya, a akan melarang pengubahan ukuran untuk sementara);

Setelah metode ini dipanggil, setiap operasi lebih lanjut pada tampilan akan memunculkan a (kecuali dirinya sendiri yang dapat dipanggil berkali-kali)

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

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

    return n
_9

Protokol manajemen konteks dapat digunakan untuk efek serupa, menggunakan 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

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

Baru di versi 3. 2

transmisikan(format[ , shape])

Transmisikan tampilan memori ke format atau bentuk baru. bentuk 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
_082, yang berarti bahwa tampilan hasil akan menjadi satu dimensi. Nilai yang dikembalikan adalah tampilan memori baru, tetapi buffer itu sendiri tidak disalin. Cast yang didukung adalah 1D -> C- dan C-contiguous -> 1D

The destination format is restricted to a single element native format in syntax. Salah satu format harus format byte ('B', 'b' atau 'c'). Panjang byte hasil harus sama dengan panjang aslinya

Cast 1D/panjang ke 1D/unsigned byte

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

Cast 1D/unsigned byte ke 1D/char

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

Cast 1D/bytes ke 3D/ints ke 1D/signed char

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

Transmisikan 1D/unsigned long ke 2D/unsigned long

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

New in version 3. 3

Berubah di versi 3. 5. Format sumber tidak lagi dibatasi saat mentransmisi ke tampilan byte.

Ada juga beberapa atribut readonly yang tersedia

obj

Objek yang mendasari tampilan memori

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

New in version 3. 3

nbytes

def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6
_084. Ini adalah jumlah ruang dalam byte yang akan digunakan array dalam representasi yang berdekatan. It is not necessarily equal to
def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6
085

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

Array multi-dimensi

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

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

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. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. (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 <= other

Uji apakah setiap elemen di himpunan ada di yang lain

setel < lainnya

Uji apakah himpunan tersebut merupakan subhimpunan 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
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

union(*others)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). A set is less than another set if and only if the first set is a proper subset of the second set (is a subset, but is not equal). 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. 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
_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()

Remove and return an arbitrary element from the 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

  • Use a dict comprehension.

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

  • 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. Jika kunci muncul lebih dari sekali, nilai terakhir untuk kunci tersebut menjadi nilai yang sesuai di kamus baru

Jika argumen kata kunci diberikan, argumen kata kunci dan nilainya ditambahkan ke kamus yang dibuat dari argumen posisi. 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[key]

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

Contoh di atas menunjukkan bagian dari implementasi. 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. Untuk mendapatkan nilai yang berbeda, gunakan a sebagai gantinya

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. Di versi sebelumnya, akan mengembalikan pasangan kunci/nilai arbitrer.

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

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. Ini juga berlaku saat membandingkan
def bit_length(self):
    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 dengan dirinya sendiri

def bit_length(self):
    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 .

Dictionaries preserve insertion order. 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)

Return an iterator over the keys, values or items (represented as tuples 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
197) in the dictionary

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. Urutan kamus dijamin menjadi urutan penyisipan.

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

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. Dictionary views are now reversible.

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. Ini diimplementasikan menggunakan sepasang metode yang memungkinkan kelas yang ditentukan pengguna untuk menentukan konteks runtime yang dimasukkan sebelum badan pernyataan dieksekusi dan keluar saat pernyataan berakhir

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

An example of a context manager that returns a related object is the one returned by . These managers set the active decimal context to a copy of the original decimal context and then return the copy. 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. Pengecualian yang terjadi selama eksekusi metode ini akan menggantikan setiap pengecualian yang terjadi di badan 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

Pengecualian yang diteruskan tidak boleh dimunculkan kembali secara eksplisit - sebagai gantinya, metode ini harus mengembalikan nilai salah untuk menunjukkan bahwa metode 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 — ,

The core built-in types for are and

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

Untuk kelas wadah, argumen yang diberikan ke salah satu kelas dapat menunjukkan jenis elemen yang dikandung objek. 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 << i*8 for i, b in enumerate(little_ordered))
        if signed and little_ordered and (little_ordered[-1] & 0x80):
            n -= 1 << 8*len(little_ordered)
    
        return n
    
    47 untuk ),
    def bit_count(self):
        return bin(self).count("1")
    
    31 juga akan menjadi turunan 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
    
    280, tetapi 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
    
    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. For example, a function expecting a containing elements

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

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. Saat membuat objek wadah 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, elemen dalam wadah tidak dicentang berdasarkan jenisnya. 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

However, such expressions are valid when are used. 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

Dokumentasi tentang cara mengimplementasikan kelas generik yang dapat diparameterisasi saat runtime dan dipahami oleh pemeriksa tipe statis

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

Mendefinisikan objek gabungan yang menampung tipe X, Y, dan seterusnya.

def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6
373 means either X or Y. 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

Jenis yang terpapar pengguna untuk objek gabungan dapat diakses dari dan digunakan untuk pemeriksaan. Objek tidak dapat dibuat dari jenisnya

def bit_length(self):
    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

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
383 untuk objek tipe ditambahkan untuk mendukung sintaks
def bit_length(self):
    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 mengusulkan sintaks

def bit_length(self):
    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 dan tipe Union

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. Atribut modul dapat ditugaskan ke. (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. Jika diambil dari file, 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
398

Kelas dan Contoh Kelas

Lihat dan untuk ini

Fungsi

Objek fungsi dibuat dengan definisi fungsi. Satu-satunya operasi pada objek fungsi adalah memanggilnya.

def bit_length(self):
    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. Built-in methods are described with the types that support them

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). Saat dipanggil, 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
_401 akan ditambahkan ke daftar argumen. Metode terikat memiliki dua atribut read-only khusus.
def bit_length(self):
    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. 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
404 sama persis dengan menelepon
def bit_length(self):
    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

Seperti objek fungsi, objek metode terikat mendukung mendapatkan atribut arbitrer. Namun, karena atribut metode sebenarnya disimpan 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
406), menyetel atribut metode pada metode terikat tidak diperbolehkan. 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. Objek kode dikembalikan oleh fungsi bawaan dan dapat diekstraksi dari objek fungsi melalui 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
409 mereka. 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. An object’s type is accessed by the built-in function . 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. Tepatnya ada satu objek nol, bernama

def bit_length(self):
    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 (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
_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. There is exactly one

def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6
428 object.
def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6
_429 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)

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

Objek Internal

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

class. __basis__

Tuple kelas dasar dari objek kelas

definisi. __nama__

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

definisi. __qualname__

Kelas, fungsi, metode, deskriptor, atau instance generator

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. Even the best known algorithms for base 10 have sub-quadratic complexity. 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

Apa yang dilakukan trim () dengan Python?

Sekilas string trim python. Memotong string dengan Python berarti menghilangkan spasi ekstra putih atau grup karakter tertentu dari awal dan akhir string input. You can trim a string in Python using three built-in functions. strip() , lstrip(), rstrip() metode masing-masing

Bagaimana cara menghapus nilai tertentu dari indeks daftar?

Anda dapat menggunakan metode pop() untuk menghapus elemen tertentu dari daftar. metode pop() mengambil nilai indeks sebagai parameter dan menghapus elemen pada indeks yang ditentukan. Oleh karena itu, a[2] berisi 3 dan pop() menghapus dan mengembalikan output yang sama. Anda juga dapat menggunakan nilai indeks negatif.

Bagaimana Anda mempersingkat panjang daftar dengan Python?

Anda dapat membuat daftar yang lebih pendek dengan Python dengan menulis elemen daftar yang dipisahkan oleh koma di antara tanda kurung siku . Elemen dalam daftar dengan n elemen, diberi nomor dengan indeks dari 0 hingga n−1. Anda mendapatkan elemen daftar dengan menulis nama daftar diikuti dengan indeks elemen di antara tanda kurung siku.