Fungsi Python str() digunakan untuk membuat versi string dari objek yang akan diteruskan sebagai argumen untuknya
Dalam tutorial ini, kita akan belajar tentang str() fungsi bawaan di Python, dengan contoh-contohnya
Sintaks – str()
Sintaks fungsi str() adalah
class str(object='') #or class str(object=b'', encoding='utf-8', errors='strict')str() mengambil fungsi Python object sebagai argumen dan mengembalikan nilai stringnya. Jika tidak ada objek yang disediakan, str() mengembalikan string kosong
str() dengan objek Daftar sebagai Argumen
Dalam contoh ini, kita akan meneruskan objek list sebagai argumen ke fungsi str(). str() mengembalikan fungsi objek string
Program Piton
myList = [25, 'hello world', 36.25] resultString = str(myList) print(f'Resulting string is - "{resultString}"')_LariKeluaran
Resulting string is - "[25, 'hello world', 36.25]"str() dengan No Object sebagai Argument
Dalam contoh ini, kami tidak akan meneruskan argumen ke fungsi str(). str() harus mengembalikan string kosong
Program Piton
resultString = str() print(f'Resulting string is - "{resultString}"')JalankanKeluaran
Resulting string is - ""_str() dengan penyandian
Mari kita gunakan bentuk kedua dari fungsi str(), dan berikan pengkodean juga ke fungsi str()
Program Piton
bytes = b'\x65\x66\x67\x68\x69' resultString = str(bytes, encoding='utf-8') print(f'Resulting string is - "{resultString}"')JalankanKeluaran
Resulting string is - "efghi"_Ringkasan
Dalam tutorial Contoh Python ini, kami mempelajari sintaks fungsi str() , dan cara mengonversi objek apa pun ke versi stringnya menggunakan fungsi str() dengan contoh
Beberapa kelas koleksi bisa berubah. Metode yang menambah, mengurangi, atau mengatur ulang anggotanya pada tempatnya, dan tidak mengembalikan item tertentu, tidak pernah mengembalikan instance koleksi itu sendiri tetapi def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31
Beberapa operasi didukung oleh beberapa tipe objek; . Fungsi yang terakhir secara implisit digunakan ketika sebuah objek ditulis oleh fungsi tersebut
Pengujian Nilai Kebenaran
Objek apa pun dapat diuji untuk nilai kebenaran, untuk digunakan dalam kondisi atau atau sebagai operan dari operasi Boolean di bawah ini
Secara default, sebuah objek dianggap benar kecuali kelasnya mendefinisikan metode def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 37 yang mengembalikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 atau metode def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 39 yang mengembalikan nol, saat dipanggil dengan objek. Berikut adalah sebagian besar objek bawaan yang dianggap salah
konstanta yang didefinisikan sebagai salah. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31 dan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38
nol dari jenis numerik apa pun. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 42, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 43, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 44, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 45, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 46
urutan dan koleksi kosong. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 47, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 48, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 49, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 50, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 51, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 52
Operasi dan fungsi bawaan yang memiliki hasil Boolean selalu mengembalikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 42 atau def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 untuk false dan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 55 atau def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56 untuk true, kecuali dinyatakan lain. (Pengecualian penting. operasi Boolean def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 57 dan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 58 selalu mengembalikan salah satu operannya. )
Operasi Boolean — def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 58, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 57, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 61
Ini adalah operasi Boolean, diurutkan berdasarkan prioritas menaik
Operasi
Hasil
Catatan
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _62
jika x salah, maka y, selain itu x
(1)
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _63
jika x salah, maka x, jika tidak y
(2)
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _64
jika x salah, maka def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _56, selain itu def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38
(3)
Catatan
Ini adalah operator hubung singkat, sehingga hanya mengevaluasi argumen kedua jika yang pertama salah
Ini adalah operator hubung singkat, sehingga hanya mengevaluasi argumen kedua jika yang pertama 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 61 memiliki prioritas lebih rendah daripada operator non-Boolean, jadi def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 68 ditafsirkan sebagai def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 69, dan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 70 adalah kesalahan sintaksis
Perbandingan
Ada delapan operasi perbandingan di Python. Mereka semua memiliki prioritas yang sama (yang lebih tinggi daripada operasi Boolean). Perbandingan dapat dirantai secara acak;
Tabel ini merangkum operasi perbandingan
Operasi
Arti
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _74
ketat kurang dari
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _75
kurang dari atau sama
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _76
ketat lebih besar dari
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _77
lebih besar atau sama
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _78
setara
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _79
tidak sama
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 80
identitas objek
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _81
identitas objek yang dinegasikan
Objek dari tipe yang berbeda, kecuali tipe numerik yang berbeda, tidak pernah sebanding. Operator def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _78 selalu didefinisikan tetapi untuk beberapa tipe objek (misalnya, objek kelas) setara dengan. Operator def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 74, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 75, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 76 dan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 77 hanya didefinisikan jika masuk akal;
Contoh kelas yang tidak identik biasanya dibandingkan sebagai tidak sama kecuali kelas tersebut mendefinisikan metodenya
Instance suatu kelas tidak dapat diurutkan sehubungan dengan instance lain dari kelas yang sama, atau jenis objek lain, kecuali jika kelas tersebut cukup mendefinisikan metode , , , dan (secara umum, dan cukup, jika Anda menginginkan arti konvensional dari
Perilaku dan operator tidak dapat disesuaikan;
Dua operasi lagi dengan prioritas sintaksis yang sama, dan , didukung oleh tipe yang mengimplementasikan metode >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 00
Jenis Numerik — , ,
Ada tiga tipe numerik yang berbeda. 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
sisa >>> 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 dinegasikan
>>> 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
nilai mutlak atau besaran 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. saya default ke nol
(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
pasangan >>> 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
Juga disebut sebagai pembagian bilangan bulat. Nilai yang dihasilkan adalah bilangan bulat utuh, meskipun tipe hasilnya belum tentu int. Hasilnya selalu dibulatkan menuju minus tak terhingga. >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 38 adalah def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 42, >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 40 adalah >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 41, >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 42 adalah >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 41, dan >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 44 adalah def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 42
Bukan untuk bilangan kompleks. Alih-alih, konversikan ke pelampung menggunakan jika sesuai
Konversi dari floating point ke bilangan bulat dapat membulatkan atau memotong seperti pada C;
float juga menerima string "nan" dan "inf" dengan awalan opsional "+" atau "-" untuk Bukan Angka (NaN) dan infinity positif atau negatif
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
Literal numerik yang diterima mencakup digit def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 42 hingga >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 53 atau Unicode yang setara (poin kode dengan properti >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 54)
Lihat https. // www. unicode. org/Publik/14. 0. 0/ucd/extracted/DerivedNumericType. txt untuk daftar lengkap poin kode dengan properti >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 54
Semua tipe ( dan ) juga menyertakan operasi berikut
Operasi
Hasil
x dipotong menjadi
x dibulatkan menjadi n digit, dibulatkan setengah menjadi genap. Jika n dihilangkan, defaultnya adalah 0
terbesar = x
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;
Tabel ini mencantumkan operasi bitwise yang diurutkan dalam prioritas menaik
Operasi
Hasil
Catatan
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 71
bitwise atau dari x dan y
(4)
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 _72
eksklusif bitwise atau dari x dan y
(4)
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 73
bitwise dan dari x dan y
(4)
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 74
x digeser ke kiri sebanyak n bit
(1)(2)
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 75
x digeser ke kanan sebanyak n bit
(1)(3)
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 _76
bit x terbalik
Catatan
Hitungan shift negatif adalah ilegal dan menyebabkan a dinaikkan
Pergeseran ke kiri sebesar n bit sama dengan perkalian dengan >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 78
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
Melakukan perhitungan ini dengan setidaknya satu bit ekstensi tanda tambahan dalam representasi komplemen dua hingga (lebar bit kerja >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 80 atau lebih) cukup untuk mendapatkan hasil yang sama seolah-olah ada jumlah bit tanda yang tak terbatas
Metode Tambahan pada Tipe Integer
Tipe int mengimplementasikan. Selain itu, ini menyediakan beberapa metode lagi
int. bit_length()Kembalikan jumlah bit yang diperlukan untuk mewakili bilangan bulat dalam biner, tidak termasuk tanda dan angka nol di depan
>>> n = -37 >>> bin(n) '-0b100101' >>> n.bit_length() 6
Lebih tepatnya, jika >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 82 bukan nol, maka >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 83 adalah bilangan bulat positif unik >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 84 sehingga >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 85. Sama halnya, ketika >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 _23 cukup kecil untuk memiliki logaritma yang dibulatkan dengan benar, maka >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 87. Jika >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 _82 adalah nol, maka >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 83 mengembalikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 42
Setara dengan
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6
Baru di versi 3. 1
int. bit_count()Return the number of ones in the binary representation of the absolute value of the integer. This is also known as the population count. Example
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3
Setara dengan
def bit_count(self): return bin(self).count("1")
New in version 3. 10
int. to_bytes(length=1 , byteorder='big' , * , signed=False)Return an array of bytes representing an integer
>>> (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'
The integer is represented using length bytes, and defaults to 1. An is raised if the integer is not representable with the given number of bytes
The byteorder argument determines the byte order used to represent the integer, and defaults to >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 92. Jika urutan byte 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
The signed argument determines whether two’s complement is used to represent the integer. 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. However, when using the default arguments, don’t try to convert a value greater than 255 or you’ll get an
>>> (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)
New in version 3. 2
Changed in version 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(bytes , byteorder='big' , * , signed=False)Return the integer represented by the given array of bytes
>>> 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
The argument bytes must either be a or an iterable producing bytes
The byteorder argument determines the byte order used to represent the integer, and defaults to >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 92. If byteorder is >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 92, the most significant byte is at the beginning of the byte array. 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. To request the native byte order of the host system, use as the byte order value
The signed argument indicates whether two’s complement is used to represent the integer
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
New in version 3. 2
Changed in version 3. 11. Added default argument value for 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. The integer ratio of integers (whole numbers) is always the integer as the numerator 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 55 as the denominator
New in version 3. 8
Additional Methods on Float
The float type implements the . float also has the following additional methods
float. as_integer_ratio()Return a pair of integers whose ratio is exactly equal to the original float and with a positive denominator. Raises on infinities and a on NaNs
float. is_integer()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 float instance is finite with integral value, 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 38 otherwise
>>> (-2.0).is_integer() True >>> (3.2).is_integer() False
Two methods support conversion to and from hexadecimal strings. Since Python’s floats are stored internally as binary numbers, converting a float to or from a decimal string usually involves a small rounding error. In contrast, hexadecimal strings allow exact representation and specification of floating-point numbers. This can be useful when debugging, and in numerical work
float. hex()Mengembalikan representasi angka floating-point sebagai string heksadesimal. For finite floating-point numbers, this representation will always include a leading def bit_count(self): return bin(self).count("1") 12 and a trailing def bit_count(self): return bin(self).count("1") 13 and exponent
classmethod float. fromhex(s)Class method to return the float represented by a hexadecimal string s. The string s may have leading and trailing whitespace
Note that is an instance method, while is a class method
A hexadecimal string takes the form
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 0
where the optional def bit_count(self): return bin(self).count("1") 16 may by either >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 69 or >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 70, def bit_count(self): return bin(self).count("1") 19 and def bit_count(self): return bin(self).count("1") 20 are strings of hexadecimal digits, and def bit_count(self): return bin(self).count("1") 21 is a decimal integer with an optional leading sign. Case is not significant, and there must be at least one hexadecimal digit in either the integer or the fraction. This syntax is similar to the syntax specified in section 6. 4. 4. 2 of the C99 standard, and also to the syntax used in Java 1. 5 onwards. In particular, the output of is usable as a hexadecimal floating-point literal in C or Java code, and hexadecimal strings produced by C’s def bit_count(self): return bin(self).count("1") 23 format character or Java’s def bit_count(self): return bin(self).count("1") 24 are accepted by
Note that the exponent is written in decimal rather than hexadecimal, and that it gives the power of 2 by which to multiply the coefficient. For example, the hexadecimal string def bit_count(self): return bin(self).count("1") 26 represents the floating-point number def bit_count(self): return bin(self).count("1") 27, or def bit_count(self): return bin(self).count("1") 28
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 1
Applying the reverse conversion to def bit_count(self): return bin(self).count("1") 28 gives a different hexadecimal string representing the same number
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 2
Hashing of numeric types
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
CPython implementation detail. Currently, the prime used is def bit_count(self): return bin(self).count("1") 48 on machines with 32-bit C longs and def bit_count(self): return bin(self).count("1") 49 on machines with 64-bit C longs
Here are the rules in detail
If def bit_count(self): return bin(self).count("1") 50 is a nonnegative rational number and def bit_count(self): return bin(self).count("1") 51 is not divisible by def bit_count(self): return bin(self).count("1") 43, define def bit_count(self): return bin(self).count("1") 53 as def bit_count(self): return bin(self).count("1") 54, where def bit_count(self): return bin(self).count("1") 55 gives the inverse of def bit_count(self): return bin(self).count("1") 51 modulo def bit_count(self): return bin(self).count("1") 43
If def bit_count(self): return bin(self).count("1") 50 is a nonnegative rational number and def bit_count(self): return bin(self).count("1") 51 is divisible by def bit_count(self): return bin(self).count("1") 43 (but def bit_count(self): return bin(self).count("1") 61 is not) then def bit_count(self): return bin(self).count("1") 51 has no inverse modulo def bit_count(self): return bin(self).count("1") 43 and the rule above doesn’t apply; in this case define def bit_count(self): return bin(self).count("1") 53 to be the constant value def bit_count(self): return bin(self).count("1") 65
If def bit_count(self): return bin(self).count("1") 50 is a negative rational number define def bit_count(self): return bin(self).count("1") 53 as def bit_count(self): return bin(self).count("1") 68. If the resulting hash is >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 41, replace it with def bit_count(self): return bin(self).count("1") 70
The particular values def bit_count(self): return bin(self).count("1") 65 and def bit_count(self): return bin(self).count("1") 72 are used as hash values for positive infinity or negative infinity (respectively)
For a number def bit_count(self): return bin(self).count("1") 74, the hash values of the real and imaginary parts are combined by computing def bit_count(self): return bin(self).count("1") 75, reduced modulo def bit_count(self): return bin(self).count("1") 76 so that it lies in def bit_count(self): return bin(self).count("1") 77. Again, if the result is >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 41, it’s replaced with def bit_count(self): return bin(self).count("1") 70
To clarify the above rules, here’s some example Python code, equivalent to the built-in hash, for computing the hash of a rational number, , or
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 3
Iterator Types
Python supports a concept of iteration over containers. This is implemented using two distinct methods; these are used to allow user-defined classes to support iteration. Sequences, described below in more detail, always support the iteration methods
One method needs to be defined for container objects to provide support
container. __iter__()Return an object. The object is required to support the iterator protocol described below. If a container supports different types of iteration, additional methods can be provided to specifically request iterators for those iteration types. (An example of an object supporting multiple forms of iteration would be a tree structure which supports both breadth-first and depth-first traversal. ) This method corresponds to the slot of the type structure for Python objects in the Python/C API
The iterator objects themselves are required to support the following two methods, which together form the iterator protocol
iterator. __iter__()Return the object itself. This is required to allow both containers and iterators to be used with the and statements. This method corresponds to the slot of the type structure for Python objects in the Python/C API
iterator. __next__()Return the next item from the . If there are no further items, raise the exception. This method corresponds to the slot of the type structure for Python objects in the Python/C API
Python defines several iterator objects to support iteration over general and specific sequence types, dictionaries, and other more specialized forms. The specific types are not important beyond their implementation of the iterator protocol
Once an iterator’s method raises , it must continue to do so on subsequent calls. Implementations that do not obey this property are deemed broken
Jenis Pembangkit
Python’s s provide a convenient way to implement the iterator protocol. If a container object’s def bit_count(self): return bin(self).count("1") 90 method is implemented as a generator, it will automatically return an iterator object (technically, a generator object) supplying the def bit_count(self): return bin(self).count("1") 90 and methods. More information about generators can be found in
Sequence Types — , ,
There are three basic sequence types. lists, tuples, and range objects. Additional sequence types tailored for processing of and are described in dedicated sections
Common Sequence Operations
The operations in the following table are supported by most sequence types, both mutable and immutable. 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
The def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 98 and def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 99 operations have the same priorities as the comparison operations. The >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 69 (concatenation) and >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 00 (repetition) operations have the same priority as the corresponding numeric operations.
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 if an item of s is equal to x, else def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38
(1)
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 04
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 if an item of s is equal to x, else def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56
(1)
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 07
the concatenation of s and t
(6)(7)
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 08 or >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 09
equivalent to adding s to itself n times
(2)(7)
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 10
ith item of s, origin 0
(3)
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 11
slice of s from i to j
(3)(4)
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 12
slice of s from i to j with step 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
length of 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
smallest item of 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
largest item of 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
index of the first occurrence of x in s (at or after index i and before index 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
total number of occurrences of x in s
Sequences of the same type also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length. (For full details see in the language reference. )
Forward and reversed iterators over mutable sequences access values using an index. That index will continue to march forward (or backward) even if the underlying sequence is mutated. The iterator terminates only when an or a is encountered (or when the index drops below zero)
Catatan
While the def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 98 and def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 99 operations are used only for simple containment testing in the general case, some specialised sequences (such as , and ) also use them for subsequence testing
def bit_length(self): 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
Values of n less than def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 42 are treated 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 42 (which yields an empty sequence of the same type as s). Note that items in the sequence s are not copied; they are referenced multiple times. This often haunts new Python programmers; consider
def bit_length(self): 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
What has happened is that >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 27 is a one-element list containing an empty list, so all three 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' 28 are references to this single empty list. Modifying any of 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' 29 modifies this single list. You can create a list of different lists this way
def bit_length(self): 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
Further explanation is available in the FAQ entry
If i or j is negative, the index is relative to the end of sequence s. >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 30 or >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 31 is substituted. But note that >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 32 is still def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 42
The slice of s from i to j is defined as the sequence of items with index k such that >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 34. If i or j is greater than >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 13, use >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 13. 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. If j is omitted or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31, use >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 13. If i is greater than or equal to j, the slice is empty
The slice of s from i to j with step k is defined as the sequence of items with index >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 41 such that >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 42. In other words, the indices are >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 43, >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 44, >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 45, >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 46 and so on, stopping when j is reached (but never including j). When k is positive, i and j are reduced to >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 13 if they are greater. When k is negative, i and j are reduced to >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 48 if they are greater. If i or j are omitted or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31, they become “end” values (which end depends on the sign of k). Note, k cannot be zero. If k is def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31, it is treated like def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 55
Concatenating immutable sequences always results in a new object. This means that building up a sequence by repeated concatenation will have a quadratic runtime cost in the total sequence length. To get a linear runtime cost, you must switch to one of the alternatives below
if concatenating objects, you can build a list and use at the end or else write to an instance and retrieve its value when complete
if concatenating objects, you can similarly use or , or you can do in-place concatenation with a object. objects are mutable and have an efficient overallocation mechanism
if concatenating objects, extend a instead
for other types, investigate the relevant class documentation
Some sequence types (such as ) only support item sequences that follow specific patterns, and hence don’t support sequence concatenation or repetition
>>> (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
membuat salinan s yang dangkal (sama seperti >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 88)
(5)
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 89 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
menyisipkan x ke s pada indeks yang diberikan oleh i (sama seperti >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 94)
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 95 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
hapus item pertama dari s di mana >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 10 sama dengan x
(3)
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' _99
membalikkan item s di tempat
(4)
Catatan
t must have the same length as the slice it is replacing
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
>>> (65).to_bytes() b'A' 01 raises when x is not found in s
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
>>> (65).to_bytes() b'A' 04 and >>> (65).to_bytes() b'A' 05 are included for consistency with the interfaces of mutable containers that don’t support slicing operations (such as and ). >>> (65).to_bytes() b'A' 05 is not part of the ABC, but most concrete mutable sequence classes provide it
New in version 3. 3. >>> (65).to_bytes() b'A' 04 and >>> (65).to_bytes() b'A' 05 methods.
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)
Untuk contoh penyortiran dan tutorial penyortiran singkat, lihat
CPython implementation detail. While a list is being sorted, the effect of attempting to mutate, or even inspect, the list is undefined. The C implementation of Python makes the list appear empty for the duration, and raises if it can detect that the list has been mutated during a sort
Tuples
Tuples are immutable sequences, typically used to store collections of heterogeneous data (such as the 2-tuples produced by the built-in). Tuples are also used for cases where an immutable sequence of homogeneous data is needed (such as allowing storage in a or instance)
class tuple([iterable])Tuples may be constructed in a number of ways
Using a pair of parentheses to denote the empty tuple. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 48
Using a trailing comma for a singleton tuple. >>> (65).to_bytes() b'A' 40 or >>> (65).to_bytes() b'A' 41
Separating items with commas. >>> (65).to_bytes() b'A' 42 or >>> (65).to_bytes() b'A' 43
Using the built-in. >>> (65).to_bytes() b'A' 44 or >>> (65).to_bytes() b'A' 46
The constructor builds a tuple whose items are the same and in the same order as iterable’s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a tuple, it is returned unchanged. For example, >>> (65).to_bytes() b'A' 47 returns >>> (65).to_bytes() b'A' 48 and >>> (65).to_bytes() b'A' 49 returns >>> (65).to_bytes() b'A' 50. If no argument is given, the constructor creates a new empty tuple, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 48
Note that it is actually the comma which makes a tuple, not the parentheses. The parentheses are optional, except in the empty tuple case, or when they are needed to avoid syntactic ambiguity. For example, >>> (65).to_bytes() b'A' 52 is a function call with three arguments, while >>> (65).to_bytes() b'A' 53 is a function call with a 3-tuple as the sole argument
Tuples implement all of the sequence operations
For heterogeneous collections of data where access by name is clearer than access by index, may be a more appropriate choice than a simple tuple object
Ranges
The type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in loops
class range(stop)class range(start , stop[ , step])The arguments to the range constructor must be integers (either built-in or any object that implements the special method). If the step argument is omitted, it defaults to def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 55. If the start argument is omitted, it defaults to def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 42. If step is zero, is raised
For a positive step, the contents of a range >>> (65).to_bytes() b'A' 62 are determined by the formula >>> (65).to_bytes() b'A' 63 where >>> (65).to_bytes() b'A' 64 and >>> (65).to_bytes() b'A' 65
For a negative step, the contents of the range are still determined by the formula >>> (65).to_bytes() b'A' 63, but the constraints are >>> (65).to_bytes() b'A' 64 and >>> (65).to_bytes() b'A' 68
A range object will be empty if >>> (65).to_bytes() b'A' 69 does not meet the value constraint. Ranges do support negative indices, but these are interpreted as indexing from the end of the sequence determined by the positive indices
Ranges containing absolute values larger than are permitted but some features (such as ) may raise
Range examples
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 7
Ranges implement all of the sequence operations except concatenation and repetition (due to the fact that range objects can only represent sequences that follow a strict pattern and repetition and concatenation will usually violate that pattern)
startThe 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)
stopThe value of the stop parameter
stepNilai parameter langkah (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 _55 jika parameter tidak diberikan)
The advantage of the type over a regular or is that a object will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores the >>> (65).to_bytes() b'A' 79, >>> (65).to_bytes() b'A' 80 and >>> (65).to_bytes() b'A' 81 values, calculating individual items and subranges as needed)
Range objects implement the ABC, and provide features such as containment tests, element index lookup, slicing and support for negative indices (see )
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 8
Menguji objek rentang untuk kesetaraan dengan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _78 dan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 79 membandingkannya sebagai urutan. That is, two range objects are considered equal if they represent the same sequence of values. (Perhatikan bahwa dua objek rentang yang membandingkan sama mungkin memiliki perbedaan , dan atribut, misalnya >>> (65).to_bytes() b'A' 88 atau >>> (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 . Jika tidak, objek bytes yang mendasari objek buffer diperoleh sebelum dipanggil. 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 ()
The section of the standard library covers a number of other modules that provide various text related utilities (including regular expression support in the module)
str. capitalize()Return a copy of the string with its first character capitalized and the rest lowercased
Changed in version 3. 8. The first character is now put into titlecase rather than uppercase. This means that characters like digraphs will only have their first letter capitalized, instead of the full character.
str. casefold()Return a casefolded copy of the string. Casefolded strings may be used for caseless matching
Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 28 is equivalent to def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 29. Since it is already lowercase, would do nothing to def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 28; converts it to def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 29
The casefolding algorithm is described in section 3. 13 of the Unicode Standard
New in version 3. 3
str. center(width[ , fillchar])Return centered in a string of length width. Padding 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.
Berubah di versi 3. 9. The value of the errors argument is now checked in and in .
str. endswith(suffix[ , start[ , end]])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 string diakhiri dengan akhiran yang ditentukan, jika tidak, 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 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). Untuk memperluas string, kolom saat ini disetel ke nol dan string diperiksa karakter demi karakter. If the character is a tab (def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 46), one or more space characters are inserted in the result until the current column is equal to the next tab position. (The tab character itself is not copied. ) If the character is a newline (def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 47) or return (def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 48), it is copied and the current column is reset to zero. Any other character is copied unchanged and the current column is incremented by one regardless of how the character is represented when printed
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 0
str. find(sub[ , start[ , end]])Return the lowest index in the string where substring sub is found within the slice def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 49. Optional arguments start and end are interpreted as in slice notation. Return >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 41 if sub is not found
Note
The method should be used only if you need to know the position of sub. To check if sub is a substring or not, use the operator
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 1
str. format(*args , **kwargs)Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 50. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 2
See for a description of the various formatting options that can be specified in format strings
Note
When formatting a number (, , , and subclasses) with the def bit_count(self): return bin(self).count("1") 51 type (ex. def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 59), the function temporarily sets the def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 60 locale to the def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 61 locale to decode def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 62 and def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 63 fields of def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 64 if they are non-ASCII or longer than 1 byte, and the def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 61 locale is different than the def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 60 locale. This temporary change affects other threads
Changed in version 3. 7. When formatting a number with the def bit_count(self): return bin(self).count("1") 51 type, the function sets temporarily the def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 60 locale to the def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 61 locale in some cases.
str. format_map(mapping)Similar to def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 70, except that def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 71 is used directly and not copied to a . This is useful if for example def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 71 is a dict subclass
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 3
New in version 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()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 string adalah string dengan huruf kapital dan setidaknya ada satu karakter, misalnya karakter huruf besar hanya boleh mengikuti karakter tanpa huruf dan karakter huruf kecil hanya dengan huruf kapital. 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. Pemisah antar elemen adalah string yang menyediakan metode ini
str. sesuai(lebar[ , fillchar])Kembalikan string yang dibiarkan rata dalam string dengan panjang lebar. Padding dilakukan menggunakan fillchar yang ditentukan (defaultnya adalah spasi ASCII). String asli dikembalikan jika lebarnya kurang dari atau sama dengan >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 13
str. lebih rendah()Kembalikan salinan string dengan semua karakter cased dikonversi menjadi huruf kecil
Algoritma huruf kecil yang digunakan dijelaskan pada bagian 3. 13 dari Standar Unicode
str. lstrip([karakter])Kembalikan salinan string dengan karakter utama dihapus. Argumen chars adalah string yang menentukan kumpulan karakter yang akan dihapus. Jika 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, argumen chars default untuk menghapus spasi. Argumen chars bukanlah awalan;
>>> 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. menghapus akhiran(akhiran , /)If the string ends with the suffix string and that suffix is not empty, return >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 26. Otherwise, return a copy of the original string
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 9
New in version 3. 9
str. replace(old , new[ , count])Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced
str. rfind(sub[ , start[ , end]])Return the highest index in the string where substring sub is found, such that sub is contained within def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 49. Optional arguments start and end are interpreted as in slice notation. Return >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 41 on failure
str. rindex(sub[ , start[ , end]])Like but raises when the substring sub is not found
str. rjust(width[ , fillchar])Return the string right justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 13
str. rpartition(sep)Split the string at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself
str. rsplit(sep=None , maxsplit=- 1)Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31, any whitespace string is a separator. Except for splitting from the right, behaves like which is described in detail below
str. rstrip([chars])Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31, the chars argument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped
def bit_count(self): return bin(self).count("1") 0
See for a method that will remove a single suffix string rather than all of a set of characters. For example
def bit_count(self): return bin(self).count("1") 1
str. split(sep=None , maxsplit=- 1)Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 37 elements). If maxsplit is not specified or >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 41, then there is no limit on the number of splits (all possible splits are made)
If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 39 returns >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 40). The sep argument may consist of multiple characters (for example, >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 41 returns >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 42). Splitting an empty string with a specified separator returns >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 43
For example
def bit_count(self): return bin(self).count("1") 2
If sep is not specified or is def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31, a different splitting algorithm is applied. runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31 separator returns def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 49
For example
def bit_count(self): return bin(self).count("1") 3
str. splitlines(keepends=False)Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true
This method splits on the following line boundaries. Secara khusus, batas-batasnya adalah superset dari
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 atau >>> 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 . Saat diindeks oleh ordinal Unicode (bilangan bulat), objek tabel dapat melakukan salah satu dari berikut ini. return a Unicode ordinal or a string, to map the character to one or more other characters; return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31, to delete the character from the return string; or raise a exception, to map the character to itself
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
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
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)
Conversion flags (optional), which affect the result of some conversion types
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
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. Jika ditentukan sebagai >>> 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 (tanda bintang), presisi aktual dibaca dari elemen berikutnya dari tuple dalam nilai, dan nilai yang akan dikonversi muncul setelah presisi
Pengubah panjang (opsional)
Jenis konversi
Jika argumen yang benar adalah kamus (atau jenis pemetaan lainnya), maka format dalam string 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. Sebagai contoh
>>> (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
Dalam hal ini, tidak ada >>> (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 specifier yang mungkin muncul dalam format (karena memerlukan daftar parameter berurutan)
Karakter bendera konversi adalah
Bendera
Arti
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 _94
Konversi nilai akan menggunakan "bentuk alternatif" (bila didefinisikan di bawah)
>>> 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
Konversi akan menjadi nol empuk untuk nilai numerik
>>> 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
Nilai yang dikonversi dibiarkan disesuaikan (mengganti konversi >>> 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 jika keduanya 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 _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
Arti
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
Signed hexadecimal (uppercase)
(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
Floating point format. 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
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
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
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
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
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
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
Bytes objects are immutable sequences of single bytes. Since many major binary protocols are based on the ASCII text encoding, bytes objects offer several methods that are only valid when working with ASCII compatible data and are closely related to string objects in a variety of other ways
class bytes([source[ , encoding[ , errors]]])Firstly, the syntax for bytes literals is largely the same as that for string literals, except that a 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. Mereka beroperasi tidak hanya dengan operan dari jenis yang sama, tetapi dengan apa saja. 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. removeprefix(prefix , /)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
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
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
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
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. Nilai lain yang mungkin adalah 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, dan nama lain yang didaftarkan melalui. 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.
Berubah di versi 3. 9. The value of the errors argument is now checked in and in .
bytes. 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.
byte. index(sub[ , start[ , end]])bytearray. indeks(sub[ , start[, end]])Seperti , tetapi naikkan jika urutan berikutnya tidak ditemukan
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
static bytes. 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
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
bytes. rfind(sub[ , start[ , end]])bytearray. rfind(sub[ , start[ , end]])Return the highest index in the sequence where the subsequence sub is found, such that sub is contained within 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.
byte. rindex(sub[ , start[ , end]])bytearray. rindeks(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. dimulai dengan(awalan[ , . start[, end]])bytearray.dimulai dengan(awalan[ , start[, end]])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 data biner dimulai dengan awalan yang ditentukan, jika tidak, 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 38. awalan juga bisa menjadi kumpulan awalan yang harus dicari. Dengan start opsional, uji mulai pada posisi itu. Dengan ujung opsional, berhentilah membandingkan pada posisi itu
Awalan yang akan dicari dapat berupa apa saja
byte. terjemahkan(tabel , / . , delete=b'')bytearray.terjemahkan(tabel , /, delete=b'')Kembalikan salinan objek byte atau bytearray di mana semua byte yang terjadi dalam penghapusan argumen opsional dihapus, dan byte yang tersisa telah dipetakan melalui tabel terjemahan yang diberikan, yang harus berupa objek byte dengan panjang 256
Anda dapat menggunakan metode ini untuk membuat tabel terjemahan
Tetapkan argumen tabel 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 untuk terjemahan yang hanya menghapus karakter
>>> (65).to_bytes() b'A' _4
Berubah di versi 3. 6. delete sekarang didukung sebagai argumen kata kunci.
Metode berikut pada objek byte dan bytearray memiliki perilaku default yang menganggap penggunaan format biner yang kompatibel dengan ASCII, tetapi masih dapat digunakan dengan data biner arbitrer dengan meneruskan argumen yang sesuai. Perhatikan bahwa semua metode bytearray di bagian ini tidak beroperasi di tempat, dan malah menghasilkan objek baru
byte. tengah(lebar[ , . fillbyte])bytearray.pusat(lebar[ , fillbyte])Kembalikan salinan objek yang dipusatkan dalam urutan lebar panjang. Padding dilakukan menggunakan fillbyte yang ditentukan (defaultnya adalah ruang ASCII). Untuk objek, urutan aslinya dikembalikan jika lebarnya kurang dari atau sama dengan >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 13
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
byte. sesuai(lebar[ , . fillbyte])bytearray.sesuai(lebar[ , fillbyte])Kembalikan salinan objek yang dibiarkan rata dalam urutan lebar panjang. Padding dilakukan menggunakan fillbyte yang ditentukan (defaultnya adalah ruang ASCII). Untuk objek, urutan aslinya dikembalikan jika lebarnya kurang dari atau sama dengan >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 13
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
byte. lstrip([karakter] . )bytearray.lstrip([chars])Kembalikan salinan urutan dengan byte utama yang ditentukan dihapus. Argumen chars adalah urutan biner yang menentukan kumpulan nilai byte yang akan dihapus - namanya mengacu pada fakta bahwa metode ini biasanya digunakan dengan karakter ASCII. Jika 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, argumen chars default untuk menghapus spasi ASCII. Argumen chars bukanlah awalan;
>>> (65).to_bytes() b'A' _5
Urutan biner dari nilai byte yang akan dihapus dapat berupa apa saja. Lihat metode yang akan menghapus satu string awalan daripada semua kumpulan karakter. Sebagai contoh
>>> (65).to_bytes() b'A' _6
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
byte. tepat(lebar[ , . fillbyte])bytearray.tepat(lebar[ , fillbyte])Kembalikan salinan objek yang dibenarkan dengan benar dalam urutan lebar panjang. Padding dilakukan menggunakan fillbyte yang ditentukan (defaultnya adalah ruang ASCII). Untuk objek, urutan aslinya dikembalikan jika lebarnya kurang dari atau sama dengan >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 13
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
byte. rsplit(sep=None , maxsplit=- 1)bytearray. rsplit(sep=Tidak ada, maxsplit=- 1)Pisahkan urutan biner menjadi suburutan dengan jenis yang sama, menggunakan sep sebagai string pembatas. Jika maxsplit diberikan, paling banyak maxsplit split dilakukan, yang paling kanan. Jika sep tidak ditentukan 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, urutan apa pun yang hanya terdiri dari spasi putih ASCII adalah pemisah. Kecuali membelah dari kanan, berperilaku seperti yang dijelaskan secara rinci di bawah ini
byte. rstrip([karakter] . )bytearray.rstrip([karakter])Kembalikan salinan urutan dengan byte tambahan yang ditentukan dihapus. Argumen chars adalah urutan biner yang menentukan kumpulan nilai byte yang akan dihapus - namanya mengacu pada fakta bahwa metode ini biasanya digunakan dengan karakter ASCII. Jika 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, argumen chars default untuk menghapus spasi ASCII. Argumen chars bukanlah sufiks;
>>> (65).to_bytes() b'A' _7
Urutan biner dari nilai byte yang akan dihapus dapat berupa apa saja. Lihat metode yang akan menghapus string akhiran tunggal daripada semua kumpulan karakter. Sebagai contoh
>>> (65).to_bytes() b'A' _8
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
byte. pisah(sep=Tidak ada . , maxsplit=- 1)bytearray.pisah(sep=Tidak ada, maxsplit=- 1)Pisahkan urutan biner menjadi suburutan dengan jenis yang sama, menggunakan sep sebagai string pembatas. Jika maxsplit diberikan dan non-negatif, paling banyak pemisahan maxsplit dilakukan (dengan demikian, daftar akan memiliki paling banyak >>> 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 elemen). Jika maxsplit tidak ditentukan atau >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 41, maka tidak ada batasan jumlah split (semua kemungkinan split dibuat)
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). Memisahkan urutan kosong dengan pemisah yang ditentukan mengembalikan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 31 atau >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 32 tergantung pada jenis objek yang dipisah. Argumen sep mungkin ada
For example
>>> (65).to_bytes() b'A' _9
Jika sep tidak ditentukan 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, algoritme pemisahan yang berbeda diterapkan. menjalankan spasi putih ASCII berurutan dianggap sebagai pemisah tunggal, dan hasilnya tidak akan berisi string kosong di awal atau akhir jika urutan memiliki spasi putih di depan atau di belakang. 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
byte. strip([karakter] . )bytearray.strip([karakter])Kembalikan salinan urutan dengan byte awal dan akhir yang ditentukan dihapus. Argumen chars adalah urutan biner yang menentukan kumpulan nilai byte yang akan dihapus - namanya mengacu pada fakta bahwa metode ini biasanya digunakan dengan karakter ASCII. Jika 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, argumen chars default untuk menghapus spasi ASCII. Argumen karakter bukanlah awalan atau akhiran;
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
Urutan biner dari nilai byte yang akan dihapus dapat berupa apa saja
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
Metode berikut pada objek byte dan bytearray mengasumsikan penggunaan format biner yang kompatibel dengan ASCII dan tidak boleh diterapkan pada data biner arbitrer. Perhatikan bahwa semua metode bytearray di bagian ini tidak beroperasi di tempat, dan malah menghasilkan objek baru
byte. kapitalisasi()bytearray. kapitalisasi()Kembalikan salinan urutan dengan setiap byte ditafsirkan sebagai karakter ASCII, dan byte pertama dikapitalisasi dan sisanya dengan huruf kecil. Nilai byte non-ASCII diteruskan tanpa perubahan
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
bytes. 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
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
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. 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) _3
bytes. 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()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 digit 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 sebaliknya. 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. islower()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. Uppercase ASCII characters are those byte values in the sequence >>> (-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()Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56 if there is at least one uppercase alphabetic ASCII character in the sequence and no lowercase ASCII characters, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 otherwise
For example
def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 8
Karakter ASCII huruf kecil adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 53. Uppercase ASCII characters are those byte values in the sequence >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 54
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. Uppercase ASCII characters are those byte values in the sequence >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 54
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
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. Uppercase ASCII characters are those byte values in the sequence >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 54
Tidak seperti , selalu ________140______71 untuk versi biner. Konversi kasus bersifat simetris dalam ASCII, meskipun hal itu umumnya tidak berlaku untuk poin kode Unicode arbitrer
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
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
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
byte. upper()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. Uppercase ASCII characters are those byte values in the sequence >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 54
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
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 asli 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
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) _ Pemformatan Byte 26 gaya
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 tupel
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
If format requires a single argument, values may be a single non-tuple object. 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
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
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)
Conversion flags (optional), which affect the result of some conversion types
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
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. Jika ditentukan sebagai >>> 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 (tanda bintang), presisi aktual dibaca dari elemen berikutnya dari tuple dalam nilai, dan nilai yang akan dikonversi muncul setelah presisi
Pengubah panjang (opsional)
Jenis konversi
Ketika argumen yang benar 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. Sebagai contoh
>>> 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
Dalam hal ini, tidak ada >>> (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 specifier yang mungkin muncul dalam format (karena memerlukan daftar parameter berurutan)
Karakter bendera konversi adalah
Bendera
Arti
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 _94
Konversi nilai akan menggunakan "bentuk alternatif" (bila didefinisikan di bawah)
>>> 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
Konversi akan menjadi nol empuk untuk nilai numerik
>>> 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
Nilai yang dikonversi dibiarkan disesuaikan (mengganti konversi >>> 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 jika keduanya 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 _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
Arti
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
Signed hexadecimal (uppercase)
(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
Floating point format. 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
Bytes (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
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
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
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
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
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
def bit_length(self): 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 sudah usang, tetapi tidak akan dihapus selama 3. seri x
def bit_length(self): 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
See PEP 237
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
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 is equal to the length of . 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. Mengubah ukuran tidak diperbolehkan
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
One-dimensional memoryviews of hashable (read-only) types with formats ‘B’, ‘b’ or ‘c’ are also 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
Perhatikan bahwa, seperti angka floating point, def bit_length(self): 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 tidak berarti def bit_length(self): 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 untuk objek memoryview
Changed in version 3. 3. Versi sebelumnya membandingkan memori mentah dengan mengabaikan format item dan struktur array logis.
tobyte(pesanan='C' C- dan C-contiguous -> 1DThe 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
keberatanObjek yang mendasari tampilan memori
>>> (-2.0).is_integer() True >>> (3.2).is_integer() False _5
New in version 3. 3
nbytesdef bit_length(self): 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. Ini belum tentu 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 _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 dibacaBool yang menunjukkan apakah memori hanya dapat dibaca
formatString 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.
itemsizeUkuran dalam byte dari setiap elemen tampilan memori
>>> (-2.0).is_integer() True >>> (3.2).is_integer() False 8
ndimBilangan bulat yang menunjukkan berapa banyak dimensi dari array multi-dimensi yang diwakili oleh memori
membentukSebuah 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.
langkahTuple 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.
suboffsetDigunakan secara internal untuk array gaya PIL. Nilai hanya bersifat informasional
c_contiguousBool yang menunjukkan apakah memori adalah C-
New in version 3. 3
f_contiguousSebuah bool yang menunjukkan apakah memori tersebut adalah Fortran
New in version 3. 3
berdekatanBool yang menunjukkan apakah memori itu
New in version 3. 3
Jenis Setel — ,
Objek set adalah kumpulan objek berbeda yang tidak terurut. Penggunaan umum termasuk pengujian keanggotaan, menghapus duplikat dari suatu urutan, dan menghitung operasi matematika seperti persimpangan, penyatuan, perbedaan, dan perbedaan simetris. (Untuk container lain lihat built-in , , dan class, dan module. )
Seperti koleksi lainnya, set dukungan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 100, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 101, dan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 102. Menjadi koleksi yang tidak terurut, himpunan tidak merekam posisi elemen atau urutan penyisipan. Dengan demikian, set tidak mendukung pengindeksan, pemotongan, atau perilaku seperti urutan lainnya
Saat ini ada dua tipe set bawaan, dan. Jenisnya bisa berubah — isinya bisa diubah menggunakan metode seperti def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 106 dan >>> (65).to_bytes() b'A' 01. Since it is mutable, it has no hash value and cannot be used as either a dictionary key or as an element of another set. 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)Return the number of elements in set s (cardinality of s)
x dalam sUji x untuk keanggotaan dalam s
x tidak dalam sUji 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 lainnyaUji apakah himpunan tersebut merupakan superset yang tepat dari yang lain, yaitu, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 121
serikat(*lainnya)set | lainnya . .Return a new set with elements from the set and all others
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 ^ otherKembalikan set baru dengan elemen di set atau lainnya tetapi tidak keduanya
salin()Kembalikan salinan set yang dangkal
Perhatikan, versi non-operator dari , , , , , dan metode akan menerima iterable apa pun sebagai argumen. Sebaliknya, rekan berbasis operator mereka membutuhkan argumen mereka untuk ditetapkan. Ini mencegah konstruksi rawan kesalahan seperti def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 128 demi def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 129 yang lebih mudah dibaca
Keduanya dan dukungan diatur untuk mengatur perbandingan. Dua himpunan adalah sama jika dan hanya jika setiap elemen dari setiap himpunan terkandung dalam yang lain (masing-masing merupakan subhimpunan dari yang lain). Himpunan kurang dari himpunan lain jika dan hanya jika himpunan pertama adalah himpunan bagian yang tepat dari himpunan kedua (adalah himpunan bagian, tetapi tidak sama). Himpunan lebih besar dari himpunan lain jika dan hanya jika himpunan pertama adalah superset yang tepat dari himpunan kedua (adalah superset, tetapi tidak sama)
Contoh dibandingkan dengan contoh berdasarkan anggotanya. Misalnya, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _134 mengembalikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56 dan begitu juga def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 136
The subset and equality comparisons do not generalize to a total ordering function. Misalnya, dua himpunan disjoint tidak kosong mana pun tidak sama dan bukan subhimpunan satu sama lain, jadi semua pengembalian berikut def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 138, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 139, atau def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 140
Karena set hanya menentukan pengurutan parsial (hubungan subset), output dari metode ini tidak ditentukan untuk daftar set
Setel elemen, seperti kunci kamus, harus
Operasi biner yang menggabungkan instance dengan mengembalikan tipe operan pertama. Sebagai contoh. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 144 mengembalikan instance dari
Tabel berikut mencantumkan operasi yang tersedia untuk yang tidak berlaku untuk instance yang tidak dapat diubah
perbarui(*lainnya)set |= other . .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 ^= otherPerbarui 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
len(d)Mengembalikan jumlah item dalam kamus d
d[kunci]Kembalikan item d dengan key key. Menimbulkan jika kunci tidak ada di peta
Jika subclass dari dict mendefinisikan metode def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 175 dan kunci tidak ada, operasi def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 176 memanggil metode itu dengan key kunci sebagai argumen. Operasi def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _176 kemudian mengembalikan atau menaikkan apa pun yang dikembalikan atau dimunculkan oleh panggilan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 178. Tidak ada operasi atau metode lain yang memanggil def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 175. Jika def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _175 tidak ditentukan, dinaikkan. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 175 harus menjadi metode;
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _00
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] = nilaiTetapkan def bit_length(self): 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]Remove def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 176 from d. Menimbulkan jika kunci tidak ada di peta
kunci di dKembalikan def bit_length(self): 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 dSetara 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()Return a shallow copy of the dictionary
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
New in version 3. 8
setdefault(kunci[ , default])Jika kunci ada di kamus, kembalikan nilainya. Jika tidak, masukkan kunci dengan nilai default dan kembalikan default. default default ke def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _31
perbarui([lainnya])Perbarui kamus dengan pasangan kunci/nilai dari yang lain, menimpa kunci yang sudah ada. Kembalikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _31
menerima objek kamus lain atau iterable dari pasangan kunci/nilai (sebagai tupel atau iterable lainnya dengan panjang dua). If keyword arguments are specified, the dictionary is then updated with those key/value pairs. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 208
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 . lainnyaBuat 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 . = lainnyaPerbarui kamus d dengan kunci dan nilai dari yang lain, yang dapat berupa a atau an dari pasangan kunci/nilai. Nilai-nilai lain diprioritaskan ketika d dan kunci berbagi lainnya
New in version 3. 9
Dictionaries compare equal if and only if they have the same def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 197 pairs (regardless of ordering). Order comparisons (‘’) raise .
Kamus mempertahankan urutan penyisipan. Perhatikan bahwa memperbarui kunci tidak memengaruhi urutan. Keys added after deletion are inserted at the end
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _02
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)Return the number of entries in the dictionary
iter(dictview)Mengembalikan iterator di atas kunci, nilai, atau item (diwakili sebagai tupel 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 197) dalam kamus
Kunci dan nilai diulang dalam urutan penyisipan. Ini memungkinkan pembuatan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _220 pasang menggunakan. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _222. Cara lain untuk membuat daftar yang sama adalah def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 223
Mengulangi tampilan sambil menambahkan atau menghapus entri dalam kamus dapat meningkatkan atau gagal mengulang semua entri
Berubah di versi 3. 7. Urutan kamus dijamin menjadi urutan penyisipan.
x di dictviewKembalikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _56 jika x ada di kunci, nilai, atau item kamus yang mendasarinya (dalam kasus terakhir, x harus berupa tuple def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 197)
terbalik (dictview)Mengembalikan iterator terbalik di atas kunci, nilai, atau item kamus. Tampilan akan diulang dalam urutan terbalik dari penyisipan
Berubah di versi 3. 8. Tampilan kamus kini dapat dibalik.
dictview. pemetaanKembalikan a yang membungkus kamus asli yang dirujuk oleh tampilan
New in version 3. 10
Tampilan kunci seperti set karena entri mereka unik dan dapat di-hash. Jika semua nilai hashable, 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 hashable, 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
Context Manager Types
Python’s statement supports the concept of a runtime context defined by a context manager. 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
Contoh pengelola konteks yang mengembalikan objek terkait adalah yang dikembalikan oleh. Manajer ini menyetel konteks desimal aktif ke salinan konteks desimal asli dan kemudian mengembalikan salinannya. Ini memungkinkan perubahan dilakukan pada konteks desimal saat ini di badan pernyataan tanpa memengaruhi kode di luar pernyataan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 081
pengelola konteks. __exit__(exc_type , exc_val, exc_tb)Keluar dari konteks runtime dan kembalikan flag Boolean yang menunjukkan jika ada pengecualian yang terjadi harus ditekan. Jika pengecualian terjadi saat menjalankan isi pernyataan, argumen berisi jenis pengecualian, nilai, dan informasi traceback. Jika tidak, ketiga argumen tersebut adalah def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _31
Mengembalikan nilai sebenarnya dari metode ini akan menyebabkan pernyataan menekan pengecualian dan melanjutkan eksekusi dengan pernyataan segera setelah pernyataan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 081. Kalau tidak, pengecualian terus menyebar setelah metode ini selesai dijalankan. 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 — ,
Tipe bawaan inti untuk adalah dan
Tipe Alias Generik
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 252 objek umumnya dibuat oleh sebuah kelas. Mereka paling sering digunakan dengan , seperti atau. Misalnya, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _255 adalah objek def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 252 yang dibuat dengan mensubskrip kelas def bit_count(self): return bin(self).count("1") 93 dengan argumen. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 252 objek dimaksudkan terutama untuk digunakan bersama
Note
Biasanya hanya mungkin untuk membuat subskrip kelas jika kelas tersebut mengimplementasikan metode khusus
Objek def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _252 bertindak sebagai proxy untuk a , mengimplementasikan generik berparameter
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 jenis, kami akan mewakili variasi objek ini dengan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 284
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 252 objek adalah turunan dari kelas, yang juga dapat digunakan untuk membuat objek def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 252 secara langsung
T[X, Y, . ]Membuat def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _252 yang mewakili tipe def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 289 yang diparameterisasi oleh tipe X, Y, dan lainnya bergantung pada def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 289 yang digunakan. Misalnya, sebuah fungsi mengharapkan elemen yang mengandung
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _05
Contoh lain untuk objek, menggunakan a , yang merupakan tipe generik yang mengharapkan dua parameter tipe yang mewakili tipe kunci dan tipe nilai. Dalam contoh ini, fungsi mengharapkan >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 68 dengan kunci tipe dan nilai tipe
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _06
Fungsi bawaan dan tidak menerima tipe def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _252 untuk argumen kedua mereka
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _07
Runtime Python tidak berlaku. Ini meluas ke tipe generik dan parameter tipenya. When creating a container object from a def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 252, the elements in the container are not checked against their type. Misalnya, kode berikut tidak dianjurkan, tetapi akan berjalan tanpa kesalahan
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _08
Selanjutnya, parameter generik menghapus parameter tipe selama pembuatan objek
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _09
Memanggil atau pada generik menunjukkan tipe parameter
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _10
Metode wadah umum akan memunculkan pengecualian untuk melarang kesalahan seperti def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 304
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _11
Namun, ekspresi seperti itu valid saat digunakan. Indeks harus memiliki elemen sebanyak item variabel tipe dalam objek def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 252
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _12
Kelas Generik Standar
Kelas pustaka standar berikut mendukung generik berparameter. Daftar ini tidak lengkap
Atribut Khusus dari def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _252 objek
Semua obat generik berparameter mengimplementasikan atribut read-only khusus
generikal. __origin__This attribute points at the non-parameterized generic class
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _13
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 PetunjukMemperkenalkan kerangka kerja Python untuk anotasi tipe
PEP 585 - Type Hinting Generics In Standard CollectionsIntroducing the ability to natively parameterize standard-library classes, provided they implement the special class method
, danDokumentasi 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 berarti X atau Y. Ini setara dengan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _374. Misalnya, fungsi berikut mengharapkan argumen bertipe or
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _16
union_object == lainnyaObjek 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
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
Namun, objek gabungan yang berisi tidak dapat digunakan
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _23
The user-exposed type for the union object can be accessed from and used for checks. 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
New in version 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 itu bukan, secara tegas, 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 memerlukan definisi (eksternal) untuk modul bernama foo di suatu tempat. )
Atribut khusus dari setiap modul adalah. Ini adalah kamus yang berisi tabel simbol modul. Memodifikasi kamus ini sebenarnya akan mengubah tabel simbol modul, tetapi penugasan langsung ke atribut tidak dimungkinkan (Anda dapat menulis def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 392, yang mendefinisikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 393 menjadi def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 55, tetapi Anda tidak dapat menulis def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 395). Memodifikasi secara langsung tidak disarankan
Modul yang dibangun ke dalam juru bahasa ditulis seperti ini. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 397. If loaded from a file, they are written as def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 398
Classes and Class Instances
See and for these
Functions
Function objects are created by function definitions. The only operation on a function object is to call it. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 399
There are really two flavors of function objects. built-in functions and user-defined functions. Both support the same operation (to call the function), but the implementation is different, hence the different object types
Lihat untuk informasi lebih lanjut
Metode
Metode adalah fungsi yang dipanggil menggunakan notasi atribut. Ada dua rasa. metode bawaan (seperti def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _400 pada daftar) dan metode instance kelas. Metode bawaan dijelaskan dengan tipe yang mendukungnya
Jika Anda mengakses metode (fungsi yang didefinisikan dalam ruang nama kelas) melalui sebuah instance, Anda mendapatkan objek khusus. objek metode terikat (juga disebut metode instan). 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 is the object on which the method operates, and def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 403 is the function implementing the method. 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 diekstrak 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. 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
A code object can be executed or evaluated by passing it (instead of a source string) to the or built-in functions
Lihat untuk informasi lebih lanjut
Ketik Objek
Jenis objek mewakili berbagai jenis objek. Jenis objek diakses oleh fungsi bawaan. Tidak ada operasi khusus pada tipe. Modul standar menentukan nama untuk semua tipe bawaan standar
Jenis ditulis seperti ini. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _419
Objek Null
Objek ini dikembalikan oleh fungsi yang tidak mengembalikan nilai secara eksplisit. Ini tidak mendukung operasi khusus. 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. Tepatnya ada satu objek def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _428. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 429 menghasilkan instance tunggal
Itu ditulis sebagai def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _428
Nilai Boolean
Nilai Boolean adalah dua objek konstan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 dan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56. Mereka digunakan untuk mewakili nilai kebenaran (walaupun nilai lain juga dapat dianggap salah atau benar). Dalam konteks numerik (misalnya ketika digunakan sebagai argumen untuk operator aritmatika), masing-masing berperilaku seperti bilangan bulat 0 dan 1. Fungsi bawaan dapat digunakan untuk mengonversi nilai apa pun menjadi Boolean, jika nilainya dapat diartikan sebagai nilai kebenaran (lihat bagian di atas)
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
kelas. __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
class. __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"). Tidak ada algoritma yang dapat mengubah string menjadi bilangan bulat biner atau bilangan bulat biner menjadi string dalam waktu linier, kecuali basisnya adalah kekuatan 2. Bahkan algoritma paling terkenal untuk basis 10 memiliki kompleksitas sub-kuadrat. Mengonversi nilai besar seperti def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _441 dapat memakan waktu lebih dari satu detik pada CPU yang cepat
Membatasi ukuran konversi menawarkan cara praktis untuk menghindari CVE-2020-10735
Batas diterapkan pada jumlah karakter digit dalam string input atau output ketika algoritma konversi non-linear akan dilibatkan. Garis bawah dan tanda tidak dihitung terhadap batas
Ketika suatu operasi akan melebihi batas, a dinaikkan
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _28
Batas default adalah 4300 digit seperti yang disediakan di. Batas terendah yang dapat dikonfigurasi adalah 640 digit seperti yang disediakan di
Verifikasi
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _29
Baru di versi 3. 11
API yang terpengaruh
Pembatasan hanya berlaku untuk konversi yang berpotensi lambat antara dan atau
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 448 with default base 10
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 449 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 opsi env var 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 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. Konsekuensi dari pengaturan batas adalah bahwa kode sumber Python yang berisi literal bilangan bulat desimal lebih lama dari batas akan mengalami kesalahan selama penguraian, biasanya pada waktu startup atau waktu impor atau bahkan pada waktu instalasi - kapan saja def bit_length(self): 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 yang diperbarui belum ada untuk . Solusi untuk sumber yang berisi konstanta besar seperti itu adalah mengubahnya 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 tes 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
Standar def bit_length(self): 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 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