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') --> 631 Show
Beberapa operasi didukung oleh beberapa tipe objek; . Fungsi yang terakhir secara implisit digunakan ketika sebuah objek ditulis oleh fungsi tersebut Pengujian Nilai KebenaranObjek 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') --> 637 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') --> 638 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') --> 639 yang mengembalikan nol, saat dipanggil dengan objek. Berikut adalah sebagian besar objek bawaan yang dianggap salah
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') --> 642 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') --> 638 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') --> 655 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') --> 656 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') --> 657 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') --> 658 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 61Ini 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') --> 638 (3) Catatan
ComparisonsAda delapan operasi perbandingan di Python. They all have the same priority (which is higher than that of the Boolean operations). Comparisons can be chained arbitrarily; for example, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 671 is equivalent to def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 672, except that y is evaluated only once (but in both cases z is not evaluated at all when def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 673 is found to be false) This table summarizes the comparison operations Operasi Meaning def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_74 ketat kurang dari def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 675 less than or equal def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 676 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') --> 678 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') --> 679 not equal def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_80 object identity def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_81 negated object identity Objek dari tipe yang berbeda, kecuali tipe numerik yang berbeda, tidak pernah sebanding. Operator def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 678 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') --> 674, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 675, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 676 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') --> 677 hanya didefinisikan jika masuk akal; Contoh kelas yang tidak identik biasanya dibandingkan sebagai tidak sama kecuali kelas tersebut mendefinisikan metodenya Instances of a class cannot be ordered with respect to other instances of the same class, or other types of object, unless the class defines enough of the methods , , , and (in general, and are sufficient, if you want the conventional meanings of the comparison operators) The behavior of the and operators cannot be customized; also they can be applied to any two objects and never raise an exception Two more operations with the same syntactic priority, and , are supported by types that are or implement the >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 300 method Jenis Numerik — , ,Ada tiga tipe numerik yang berbeda. bilangan bulat, bilangan floating point, dan bilangan kompleks. Selain itu, Boolean adalah subtipe dari bilangan bulat. Bilangan bulat memiliki presisi tak terbatas. Angka floating point biasanya diimplementasikan menggunakan double di C; . Bilangan kompleks memiliki bagian nyata dan imajiner, yang masing-masing merupakan bilangan floating point. Untuk mengekstrak bagian ini dari bilangan kompleks z, gunakan >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 305 dan >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 306. (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() 309 atau >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 310 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() 314 jumlah x dan y >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 315 selisih x dan y >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 316 produk dari x dan y >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 317 hasil bagi x dan y >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 318 hasil bagi berlantai dari x dan y (1) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 319 remainder of >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 317 (2) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 321 x negated >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 322 x tidak berubah >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 323 absolute value or magnitude of x >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 325 x dikonversi ke bilangan bulat (3)(6) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 327 x dikonversi ke floating point (4)(6) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 329 bilangan kompleks dengan bagian real re, bagian imajiner in. im defaults to zero (6) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 331 konjugasi bilangan kompleks c >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 332 the pair >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 333 (2) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 335 x pangkat y (5) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 337 x pangkat y (5) Catatan
All types ( and ) also include the following operations Operasi Hasil x truncated to x dibulatkan menjadi n digit, dibulatkan setengah menjadi genap. Jika n dihilangkan, defaultnya adalah 0 terbesar <= x minimal >= x Untuk operasi numerik tambahan, lihat dan modul Operasi Bitwise pada Jenis IntegerOperasi bitwise hanya masuk akal untuk bilangan bulat. Hasil operasi bitwise dihitung seolah-olah dilakukan dalam komplemen dua dengan jumlah bit tanda yang tak terhingga Prioritas operasi bitwise biner semuanya lebih rendah dari operasi numerik dan lebih tinggi dari perbandingan; This table lists the bitwise operations sorted in ascending priority Operasi Hasil Catatan >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 371 bitwise atau dari x dan y (4) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 372 eksklusif bitwise atau dari x dan y (4) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 373 bitwise dan dari x dan y (4) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 374 x digeser ke kiri sebanyak n bit (1)(2) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 375 x digeser ke kanan sebanyak n bit (1)(3) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 376 the bits of x inverted Catatan
Metode Tambahan pada Tipe IntegerTipe int mengimplementasikan. In addition, it provides a few more methods int. bit_length()Kembalikan jumlah bit yang diperlukan untuk mewakili bilangan bulat dalam biner, tidak termasuk tanda dan angka nol di depan >>> n = -37 >>> bin(n) '-0b100101' >>> n.bit_length() 6 Lebih tepatnya, jika >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 382 bukan nol, maka >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 383 adalah bilangan bulat positif unik >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 384 sehingga >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 385. Equivalently, when >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 323 is small enough to have a correctly rounded logarithm, then >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 387. If >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 382 is zero, then >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 383 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') --> 642 Setara dengan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 Baru di versi 3. 1 int. bit_count()Return the number of ones in the binary representation of the absolute value of the integer. This is also known as the population count. Contoh >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 Setara dengan def bit_count(self): return bin(self).count("1") Baru di versi 3. 10 int. to_bytes(panjang=1, byteorder='big', *, signed=False)Mengembalikan array byte yang mewakili bilangan bulat >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' Bilangan bulat direpresentasikan menggunakan byte panjang, dan standarnya adalah 1. An dimunculkan jika bilangan bulat tidak dapat diwakili dengan jumlah byte yang diberikan Argumen byteorder menentukan urutan byte yang digunakan untuk mewakili bilangan bulat, dan standarnya adalah >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 392. Jika byteorder adalah >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3_92, byte paling signifikan ada di awal array byte. Jika byteorder adalah >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3_94, byte paling signifikan ada di akhir array byte Argumen yang ditandatangani menentukan apakah komplemen dua digunakan untuk mewakili bilangan bulat. Jika ditandatangani adalah def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_38 dan bilangan bulat negatif diberikan, an dinaikkan. The default value for signed is def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 The default values can be used to conveniently turn an integer into a single byte object. Namun, saat menggunakan argumen default, jangan mencoba mengonversi nilai yang lebih besar dari 255 atau Anda akan mendapatkan >>> (65).to_bytes() b'A' Setara dengan def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) Baru di versi 3. 2 Berubah di versi 3. 11. Added default argument values for >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 399 and def bit_count(self): return bin(self).count("1")00. classmethod int. from_bytes(byte , byteorder='big', *, signed=False) Kembalikan bilangan bulat yang diwakili oleh larik byte yang diberikan >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 Byte argumen harus berupa byte penghasil a atau iterable Argumen byteorder menentukan urutan byte yang digunakan untuk mewakili bilangan bulat, dan standarnya adalah >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 392. Jika byteorder adalah >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3_92, byte paling signifikan ada di awal array byte. If byteorder is >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 394, the most significant byte is at the end of the byte array. Untuk meminta urutan byte asli dari sistem host, gunakan sebagai nilai urutan byte Argumen yang ditandatangani menunjukkan apakah komplemen dua digunakan untuk mewakili bilangan bulat Setara dengan def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n Baru di versi 3. 2 Changed in version 3. 11. Menambahkan nilai argumen default untuk def bit_count(self): return bin(self).count("1")00. int. as_integer_ratio() Kembalikan sepasang bilangan bulat yang rasionya persis sama dengan bilangan bulat asli dan dengan penyebut positif. Rasio bilangan bulat bilangan bulat (bilangan bulat) selalu bilangan bulat sebagai pembilang dan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 655 sebagai penyebut Baru di versi 3. 8 Metode Tambahan di FloatTipe float mengimplementasikan. float also has the following additional methods mengambang. as_integer_ratio()Kembalikan sepasang bilangan bulat yang rasionya persis sama dengan float asli dan dengan penyebut positif. Menaikkan infinitas dan NaN mengambang. is_integer()Kembalikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_56 jika instance float terbatas dengan nilai integral, dan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 sebaliknya >>> (-2.0).is_integer() True >>> (3.2).is_integer() False Dua metode mendukung konversi ke dan dari string heksadesimal. Karena pelampung Python disimpan secara internal sebagai bilangan biner, mengonversi pelampung ke atau dari string desimal biasanya melibatkan kesalahan pembulatan kecil. Sebaliknya, string heksadesimal memungkinkan representasi yang tepat dan spesifikasi angka floating-point. Ini dapat berguna saat melakukan debug, dan dalam pekerjaan numerik mengambang. hex()Mengembalikan representasi angka floating-point sebagai string heksadesimal. Untuk bilangan floating-point terbatas, representasi ini akan selalu menyertakan def bit_count(self): return bin(self).count("1")12 di depan dan def bit_count(self): return bin(self).count("1")13 di belakang dan eksponenmetode kelas float. fromhex(s) Metode kelas untuk mengembalikan float yang diwakili oleh string heksadesimal s. String s mungkin memiliki spasi putih di depan dan di belakang Perhatikan bahwa itu adalah metode instan, sementara itu adalah metode kelas Sebuah string heksadesimal mengambil bentuk def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 60 di mana def bit_count(self): return bin(self).count("1")16 opsional dapat dengan ________51______69 atau >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 370, def bit_count(self): return bin(self).count("1")19 dan def bit_count(self): return bin(self).count("1")20 adalah string digit heksadesimal, dan def bit_count(self): return bin(self).count("1")21 adalah bilangan bulat desimal dengan tanda awal opsional. Huruf besar kecil tidak signifikan, dan harus ada setidaknya satu digit heksadesimal baik dalam bilangan bulat maupun pecahan. Sintaks ini mirip dengan sintaks yang ditentukan di bagian 6. 4. 4. 2 dari standar C99, dan juga sintaks yang digunakan di Java 1. 5 dan seterusnya. Secara khusus, output dari dapat digunakan sebagai literal floating-point heksadesimal dalam kode C atau Java, dan string heksadesimal yang dihasilkan oleh karakter format def bit_count(self): return bin(self).count("1")23 C atau def bit_count(self): return bin(self).count("1")24 Java diterima oleh Perhatikan bahwa eksponen ditulis dalam desimal dan bukan heksadesimal, dan memberikan pangkat 2 untuk mengalikan koefisien. Misalnya, string heksadesimal def bit_count(self): return bin(self).count("1")26 mewakili bilangan floating-point def bit_count(self): return bin(self).count("1")27, atau def bit_count(self): return bin(self).count("1")28 def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_1 Menerapkan konversi terbalik ke def bit_count(self): return bin(self).count("1")_28 memberikan string heksadesimal berbeda yang mewakili angka yang sama def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_2 Hashing tipe numerikUntuk nomor >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 382 dan def bit_count(self): return bin(self).count("1")31, mungkin dari jenis yang berbeda, itu adalah persyaratan bahwa def bit_count(self): return bin(self).count("1")32 setiap kali def bit_count(self): return bin(self).count("1")33 (lihat dokumentasi metode untuk detail lebih lanjut). Untuk kemudahan implementasi dan efisiensi di berbagai tipe numerik (termasuk , , dan ) hash Python untuk tipe numerik didasarkan pada fungsi matematika tunggal yang ditentukan untuk bilangan rasional apa pun, dan karenanya berlaku untuk semua instance dari and , dan semua instance terbatas . Pada dasarnya, fungsi ini diberikan oleh modulo reduksi def bit_count(self): return bin(self).count("1")43 untuk bilangan prima tetap def bit_count(self): return bin(self).count("1")43. Nilai def bit_count(self): return bin(self).count("1")_43 disediakan untuk Python sebagai atribut def bit_count(self): return bin(self).count("1")46 dari Detail implementasi CPython. Saat ini, bilangan prima yang digunakan adalah def bit_count(self): return bin(self).count("1")_48 pada mesin dengan long C 32-bit dan def bit_count(self): return bin(self).count("1")49 pada mesin dengan long C 64-bit Berikut aturannya secara detail
Untuk memperjelas aturan di atas, berikut adalah beberapa contoh kode Python, yang setara dengan hash bawaan, untuk menghitung hash bilangan rasional, , atau def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_3 Jenis IteratorPython mendukung konsep iterasi melalui kontainer. Ini diimplementasikan menggunakan dua metode berbeda; . Urutan, dijelaskan di bawah ini secara lebih rinci, selalu mendukung metode iterasi Salah satu metode perlu didefinisikan untuk objek wadah untuk memberikan dukungan wadah. __iter__()Mengembalikan objek. Objek diperlukan untuk mendukung protokol iterator yang dijelaskan di bawah ini. If a container supports different types of iteration, additional methods can be provided to specifically request iterators for those iteration types. (Contoh objek yang mendukung berbagai bentuk iterasi adalah struktur pohon yang mendukung traversal pertama lebar dan kedalaman pertama. ) Metode ini sesuai dengan slot struktur tipe untuk objek Python di Python/C API Objek iterator itu sendiri diperlukan untuk mendukung dua metode berikut, yang bersama-sama membentuk protokol iterator iterator. __iter__()Kembalikan objek itu sendiri. Ini diperlukan agar container dan iterator dapat digunakan dengan pernyataan and. Metode ini sesuai dengan slot struktur tipe untuk objek Python di Python/C API iterator. __selanjutnya__()Mengembalikan item berikutnya dari. Jika tidak ada item lebih lanjut, ajukan pengecualian. Metode ini sesuai dengan slot struktur tipe untuk objek Python di Python/C API Python mendefinisikan beberapa objek iterator untuk mendukung iterasi pada tipe urutan umum dan spesifik, kamus, dan bentuk lain yang lebih khusus. Jenis spesifik tidak penting di luar penerapan protokol iterator Setelah metode iterator raise , metode tersebut harus terus melakukannya pada panggilan berikutnya. Implementasi yang tidak mematuhi properti ini dianggap rusak Jenis PembangkitPython menyediakan cara mudah untuk mengimplementasikan protokol iterator. Jika metode def bit_count(self): return bin(self).count("1")_90 objek kontainer diimplementasikan sebagai generator, ia akan secara otomatis mengembalikan objek iterator (secara teknis, objek generator) yang memasok def bit_count(self): return bin(self).count("1")90 dan metode. Informasi lebih lanjut tentang generator dapat ditemukan di Jenis Urutan — , ,Ada tiga jenis urutan dasar. list, tuple, dan range objek. Jenis urutan tambahan yang disesuaikan untuk pemrosesan dan dijelaskan dalam bagian khusus Operasi Urutan UmumOperasi dalam tabel berikut ini didukung oleh sebagian besar tipe urutan, baik yang dapat diubah maupun yang tidak dapat diubah. ABC disediakan untuk mempermudah penerapan operasi ini dengan benar pada tipe urutan kustom Tabel ini mencantumkan operasi urutan yang diurutkan dalam prioritas menaik. Dalam tabel, s dan t adalah urutan dari tipe yang sama, n, i, j dan k adalah bilangan bulat dan x adalah objek arbitrer yang memenuhi batasan tipe dan nilai apa pun yang diberlakukan oleh s Operasi def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 698 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') --> 699 memiliki prioritas yang sama dengan operasi pembanding. Operasi >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3_69 (penggabungan) dan >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'00 (pengulangan) memiliki prioritas yang sama dengan operasi numerik yang sesuai. Operasi Hasil Catatan >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'_01 def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 jika item s sama dengan x, jika tidak def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 (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') --> 638 jika item s sama dengan x, jika tidak def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 (1) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'_07 gabungan dari s dan t (6)(7) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'_08 atau >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'09 setara dengan menambahkan s ke dirinya sendiri sebanyak n kali (2)(7) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'_10 item ke-i dari s, asal 0 (3) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'_11 potongan s dari i ke j (3)(4) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'_12 potongan s dari i ke j dengan langkah k (3)(5) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'_13 panjang s >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'_14 item terkecil dari s >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'_15 item terbesar dari s >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'_16 indeks kemunculan pertama x dalam s (pada atau setelah indeks i dan sebelum indeks j) (8) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'_17 jumlah total kemunculan x dalam s Urutan dari jenis yang sama juga mendukung perbandingan. Secara khusus, tupel dan daftar dibandingkan secara leksikografis dengan membandingkan elemen yang sesuai. Ini berarti bahwa untuk membandingkan sama, setiap elemen harus membandingkan sama dan dua urutan harus dari jenis yang sama dan memiliki panjang yang sama. (Untuk perincian lengkap lihat di referensi bahasa. ) Meneruskan dan membalikkan iterator melalui nilai akses urutan yang dapat diubah menggunakan indeks. Indeks itu akan terus bergerak maju (atau mundur) bahkan jika urutan yang mendasarinya dimutasi. Iterator berakhir hanya ketika atau ditemui (atau ketika indeks turun di bawah nol) Catatan
Immutable Sequence TypesThe 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 TypesThe operations in the following table are defined on mutable sequence types. The ABC is provided to make it easier to correctly implement these operations on custom sequence types In the table s is an instance of a mutable sequence type, t is any iterable object and x is an arbitrary object that meets any type and value restrictions imposed by s (for example, only accepts integers that meet the value restriction >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'74) Operasi Hasil Catatan >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'75 item i of s is replaced by x >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'76 slice of s from i to j is replaced by the contents of the iterable t >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'77 same as >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'78 >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'79 the elements of >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'12 are replaced by those of t (1) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'81 removes the elements of >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'12 from the list >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'83 appends x to the end of the sequence (same as >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'84) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'85 removes all items from s (same as >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'86) (5) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'87 creates a shallow copy of s (same as >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'88) (5) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'89 or >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'90 extends s with the contents of t (for the most part the same as >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'91) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'92 updates s with its contents repeated n times (6) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'93 inserts x into s at the index given by i (same as >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'94) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'95 or >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'96 retrieves the item at i and also removes it from s (2) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'97 remove the first item from s where >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'10 is equal to x (3) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'99 reverses the items of s in place (4) Catatan
ListsLists 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
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') --> 649 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') --> 674 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') --> 631 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') --> 656, then the list elements are sorted as if each comparison were reversed This method modifies the sequence in place for economy of space when sorting a large sequence. To remind users that it operates by side effect, it does not return the sorted sequence (use to explicitly request a new sorted list instance) The method is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade) For sorting examples and a brief sorting tutorial, see CPython implementation detail. While a list is being sorted, the effect of attempting to mutate, or even inspect, the list is undefined. The C implementation of Python makes the list appear empty for the duration, and raises if it can detect that the list has been mutated during a sort TuplesTuples 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
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') --> 648 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 RangesThe 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') --> 655. 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') --> 642. If step is zero, is raised Untuk langkah positif, isi rentang >>> (65).to_bytes() b'A'62 ditentukan dengan rumus >>> (65).to_bytes() b'A'63 di mana >>> (65).to_bytes() b'A'64 dan >>> (65).to_bytes() b'A'65 For a negative step, the contents of the range are still determined by the formula >>> (65).to_bytes() b'A'63, but the constraints are >>> (65).to_bytes() b'A'64 and >>> (65).to_bytes() b'A'68 A range object will be empty if >>> (65).to_bytes() b'A'69 does not meet the value constraint. Ranges do support negative indices, but these are interpreted as indexing from the end of the sequence determined by the positive indices Ranges containing absolute values larger than are permitted but some features (such as ) may raise Range examples def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 67 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') --> 642 if the parameter was not supplied)stop The value of the stop parameter stepThe value of the step parameter (or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 655 if the parameter was not supplied) Keuntungan dari tipe dibandingkan reguler atau adalah bahwa suatu objek akan selalu mengambil jumlah memori (kecil) yang sama, tidak peduli ukuran rentang yang diwakilinya (karena hanya menyimpan nilai >>> (65).to_bytes() b'A'79, >>> (65).to_bytes() b'A'80 dan >>> (65).to_bytes() b'A'81, menghitung masing-masing item Range objects implement the ABC, and provide features such as containment tests, element index lookup, slicing and support for negative indices (see ) def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 68 Testing range objects for equality with def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 678 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') --> 679 compares them as sequences. That is, two range objects are considered equal if they represent the same sequence of values. (Note that two range objects that compare equal might have different , and attributes, for example >>> (65).to_bytes() b'A'88 or >>> (65).to_bytes() b'A'89. ) Changed in version 3. 2. Implement the Sequence ABC. Support slicing and negative indices. Uji objek untuk keanggotaan dalam waktu konstan alih-alih mengulangi semua item. Changed in version 3. 3. Define ‘==’ and ‘. =’ to compare range objects based on the sequence of values they define (instead of comparing based on object identity). New in version 3. 3. The , and attributes. See also
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
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') --> 633 depends on whether encoding or errors is given, as follows If neither encoding nor errors is given, def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)09 returns , which is the “informal” or nicely printable string representation of object. For string objects, this is the string itself. If object does not have a method, then falls back to returning If at least one of encoding or errors is given, object should be a (e. g. or ). In this case, if object is a (or ) object, then def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)18 is equivalent to . Otherwise, the bytes object underlying the buffer object is obtained before calling . See and for information on buffer objects Passing a object to without the encoding or errors arguments falls under the first case of returning the informal string representation (see also the command-line option to Python). For example def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 69 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 MethodsStrings implement all of the sequence operations, along with the additional methods described below Strings also support two styles of string formatting, one providing a large degree of flexibility and customization (see , and ) and the other based on C def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)26 style formatting that handles a narrower range of types and is slightly harder to use correctly, but is often faster for the cases it can handle () Bagian pustaka standar mencakup sejumlah modul lain yang menyediakan berbagai utilitas terkait teks (termasuk dukungan ekspresi reguler dalam modul) str. capitalize()Return a copy of the string with its first character capitalized and the rest lowercased Changed in version 3. 8. The first character is now put into titlecase rather than uppercase. This means that characters like digraphs will only have their first letter capitalized, instead of the full character. str. casefold()Return a casefolded copy of the string. Casefolded strings may be used for caseless matching Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)28 is equivalent to def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)29. Since it is already lowercase, would do nothing to def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)28; converts it to def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)29 The casefolding algorithm is described in section 3. 13 of the Unicode Standard New in version 3. 3 str. center(width[ , fillchar])Return centered in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'13str. count(sub[ , start[ , end]]) Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation If sub is empty, returns the number of empty strings between characters which is the length of the string plus one str. encode(encoding='utf-8' , errors='strict')Return the string encoded to encoding defaults to def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)36; see for possible values errors controls how encoding errors are handled. If def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)37 (the default), a exception is raised. Other possible values are def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)39, def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)40, def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)41, def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)42 and any other name registered via . See for details For performance reasons, the value of errors is not checked for validity unless an encoding error actually occurs, is enabled or a is used Changed in version 3. 1. Added support for keyword arguments. Changed in version 3. 9. The value of the errors argument is now checked in and in . str. endswith(suffix[ , start[ , end]])Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if the string ends with the specified suffix, otherwise return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638. 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 positionstr. expandtabs(tabsize=8) Return a copy of the string where all tab characters are replaced by one or more spaces, depending on the current column and the given tab size. Tab positions occur every tabsize characters (default is 8, giving tab positions at columns 0, 8, 16 and so on). To expand the string, the current column is set to zero and the string is examined character by character. If the character is a tab ( def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)46), one or more space characters are inserted in the result until the current column is equal to the next tab position. (The tab character itself is not copied. ) If the character is a newline ( def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)47) or return ( def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)48), it is copied and the current column is reset to zero. Any other character is copied unchanged and the current column is incremented by one regardless of how the character is represented when printed >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 30str. 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() 341 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() 31str. format(*args , **kwargs) Lakukan operasi pemformatan string. The string on which this method is called can contain literal text or replacement fields delimited by braces def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 650. 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() 32 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() 33 Baru di versi 3. 2 str. index(sub[ , start[ , end]])Like , but raise when the substring is not found str. isalnum()Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 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') --> 638 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') --> 656. 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)83str. 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') --> 656 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') --> 638 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 Standardstr. 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') --> 656 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') --> 638 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') --> 656 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') --> 638 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') --> 656 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') --> 638 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=Decimalstr. 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') --> 656 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() 34str. 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') --> 656 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') --> 638 otherwisestr. 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') --> 656 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') --> 638 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=Numericstr. 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') --> 656 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') --> 638 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') --> 656 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') --> 638 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') 1671168009 (“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') 1671168010, >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168011, 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') 1671168012str. istitle() Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 otherwisestr. 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') --> 656 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') --> 638 otherwise >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 35str. join(iterable) Return a string which is the concatenation of the strings in iterable. A will be raised if there are any non-string values in iterable, including objects. The separator between elements is the string providing this method str. ljust(width[ , fillchar])Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'13str. lower() Return a copy of the string with all the cased characters converted to lowercase The lowercasing algorithm used is described in section 3. 13 of the Unicode Standard str. lstrip([chars])Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631, the chars argument defaults to removing whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 36 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() 37static 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') --> 631. 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') --> 631 in the resultstr. 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') 1671168025. Otherwise, return a copy of the original string >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 38 New in version 3. 9 str. removesuffix(suffix , /)If the string ends with the suffix string and that suffix is not empty, return >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168026. Otherwise, return a copy of the original string >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 39 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() 341 on failurestr. 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'13str. 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') --> 631, any whitespace string is a separator. Except for splitting from the right, behaves like which is described in detail belowstr. 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') --> 631, 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")1str. split(sep=None , maxsplit=- 1) Kembalikan daftar kata dalam string, gunakan sep sebagai string pembatas. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168037 elements). If maxsplit is not specified or >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 341, 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') 1671168039 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') 1671168040). 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') 1671168041 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') 1671168042). 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') 1671168043 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') --> 631, a different splitting algorithm is applied. menjalankan spasi putih berurutan dianggap sebagai pemisah tunggal, dan hasilnya tidak akan berisi string kosong di awal atau akhir jika string memiliki spasi putih di depan atau di belakang. Akibatnya, memisahkan string kosong atau string yang hanya terdiri dari spasi kosong dengan pemisah def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631 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') --> 649 For example def bit_count(self): return bin(self).count("1")3str. splitlines(keepends=False) Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true This method splits on the following line boundaries. In particular, the boundaries are a superset of Representation Description def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)47 Line Feed def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)48 Carriage Return >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168049 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') 1671168050 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') 1671168051 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') 1671168052 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') 1671168053 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') 1671168054 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') 1671168055 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') 1671168056 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') 1671168057 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') 1671168058 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') 1671168059 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') 1671168050 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') 1671168052 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') 1671168063 gives def bit_count(self): return bin(self).count("1")6str. 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') --> 656 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') --> 638. 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 positionstr. 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') --> 631, 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")8str. 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') 1671168067str. 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'1str. 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') 1671168069, typically a or . When indexed by a Unicode ordinal (an integer), the table object can do any of the following. return a Unicode ordinal or a string, to map the character to one or more other characters; return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631, 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') 1671168074 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') --> 638 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') 1671168077 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') 1671168078/ >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168079) 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 FormattingNote 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') 1671168083 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') 1671168084 (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') 1671168083 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') 1671168086 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
When the right argument is a dictionary (or other mapping type), then the formats in the string must include a parenthesised mapping key into that dictionary inserted immediately after the >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168087 character. The mapping key selects the value to be formatted from the mapping. For example >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'3 In this case no >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'00 specifiers may occur in a format (since they require a sequential parameter list) The conversion flag characters are Flag Meaning >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680_94 The value conversion will use the “alternate form” (where defined below) >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168077 The conversion will be zero padded for numeric values >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168079 The converted value is left adjusted (overrides the >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168077 conversion if both are given) >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168098 (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') 1671168078 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') 1671168078 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') 1671168079) 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 n02, 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 n03, 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 n04) 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 n05 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 n06 The conversion types are Conversion Meaning Catatan def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n07 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 n08 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 n09 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 n10 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 n07 (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 n12 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 n13 Heksadesimal bertanda (huruf besar) (2) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n14 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 n15 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 n16 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 n17 Floating point decimal format (3) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n_18 Format titik mengambang. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise (4) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n19 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 n20 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 n21 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 n23 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 n25 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') 1671168087 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') 1671168087 character in the result Catatan
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 n36 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 n37 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 n38 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 n39 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 ObjectsObjek byte adalah urutan byte tunggal yang tidak dapat diubah. Since many major binary protocols are based on the ASCII text encoding, bytes objects offer several methods that are only valid when working with ASCII compatible data and are closely related to string objects in a variety of other ways class bytes([source[ , encoding[ , errors]]])Firstly, the syntax for bytes literals is largely the same as that for string literals, except that a def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n47 prefix is added
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 n53 (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
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 n61 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 n62 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 n63) 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 n64. 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 n65 Bytearray Objectsobjects 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
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 n61 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 n62 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 n78) 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 n65 Bytes and Bytearray OperationsBoth bytes and bytearray objects support the sequence operations. They interoperate not just with operands of the same type, but with any . Due to this flexibility, they can be freely mixed in operations without causing errors. However, the return type of the result may depend on the order of operands Note The methods on bytes and bytearray objects don’t accept strings as their arguments, just as the methods on strings don’t accept bytes as their arguments. For example, you have to write >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'9 and >>> (65).to_bytes() b'A'0 Some bytes and bytearray operations assume the use of ASCII compatible binary formats, and hence should be avoided when working with arbitrary binary data. These restrictions are covered below Note Using these ASCII based operations to manipulate binary data that is not stored in an ASCII based format may lead to data corruption The following methods on bytes and bytearray objects can be used with arbitrary binary data bytes. count(sub[ , start[ , end]])bytearray. count(sub[ , start[ , end]])Return the number of non-overlapping occurrences of subsequence sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation The subsequence to search for may be any or an integer in the range 0 to 255 If sub is empty, returns the number of empty slices between characters which is the length of the bytes object plus one Changed in version 3. 3. Also accept an integer in the range 0 to 255 as the subsequence. bytes. removeprefix(prefix , /)bytearray. hapus awalan(awalan , /)If the binary data starts with the prefix string, return def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n81. Otherwise, return a copy of the original binary data >>> (65).to_bytes() b'A'1 The prefix may be any Note Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan New in version 3. 9 bytes. removesuffix(suffix , /)bytearray. removesuffix(suffix , /)If the binary data ends with the suffix string and that suffix is not empty, return def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n82. Otherwise, return a copy of the original binary data >>> (65).to_bytes() b'A'2 The suffix may be any Note Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan New in version 3. 9 bytes. decode(encoding='utf-8' , errors='strict')bytearray. decode(encoding='utf-8' , errors='strict')Return the bytes decoded to a encoding defaults to def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)36; see for possible values errors controls how decoding errors are handled. If def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)37 (the default), a exception is raised. Other possible values are def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)39, def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)40, and any other name registered via . See for details For performance reasons, the value of errors is not checked for validity unless a decoding error actually occurs, is enabled or a is used Note Passing the encoding argument to allows decoding any directly, without needing to make a temporary >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'23 or >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'24 object Changed in version 3. 1. Added support for keyword arguments. Changed in version 3. 9. The value of the errors argument is now checked in and in . byte. endswith(suffix[ , start[ , end]])bytearray. endswith(suffix[ , start[ , end]])Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 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') --> 638. 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() 341 if sub is not found The subsequence to search for may be any or an integer in the range 0 to 255 Note The method should be used only if you need to know the position of sub. To check if sub is a substring or not, use the operator >>> (65).to_bytes() b'A'3 Changed in version 3. 3. Also accept an integer in the range 0 to 255 as the subsequence. bytes. index(sub[ , start[ , end]])bytearray. index(sub[ , start[ , end]])Like , but raise when the subsequence is not found The subsequence to search for may be any or an integer in the range 0 to 255 Changed in version 3. 3. Also accept an integer in the range 0 to 255 as the subsequence. bytes. join(iterable)bytearray. join(iterable)Return a bytes or bytearray object which is the concatenation of the binary data sequences in iterable. A will be raised if there are any values in iterable that are not , including objects. The separator between elements is the contents of the bytes or bytearray object providing this method statis byte. maketrans(from , to)static bytearray. maketrans(from , to)This static method returns a translation table usable for that will map each character in from into the character at the same position in to; from and to must both be and have the same length Baru di versi 3. 1 bytes. partition(sep)bytearray. partition(sep)Split the sequence at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself or its bytearray copy, and the part after the separator. If the separator is not found, return a 3-tuple containing a copy of the original sequence, followed by two empty bytes or bytearray objects The separator to search for may be any bytes. replace(old , new[ , count])bytearray. replace(old , new[ , count])Return a copy of the sequence with all occurrences of subsequence old replaced by new. If the optional argument count is given, only the first count occurrences are replaced The subsequence to search for and its replacement may be any Note Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan bytes. rfind(sub[ , start[ , end]])bytearray. rfind(sub[ , start[ , end]])Return the highest index in the sequence where the subsequence sub is found, such that sub is contained within def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)49. Optional arguments start and end are interpreted as in slice notation. Return >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 341 on failure The subsequence to search for may be any or an integer in the range 0 to 255 Changed in version 3. 3. Also accept an integer in the range 0 to 255 as the subsequence. bytes. rindex(sub[ , start[ , end]])bytearray. rindex(sub[ , start[ , end]])Like but raises when the subsequence sub is not found The subsequence to search for may be any or an integer in the range 0 to 255 Changed in version 3. 3. Also accept an integer in the range 0 to 255 as the subsequence. bytes. rpartition(sep)bytearray. rpartition(sep)Split the sequence at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself or its bytearray copy, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty bytes or bytearray objects, followed by a copy of the original sequence The separator to search for may be any bytes. startswith(prefix[ , start[ , end]])bytearray. startswith(prefix[ , start[ , end]])Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if the binary data starts with the specified prefix, otherwise return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638. prefix can also be a tuple of prefixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position The prefix(es) to search for may be any bytes. translate(table , / , delete=b'')bytearray. translate(table , / , delete=b'')Return a copy of the bytes or bytearray object where all bytes occurring in the optional argument delete are removed, and the remaining bytes have been mapped through the given translation table, which must be a bytes object of length 256 You can use the method to create a translation table Set the table argument to def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631 for translations that only delete characters >>> (65).to_bytes() b'A'4 Changed in version 3. 6. delete is now supported as a keyword argument. The following methods on bytes and bytearray objects have default behaviours that assume the use of ASCII compatible binary formats, but can still be used with arbitrary binary data by passing appropriate arguments. Note that all of the bytearray methods in this section do not operate in place, and instead produce new objects bytes. center(width[ , fillbyte])bytearray. center(width[ , fillbyte])Return a copy of the object centered in a sequence of length width. Padding is done using the specified fillbyte (default is an ASCII space). For objects, the original sequence is returned if width is less than or equal to >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'13 Note Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan bytes. ljust(width[ , fillbyte])bytearray. ljust(width[ , fillbyte])Return a copy of the object left justified in a sequence of length width. Padding is done using the specified fillbyte (default is an ASCII space). For objects, the original sequence is returned if width is less than or equal to >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'13 Note Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan bytes. lstrip([chars])bytearray. lstrip([chars])Return a copy of the sequence with specified leading bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631, the chars argument defaults to removing ASCII whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped >>> (65).to_bytes() b'A'5 The binary sequence of byte values to remove may be any . See for a method that will remove a single prefix string rather than all of a set of characters. For example >>> (65).to_bytes() b'A'_6 Note Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan bytes. rjust(width[ , fillbyte])bytearray. rjust(width[ , fillbyte])Return a copy of the object right justified in a sequence of length width. Padding is done using the specified fillbyte (default is an ASCII space). For objects, the original sequence is returned if width is less than or equal to >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'13 Note Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan bytes. rsplit(sep=None , maxsplit=- 1)bytearray. rsplit(sep=None , maxsplit=- 1)Split the binary sequence into subsequences of the same type, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631, any subsequence consisting solely of ASCII whitespace is a separator. Except for splitting from the right, behaves like which is described in detail belowbytes. rstrip([chars])bytearray. rstrip([chars]) Return a copy of the sequence with specified trailing bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631, the chars argument defaults to removing ASCII whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped >>> (65).to_bytes() b'A'7 The binary sequence of byte values to remove may be any . See for a method that will remove a single suffix string rather than all of a set of characters. For example >>> (65).to_bytes() b'A'8 Note Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan bytes. split(sep=None , maxsplit=- 1)bytearray. split(sep=None , maxsplit=- 1)Pisahkan urutan biner menjadi suburutan dengan jenis yang sama, menggunakan sep sebagai string pembatas. If maxsplit is given and non-negative, at most maxsplit splits are done (thus, the list will have at most >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168037 elements). If maxsplit is not specified or is >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 341, then there is no limit on the number of splits (all possible splits are made) Jika sep diberikan, pembatas berurutan tidak dikelompokkan bersama dan dianggap membatasi urutan kosong (misalnya, >>> (-2.0).is_integer() True >>> (3.2).is_integer() False27 mengembalikan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False28). Argumen sep dapat terdiri dari urutan multibyte (misalnya, >>> (-2.0).is_integer() True >>> (3.2).is_integer() False29 mengembalikan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False30). Splitting an empty sequence with a specified separator returns >>> (-2.0).is_integer() True >>> (3.2).is_integer() False31 or >>> (-2.0).is_integer() True >>> (3.2).is_integer() False32 depending on the type of object being split. The sep argument may be any For example >>> (65).to_bytes() b'A'9 If sep is not specified or is def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631, a different splitting algorithm is applied. runs of consecutive ASCII whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the sequence has leading or trailing whitespace. Consequently, splitting an empty sequence or a sequence consisting solely of ASCII whitespace without a specified separator returns def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 649 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)_0bytes. strip([karakter] . )bytearray.strip([chars]) Return a copy of the sequence with specified leading and trailing bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631, the chars argument defaults to removing ASCII whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)1 The binary sequence of byte values to remove may be any Note Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan The following methods on bytes and bytearray objects assume the use of ASCII compatible binary formats and should not be applied to arbitrary binary data. Note that all of the bytearray methods in this section do not operate in place, and instead produce new objects bytes. capitalize()bytearray. capitalize()Return a copy of the sequence with each byte interpreted as an ASCII character, and the first byte capitalized and the rest lowercased. Non-ASCII byte values are passed through unchanged Note Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan bytes. perluas tab(ukuran tab=8 . )bytearray.expandtabs(ukuran tab=8)Kembalikan salinan urutan di mana semua karakter tab ASCII diganti dengan satu atau lebih spasi ASCII, bergantung pada kolom saat ini dan ukuran tab yang diberikan. Posisi tab terjadi setiap byte tabsize (default adalah 8, memberikan posisi tab pada kolom 0, 8, 16 dan seterusnya). Untuk memperluas urutan, kolom saat ini diatur ke nol dan urutan diperiksa byte demi byte. Jika byte adalah karakter tab ASCII ( >>> (-2.0).is_integer() True >>> (3.2).is_integer() False36), 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() False37) atau carriage return ( >>> (-2.0).is_integer() True >>> (3.2).is_integer() False38), ini akan disalin dan kolom saat ini disetel ulang ke nol. Nilai byte lainnya disalin tidak berubah dan kolom saat ini bertambah satu terlepas dari bagaimana nilai byte direpresentasikan saat dicetak def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)_2 Note Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan byte. isalnum()bytearray. isalnum()Kembalikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_56 jika semua byte dalam urutan adalah karakter ASCII abjad atau angka desimal ASCII dan urutannya tidak kosong, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 jika tidak. Karakter ASCII alfabetis adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False41. ASCII decimal digits are those byte values in the sequence >>> (-2.0).is_integer() True >>> (3.2).is_integer() False42 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)_3byte. 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') --> 638 jika tidak. Karakter ASCII alfabetis adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False41 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)_4byte. 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') --> 638 sebaliknya. Byte ASCII berada dalam kisaran 0-0x7F New in version 3. 7 byte. isdigit()bytearray. angka()Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if all bytes in the sequence are ASCII decimal digits and the sequence is not empty, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 otherwise. Digit desimal ASCII adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False42 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)_5byte. lebih rendah()bytearray. lebih rendah() Kembalikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_56 jika setidaknya ada satu karakter ASCII huruf kecil dalam urutan dan tidak ada karakter ASCII huruf besar, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 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() False53. Karakter ASCII huruf besar adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False54byte. 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') --> 638 jika tidak. Karakter spasi putih ASCII adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False57 (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') --> 638 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)_7byte. persediaan()bytearray. supper() Kembalikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_56 jika setidaknya ada satu karakter ASCII alfabet huruf besar dalam urutan dan tidak ada karakter ASCII huruf kecil, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 jika tidak For example def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)_8 Karakter ASCII huruf kecil adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False53. Karakter ASCII huruf besar adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False54byte. 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() False53. Karakter ASCII huruf besar adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False54 Note Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan byte. splitlines(keepends=False)bytearray. splitlines(keepends=False)Kembalikan daftar garis dalam urutan biner, putus pada batas garis ASCII. Metode ini menggunakan pendekatan pemisahan garis. Jeda baris tidak disertakan dalam daftar yang dihasilkan kecuali keepends diberikan dan benar For example >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680_0 Unlike when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680_1byte. 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() False53. Karakter ASCII huruf besar adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False54 Tidak seperti , selalu demikian >>> (-2.0).is_integer() True >>> (3.2).is_integer() False71 untuk versi biner. Konversi kasus bersifat simetris dalam ASCII, meskipun hal itu umumnya tidak berlaku untuk poin kode Unicode arbitrer Note Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan byte. judul()bytearray. judul()Mengembalikan versi huruf-huruf dari urutan biner di mana kata-kata dimulai dengan karakter ASCII huruf besar dan karakter yang tersisa adalah huruf kecil. Nilai byte tanpa huruf dibiarkan tidak dimodifikasi For example >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 167116803 Karakter ASCII huruf kecil adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False53. Karakter ASCII huruf besar adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False54. Semua nilai byte lainnya tidak di-uncase The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680_4 Solusi untuk apostrof dapat dibangun menggunakan ekspresi reguler >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680_5 Note Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan byte. atas()bytearray. atas()Kembalikan salinan urutan dengan semua karakter ASCII huruf kecil yang dikonversi ke pasangan huruf besar yang sesuai For example >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680_6 Karakter ASCII huruf kecil adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False53. Karakter ASCII huruf besar adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False54 Note Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan byte. zisi(lebar)bytearray. zisi(lebar)Mengembalikan salinan urutan kiri diisi dengan ASCII >>> (-2.0).is_integer() True >>> (3.2).is_integer() False76 digit untuk membuat urutan panjang lebar. Prefiks tanda depan ( >>> (-2.0).is_integer() True >>> (3.2).is_integer() False77/ >>> (-2.0).is_integer() True >>> (3.2).is_integer() False78) ditangani dengan menyisipkan padding setelah karakter tanda, bukan sebelumnya. Untuk objek, urutan aslinya dikembalikan jika lebarnya kurang dari atau sama dengan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False80 For example >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680_7 Note Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 26-style Bytes FormattingNote Operasi pemformatan yang dijelaskan di sini menunjukkan berbagai keanehan yang menyebabkan sejumlah kesalahan umum (seperti gagal menampilkan tupel dan kamus dengan benar). Jika nilai yang dicetak mungkin berupa tupel atau kamus, bungkus dalam tuple Objek byte ( >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'23/ >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'24) memiliki satu operasi bawaan yang unik. operator >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680_83 (modulo). Ini juga dikenal sebagai pemformatan byte atau operator interpolasi. Diberikan >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680_84 (di mana format adalah objek byte), >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168083 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') 1671168086 dalam bahasa C Jika format memerlukan argumen tunggal, nilai mungkin merupakan objek non-tupel tunggal. Jika tidak, nilai harus berupa tuple dengan jumlah persis item yang ditentukan oleh objek format byte, atau objek pemetaan tunggal (misalnya, kamus) A conversion specifier contains two or more characters and has the following components, which must occur in this order
Ketika argumen yang tepat adalah kamus (atau tipe pemetaan lainnya), maka format dalam objek byte harus menyertakan kunci pemetaan dalam tanda kurung ke dalam kamus yang dimasukkan tepat setelah karakter >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168087. Kunci pemetaan memilih nilai yang akan diformat dari pemetaan. Misalnya >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680_8 In this case no >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'00 specifiers may occur in a format (since they require a sequential parameter list) The conversion flag characters are Flag Meaning >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680_94 The value conversion will use the “alternate form” (where defined below) >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168077 The conversion will be zero padded for numeric values >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168079 The converted value is left adjusted (overrides the >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168077 conversion if both are given) >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168098 (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') 1671168078 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') 1671168078 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') 1671168079) 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 n02, 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 n03, 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 n04) 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 n05 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 n06 The conversion types are Conversion Meaning Catatan def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n07 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 n08 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 n09 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 n10 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 n07 (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 n12 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 n13 Heksadesimal bertanda (huruf besar) (2) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n14 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 n15 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 n16 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 n17 Floating point decimal format (3) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n_18 Format titik mengambang. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise (4) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n19 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 n20 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') --> 6023) (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 n23 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') --> 6022 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 n25 Byte (mengonversi objek Python apa pun menggunakan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6028) (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 n21 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 n25 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') 1671168087 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') 1671168087 character in the result Catatan
Note Versi bytearray dari metode ini tidak beroperasi di tempat - selalu menghasilkan objek baru, meskipun tidak ada perubahan yang dilakukan See also PEP 461 - Menambahkan % pemformatan ke byte dan bytearray New in version 3. 5 Tampilan Memoriobjek memungkinkan kode Python untuk mengakses data internal objek yang mendukung tanpa menyalin kelas memoryview(objek)Buat objek referensi itu. objek harus mendukung protokol buffer. Objek bawaan yang mendukung protokol buffer termasuk dan A memiliki gagasan tentang elemen, yang merupakan unit memori atom yang ditangani oleh objek asal. Untuk banyak tipe sederhana seperti and , sebuah elemen berukuran satu byte, tetapi tipe lain seperti mungkin memiliki elemen yang lebih besar def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_051 sama dengan panjang. Jika def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_053, panjangnya 1. Jika def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_054, panjangnya sama dengan jumlah elemen dalam tampilan. Untuk dimensi yang lebih tinggi, panjangnya sama dengan panjang representasi daftar bersarang dari tampilan. Atribut akan memberi Anda jumlah byte dalam satu elemen A mendukung pemotongan dan pengindeksan untuk mengekspos datanya. Pemotongan satu dimensi akan menghasilkan subview >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680_9 Jika adalah salah satu penentu format asli dari modul, pengindeksan dengan bilangan bulat atau tupel bilangan bulat juga didukung dan mengembalikan satu elemen dengan tipe yang benar. Tampilan memori satu dimensi dapat diindeks dengan integer atau tuple satu integer. Tampilan memori multi-dimensi dapat diindeks dengan tupel bilangan bulat ndim yang tepat di mana ndim adalah jumlah dimensi. Tampilan memori nol dimensi dapat diindeks dengan tuple kosong Berikut adalah contoh dengan format non-byte def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n_0 Jika objek yang mendasarinya dapat ditulisi, tampilan memori mendukung penugasan irisan satu dimensi. Resizing is not allowed def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n1 Tampilan memori satu dimensi dari tipe hashable (read-only) dengan format 'B', 'b' atau 'c' juga hashable. Hash didefinisikan sebagai def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_059 def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n_2 Berubah di versi 3. 3. Tampilan memori satu dimensi sekarang dapat dipotong. Tampilan memori satu dimensi dengan format 'B', 'b' atau 'c' kini dapat di-hash. Berubah di versi 3. 4. memoryview sekarang terdaftar secara otomatis dengan Berubah di versi 3. 5. memoryview sekarang dapat diindeks dengan tuple bilangan bulat. memiliki beberapa metode __eq__(eksportir)Tampilan memori dan pengekspor PEP 3118 sama jika bentuknya sama dan jika semua nilai yang sesuai sama ketika kode format masing-masing operan ditafsirkan menggunakan sintaks Untuk subset string format yang saat ini didukung oleh , def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6065 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') --> 6066 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') --> 6067 def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n_3 Jika salah satu string format tidak didukung oleh modul, maka objek akan selalu dibandingkan sebagai tidak sama (bahkan jika string format dan konten buffer identik) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n_4 Note that, as with floating point numbers, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6069 does not imply def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6070 for memoryview objects Berubah di versi 3. 3. Versi sebelumnya membandingkan memori mentah dengan mengabaikan format item dan struktur array logis. tobyte(pesanan='C')Kembalikan data dalam buffer sebagai bytestring. Ini sama dengan memanggil konstruktor pada tampilan memori def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n_5 Untuk array yang tidak bersebelahan, hasilnya sama dengan representasi daftar yang diratakan dengan semua elemen dikonversi menjadi byte. mendukung semua string format, termasuk yang tidak ada dalam sintaks modul Baru di versi 3. 8. pesanan bisa {‘C’, ‘F’, ‘A’}. Ketika pesanan adalah 'C' atau 'F', data dari larik asli diubah menjadi pesanan C atau Fortran. Untuk tampilan yang berdekatan, 'A' mengembalikan salinan persis dari memori fisik. Secara khusus, urutan Fortran dalam memori dipertahankan. Untuk tampilan yang tidak bersebelahan, data dikonversi ke C terlebih dahulu. order=None sama dengan order=’C’. hex([sep[ , bytes_per_sep]])Mengembalikan objek string yang berisi dua digit heksadesimal untuk setiap byte dalam buffer def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n_6 New in version 3. 5 Changed in version 3. 8. Similar to , now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output. daftar()Return the data in the buffer as a list of elements def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n_7 Berubah di versi 3. 3. sekarang mendukung semua format asli karakter tunggal dalam sintaks modul serta representasi multidimensi. hanya untuk dibaca()Mengembalikan versi readonly dari objek memoryview. Objek memoryview asli tidak berubah def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n_8 Baru di versi 3. 8 rilis()Lepaskan buffer dasar yang diekspos oleh objek memoryview. Banyak objek mengambil tindakan khusus saat tampilan diadakan padanya (misalnya, a akan melarang pengubahan ukuran untuk sementara); Setelah metode ini dipanggil, setiap operasi lebih lanjut pada tampilan akan memunculkan a (kecuali dirinya sendiri yang dapat dipanggil berkali-kali) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n_9 Protokol manajemen konteks dapat digunakan untuk efek serupa, menggunakan pernyataan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6081 >>> (-2.0).is_integer() True >>> (3.2).is_integer() False_0 Baru di versi 3. 2 transmisikan(format[ , shape])Transmisikan tampilan memori ke format atau bentuk baru. bentuk default ke def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_082, yang berarti bahwa tampilan hasil akan menjadi satu dimensi. Nilai yang dikembalikan adalah tampilan memori baru, tetapi buffer itu sendiri tidak disalin. Cast yang didukung adalah 1D -> C- dan C-contiguous -> 1D The destination format is restricted to a single element native format in syntax. Salah satu format harus format byte ('B', 'b' atau 'c'). Panjang byte hasil harus sama dengan panjang aslinya Cast 1D/panjang ke 1D/unsigned byte >>> (-2.0).is_integer() True >>> (3.2).is_integer() False_1 Cast 1D/unsigned byte ke 1D/char >>> (-2.0).is_integer() True >>> (3.2).is_integer() False_2 Cast 1D/bytes ke 3D/ints ke 1D/signed char >>> (-2.0).is_integer() True >>> (3.2).is_integer() False_3 Transmisikan 1D/unsigned long ke 2D/unsigned long >>> (-2.0).is_integer() True >>> (3.2).is_integer() False_4 New in version 3. 3 Berubah di versi 3. 5. Format sumber tidak lagi dibatasi saat mentransmisi ke tampilan byte. Ada juga beberapa atribut readonly yang tersedia objObjek 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. It is not necessarily equal to def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6085 >>> (-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') --> 6088 sekarang ditangani sesuai dengan sintaks modul struct. Ini berarti bahwa def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_089. itemsize Ukuran dalam byte dari setiap elemen tampilan memori >>> (-2.0).is_integer() True >>> (3.2).is_integer() False_8ndim An integer indicating how many dimensions of a multi-dimensional array the memory represents 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') --> 631 saat ndim = 0. langkah Tuple bilangan bulat dengan panjang pemberian ukuran dalam byte untuk mengakses setiap elemen untuk setiap dimensi array Berubah di versi 3. 3. Tuple kosong bukan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631 saat ndim = 0. suboffset Digunakan 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. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. (Untuk container lain lihat built-in , , dan class, dan module. ) Seperti koleksi lainnya, set dukungan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6100, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6101, 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') --> 6102. 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') --> 6106 dan >>> (65).to_bytes() b'A'01. Karena dapat diubah, ia tidak memiliki nilai hash dan tidak dapat digunakan baik sebagai kunci kamus atau sebagai elemen dari kumpulan lain. Jenisnya tidak dapat diubah dan — isinya tidak dapat diubah setelah dibuat; Set yang tidak kosong (bukan set yang dibekukan) dapat dibuat dengan menempatkan daftar elemen yang dipisahkan koma di dalam kurung kurawal, misalnya. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_109, selain konstruktor Konstruktor untuk kedua kelas bekerja sama kelas set([dapat diubah])class frozenset([iterable])Kembalikan set baru atau objek set beku yang elemennya diambil dari iterable. Unsur-unsur suatu himpunan harus. Untuk merepresentasikan himpunan dari himpunan, himpunan bagian dalam harus berupa objek. Jika iterable tidak ditentukan, set kosong baru dikembalikan Set dapat dibuat dengan beberapa cara
Contoh dari dan menyediakan operasi berikut lensa)Mengembalikan jumlah elemen dalam set s (kardinalitas 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 kosongsubset(lainnya)diatur <= other Uji apakah setiap elemen di himpunan ada di yang lain setel < lainnyaUji apakah himpunan tersebut merupakan subhimpunan yang tepat dari yang lain, yaitu, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6120issuperset(other)set >= other Uji apakah setiap elemen lainnya ada di himpunan setel > 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') --> 6121union(*others)set . lainnya . . Kembalikan set baru dengan elemen dari set dan yang lainnya persimpangan(*lainnya)set & other & ...Kembalikan set baru dengan elemen yang umum ke set dan yang lainnya perbedaan(*lainnya)set - other - ...Kembalikan set baru dengan elemen di set yang tidak ada di set lainnya perbedaan_simetris(lainnya)set ^ 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') --> 6128 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') --> 6129 yang lebih mudah dibaca Keduanya dan dukungan diatur untuk mengatur perbandingan. Dua himpunan adalah sama jika dan hanya jika setiap elemen dari setiap himpunan terkandung dalam yang lain (masing-masing merupakan subhimpunan dari yang lain). A set is less than another set if and only if the first set is a proper subset of the second set (is a subset, but is not equal). Himpunan lebih besar dari himpunan lain jika dan hanya jika himpunan pertama adalah superset yang tepat dari himpunan kedua (adalah superset, tetapi tidak sama) Contoh dibandingkan dengan contoh berdasarkan anggotanya. Misalnya, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6134 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') --> 656 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') --> 6136 Perbandingan subset dan kesetaraan tidak digeneralisasikan ke fungsi pengurutan total. Misalnya, dua himpunan disjoint tidak kosong mana pun tidak sama dan bukan subhimpunan satu sama lain, jadi semua hasil berikut def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6138, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6139, 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') --> 6140 Karena set hanya menentukan pengurutan parsial (hubungan subset), output dari metode ini tidak ditentukan untuk daftar set Setel elemen, seperti kunci kamus, harus Operasi biner yang menggabungkan instance dengan mengembalikan tipe operan pertama. Misalnya. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_144 mengembalikan instance dari Tabel berikut mencantumkan operasi yang tersedia untuk yang tidak berlaku untuk instance yang tidak dapat diubah perbarui(*lainnya)set |= lainnya . .Perbarui set, tambahkan elemen dari yang lainnya intersection_update(*lainnya)set &= other & ...Perbarui set, pertahankan hanya elemen yang ditemukan di dalamnya dan yang lainnya difference_update(*lainnya)set -= other | .Perbarui set, hapus elemen yang ditemukan di orang lain symmetric_difference_update(other)set ^= 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() 300, , 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') --> 6163, 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') --> 656) dapat digunakan secara bergantian untuk mengindeks entri kamus yang samakelas 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
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') --> 6173 >>> (-2.0).is_integer() True >>> (3.2).is_integer() False_9 Memberikan argumen kata kunci seperti pada contoh pertama hanya berfungsi untuk kunci yang merupakan pengidentifikasi Python yang valid. Jika tidak, kunci apa pun yang valid dapat digunakan Ini adalah operasi yang didukung kamus (dan oleh karena itu, jenis pemetaan khusus juga harus didukung) daftar(d)Mengembalikan daftar semua kunci yang digunakan dalam kamus d meminjamkan)Mengembalikan jumlah item dalam kamus d d[key]Kembalikan item d dengan key key. Menimbulkan jika kunci tidak ada di peta Jika subkelas dict mendefinisikan metode def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6175 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') --> 6176 memanggil metode itu dengan kunci kunci sebagai argumen. Operasi def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6176 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') --> 6178. 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') --> 6175. 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 olehd[key] = nilai Tetapkan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_176 ke nilai Hapus def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_176 dari d. Menimbulkan jika kunci tidak ada di petakunci di d Kembalikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_56 jika d memiliki kunci kunci, selain itu def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638kunci bukan di d Setara dengan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_191iter(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_192jelas() Hapus semua item dari kamus salin()Kembalikan salinan kamus yang dangkal classmethod fromkeys(dapat diubah[, value])Buat kamus baru dengan kunci dari iterable dan nilai disetel ke nilai adalah metode kelas yang mengembalikan kamus baru. nilai default ke def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_31. Semua nilai merujuk hanya pada satu contoh, jadi umumnya tidak masuk akal jika nilai menjadi objek yang dapat diubah seperti daftar kosong. Untuk mendapatkan nilai yang berbeda, gunakan a sebagai gantinyadapatkan(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') --> 631, sehingga metode ini tidak pernah memunculkanitem() 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') --> 6197 pasang). Lihatkunci() Kembalikan tampilan baru dari kunci kamus. Lihat pop(key[ , default])Jika kunci ada di kamus, hapus dan kembalikan nilainya, jika tidak, kembalikan default. Jika default tidak diberikan dan kunci tidak ada dalam kamus, a dimunculkan popitem()Hapus dan kembalikan pasangan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_197 dari kamus. Pasangan dikembalikan dalam urutan LIFO berguna untuk mengulang kamus secara destruktif, seperti yang sering digunakan dalam algoritme set. Jika kamus kosong, pemanggilan memunculkan a Berubah di versi 3. 7. Pesanan LIFO sekarang dijamin. Di versi sebelumnya, akan mengembalikan pasangan kunci/nilai arbitrer. terbalik(d)Kembalikan iterator terbalik di atas kunci kamus. Ini adalah jalan pintas untuk def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_204 Baru di versi 3. 8 setdefault(kunci[ , default])Jika kunci ada di kamus, kembalikan nilainya. Jika tidak, masukkan kunci dengan nilai default dan kembalikan default. default default ke def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_31perbarui([lainnya]) Perbarui kamus dengan pasangan kunci/nilai dari yang lain, menimpa kunci yang sudah ada. Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631 menerima objek kamus lain atau iterable dari pasangan kunci/nilai (sebagai tupel atau iterable lainnya dengan panjang dua). Jika argumen kata kunci ditentukan, kamus kemudian diperbarui dengan pasangan kunci/nilai tersebut. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_208nilai() 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') --> 6209 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') --> 638. 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_01d . lainnya Buat kamus baru dengan gabungan kunci dan nilai d dan lainnya, yang keduanya harus berupa kamus. Nilai-nilai lain diprioritaskan ketika d dan kunci berbagi lainnya New in version 3. 9 d . = 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') --> 6197 pairs (regardless of ordering). Order comparisons (‘<’, ‘<=’, ‘>=’, ‘>’) raise . Dictionaries preserve insertion order. Perhatikan bahwa memperbarui kunci tidak memengaruhi urutan. Kunci yang ditambahkan setelah penghapusan dimasukkan di bagian akhir def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_02 Berubah di versi 3. 7. Urutan kamus dijamin menjadi urutan penyisipan. Perilaku ini merupakan detail implementasi CPython dari 3. 6. Tampilan kamus dan kamus dapat dibalik def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_03 Berubah di versi 3. 8. Kamus sekarang dapat dibalik. See also dapat digunakan untuk membuat tampilan read-only dari a Objek tampilan kamusObjek yang dikembalikan oleh , dan adalah objek tampilan. Mereka memberikan tampilan dinamis pada entri kamus, yang berarti bahwa saat kamus berubah, tampilan mencerminkan perubahan ini Tampilan kamus dapat diulangi untuk menghasilkan datanya masing-masing, dan mendukung pengujian keanggotaan len(tampilan dikt)Kembalikan jumlah entri dalam kamus iter(dictview)Return an iterator over the keys, values or items (represented as tuples of def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6197) in the dictionary Kunci dan nilai diulang dalam urutan penyisipan. Ini memungkinkan pembuatan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_220 pasang menggunakan. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_222. Cara lain untuk membuat daftar yang sama adalah def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6223 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 tupel def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6197)terbalik (dictview) Mengembalikan iterator terbalik di atas kunci, nilai, atau item kamus. Tampilan akan diulang dalam urutan terbalik dari penyisipan Berubah di versi 3. 8. Dictionary views are now reversible. dictview. pemetaanKembalikan a yang membungkus kamus asli yang dirujuk oleh tampilan Baru di versi 3. 10 Tampilan kunci seperti set karena entri mereka unik dan dapat di-hash. Jika semua nilai dapat di-hash, sehingga def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_197 pasangan unik dan dapat di-hash, maka tampilan item juga seperti set. (Tampilan nilai tidak diperlakukan sebagai set-like karena entri umumnya tidak unik. ) Untuk tampilan set-like, semua operasi yang ditentukan untuk kelas dasar abstrak tersedia (misalnya, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 678, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 674, 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') --> 6232) Contoh penggunaan tampilan kamus def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_04 Jenis Manajer KonteksPernyataan Python mendukung konsep konteks runtime yang ditentukan oleh pengelola konteks. Ini diimplementasikan menggunakan sepasang metode yang memungkinkan kelas yang ditentukan pengguna untuk menentukan konteks runtime yang dimasukkan sebelum badan pernyataan dieksekusi dan keluar saat pernyataan berakhir pengelola konteks. __masuk__()Masukkan konteks runtime dan kembalikan objek ini atau objek lain yang terkait dengan konteks runtime. Nilai yang dikembalikan oleh metode ini terikat pada pengidentifikasi dalam klausa def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6234 menggunakan manajer konteks ini Contoh manajer konteks yang mengembalikan dirinya sendiri adalah a. Objek file mengembalikan dirinya sendiri dari __enter__() agar dapat digunakan sebagai ekspresi konteks dalam pernyataan An example of a context manager that returns a related object is the one returned by . These managers set the active decimal context to a copy of the original decimal context and then return the copy. Ini memungkinkan perubahan dilakukan pada konteks desimal saat ini di badan pernyataan tanpa memengaruhi kode di luar pernyataan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6081pengelola 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') --> 631 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') --> 6081. Kalau tidak, pengecualian terus menyebar setelah metode ini selesai dieksekusi. Pengecualian yang terjadi selama eksekusi metode ini akan menggantikan setiap pengecualian yang terjadi di badan pernyataan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6081 Pengecualian yang diteruskan tidak boleh dimunculkan kembali secara eksplisit - sebagai gantinya, metode ini harus mengembalikan nilai salah untuk menunjukkan bahwa metode berhasil diselesaikan dan tidak ingin menekan pengecualian yang dimunculkan. Ini memungkinkan kode manajemen konteks untuk dengan mudah mendeteksi apakah suatu metode benar-benar gagal atau tidak Python mendefinisikan beberapa manajer konteks untuk mendukung sinkronisasi utas yang mudah, penutupan cepat file atau objek lain, dan manipulasi yang lebih sederhana dari konteks aritmatika desimal aktif. Jenis spesifik tidak diperlakukan secara khusus di luar penerapan protokol manajemen konteksnya. Lihat modul untuk beberapa contoh Python dan dekorator menyediakan cara mudah untuk mengimplementasikan protokol ini. Jika fungsi generator didekorasi dengan dekorator, itu akan mengembalikan manajer konteks yang mengimplementasikan metode yang diperlukan dan, daripada iterator yang dihasilkan oleh fungsi generator yang tidak didekorasi Perhatikan bahwa tidak ada slot khusus untuk salah satu metode ini dalam struktur tipe untuk objek Python di Python/C API. Jenis ekstensi yang ingin mendefinisikan metode ini harus menyediakannya sebagai metode normal yang dapat diakses Python. Dibandingkan dengan biaya tambahan untuk menyiapkan konteks runtime, biaya tambahan dari pencarian kamus kelas tunggal dapat diabaikan Ketik Jenis Anotasi — ,The core built-in types for are and Tipe Alias Generikdef bit_length(self): 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') --> 6252 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
def bit_length(self): 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') --> 6252 secara langsungT[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') --> 6289 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') --> 6289 yang digunakan. For example, a function expecting a containing elements def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_05 Contoh lain untuk objek, menggunakan a , yang merupakan tipe generik yang mengharapkan dua parameter tipe yang mewakili tipe kunci dan tipe nilai. Dalam contoh ini, fungsi mengharapkan >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'68 dengan kunci tipe dan nilai tipe def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_06 Fungsi bawaan dan tidak menerima tipe def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6252 untuk argumen kedua mereka def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_07 Runtime Python tidak berlaku. Ini meluas ke tipe generik dan parameter tipenya. Saat membuat objek wadah dari def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_252, elemen dalam wadah tidak dicentang berdasarkan jenisnya. Misalnya, kode berikut tidak dianjurkan, tetapi akan berjalan tanpa kesalahan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_08 Selanjutnya, parameter generik menghapus parameter tipe selama pembuatan objek def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_09 Memanggil atau pada generik menunjukkan tipe parameter def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_10 Metode wadah umum akan memunculkan pengecualian untuk melarang kesalahan seperti def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6304 def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6_11 However, such expressions are valid when are used. Indeks harus memiliki elemen sebanyak item variabel tipe dalam objek def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6252 def bit_length(self): 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 StandarKelas pustaka standar berikut mendukung generik berparameter. Daftar ini tidak lengkap Atribut Khusus dari |