Tipe data dari array; . mengambang. Untuk data input biner, data harus persis dalam format ini
menghitung. int, opsional
Baca jumlah elemen ini dari data. Jika ini negatif (default), hitungan akan ditentukan dari panjang data
September. str, opsional
Jika tidak diberikan atau, dengan kata lain, string kosong, data akan diinterpretasikan sebagai data biner; . Juga dalam kasus terakhir ini, argumen ini ditafsirkan sebagai string yang memisahkan angka dalam data;
Beberapa kelas koleksi bisa berubah. Metode yang menambah, mengurangi, atau mengatur ulang anggotanya pada tempatnya, dan tidak mengembalikan item tertentu, tidak pernah mengembalikan instance koleksi itu sendiri tetapi def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31
Beberapa operasi didukung oleh beberapa tipe objek; . Fungsi yang terakhir secara implisit digunakan ketika sebuah objek ditulis oleh fungsi tersebut
Pengujian Nilai Kebenaran
Objek apa pun dapat diuji untuk nilai kebenaran, untuk digunakan dalam kondisi atau atau sebagai operan dari operasi Boolean di bawah ini
Secara default, sebuah objek dianggap benar kecuali kelasnya mendefinisikan metode def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 37 yang mengembalikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 atau metode def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 39 yang mengembalikan nol, saat dipanggil dengan objek. Berikut adalah sebagian besar objek bawaan yang dianggap salah
konstanta yang didefinisikan sebagai salah. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31 and def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38
zero of any numeric type. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 42, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 43, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 44, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 45, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 46
empty sequences and collections. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 47, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 48, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 49, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 50, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 51, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 52
Operations and built-in functions that have a Boolean result always return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 42 or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 for false and def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 55 or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56 for true, unless otherwise stated. (Important exception. the Boolean operations def bit_length(self): 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 and def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 58 always return one of their operands. )
Boolean Operations — def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 58, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 57, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 61
These are the Boolean operations, ordered by ascending priority
Operation
Result
Notes
def bit_length(self): 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
if x is false, then y, else 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
if x is false, then x, else 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
if x is false, then def bit_length(self): 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, else def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38
(3)
Notes
This is a short-circuit operator, so it only evaluates the second argument if the first one is false
This is a short-circuit operator, so it only evaluates the second argument if the first one is true
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 61 has a lower priority than non-Boolean operators, so def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 68 is interpreted as def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 69, and def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 70 is a syntax error
Comparisons
There are eight comparison operations in Python. They all have the same priority (which is higher than that of the Boolean operations). Comparisons can be chained arbitrarily; for example, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 71 is equivalent to def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 72, except that y is evaluated only once (but in both cases z is not evaluated at all when def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 73 is found to be false)
This table summarizes the comparison operations
Operation
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
strictly less than
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 75
less than or equal
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 76
strictly greater than
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 77
greater than or equal
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 78
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 79
not equal
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 80
object identity
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 81
negated object identity
Objects of different types, except different numeric types, never compare equal. The def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 78 operator is always defined but for some object types (for example, class objects) is equivalent to . The def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 74, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 75, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 76 and def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 77 operators are only defined where they make sense; for example, they raise a exception when one of the arguments is a complex number
Non-identical instances of a class normally compare as non-equal unless the class defines the method
Instances of a class cannot be ordered with respect to other instances of the same class, or other types of object, unless the class defines enough of the methods , , , and (in general, and are sufficient, if you want the conventional meanings of the comparison operators)
The behavior of the and operators cannot be customized; also they can be applied to any two objects and never raise an exception
Two more operations with the same syntactic priority, and , are supported by types that are or implement the >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 00 method
Numeric Types — , ,
There are three distinct numeric types. bilangan bulat, bilangan floating point, dan bilangan kompleks. In addition, Booleans are a subtype of integers. Integers have unlimited precision. Angka floating point biasanya diimplementasikan menggunakan double di C; . Bilangan kompleks memiliki bagian nyata dan imajiner, yang masing-masing merupakan bilangan floating point. To extract these parts from a complex number z, use >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 05 and >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 06. (The standard library includes the additional numeric types , for rationals, and , for floating-point numbers with user-definable precision. )
Numbers are created by numeric literals or as the result of built-in functions and operators. Literal bilangan bulat tanpa hiasan (termasuk bilangan hex, oktal, dan biner) menghasilkan bilangan bulat. Literal numerik yang mengandung titik desimal atau tanda eksponen menghasilkan angka floating point. Menambahkan >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 09 atau >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 10 ke literal numerik menghasilkan bilangan imajiner (bilangan kompleks dengan bagian nyata nol) yang dapat Anda tambahkan ke bilangan bulat atau float untuk mendapatkan bilangan kompleks dengan bagian nyata dan imajiner
Python sepenuhnya mendukung aritmatika campuran. ketika operator aritmatika biner memiliki operan dari tipe numerik yang berbeda, operan dengan tipe "sempit" diperlebar ke yang lain, di mana bilangan bulat lebih sempit dari floating point, yang lebih sempit dari kompleks. Perbandingan antara angka-angka dari jenis yang berbeda berlaku seolah-olah nilai pasti dari angka-angka itu sedang dibandingkan.
Konstruktor , , dan dapat digunakan untuk menghasilkan angka dengan tipe tertentu
Semua tipe numerik (kecuali kompleks) mendukung operasi berikut (untuk prioritas operasi, lihat )
Operation
Result
Notes
Dokumentasi lengkap
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 14
jumlah x dan y
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 15
selisih x dan y
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 16
produk dari x dan y
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 17
quotient of x and y
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 18
floored quotient of x and y
(1)
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 19
remainder of >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 17
(2)
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 21
x negated
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 22
x unchanged
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 23
absolute value or magnitude of x
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 25
x converted to integer
(3)(6)
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 27
x converted to floating point
(4)(6)
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 29
a complex number with real part re, imaginary part im. im defaults to zero
(6)
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 31
conjugate of the complex number c
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 32
the pair >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 33
(2)
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 35
x to the power y
(5)
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 37
x to the power y
(5)
Notes
Also referred to as integer division. The resultant value is a whole integer, though the result’s type is not necessarily int. The result is always rounded towards minus infinity. >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 38 is def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 42, >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 40 is >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 41, >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 42 is >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 41, and >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 44 is def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 42
Not for complex numbers. Instead convert to floats using if appropriate
Conversion from floating point to integer may round or truncate as in C; see functions and for well-defined conversions
float also accepts the strings “nan” and “inf” with an optional prefix “+” or “-” for Not a Number (NaN) and positive or negative infinity
Python defines >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 49 and >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 50 to be def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 55, as is common for programming languages
The numeric literals accepted include the digits def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 42 to >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 53 or any Unicode equivalent (code points with the >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 54 property)
See https. //www. unicode. org/Public/14. 0. 0/ucd/extracted/DerivedNumericType. txt for a complete list of code points with the >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 54 property
All types ( and ) also include the following operations
Operation
Result
x truncated to
x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0
the greatest = x
For additional numeric operations see the and modules
Bitwise Operations on Integer Types
Bitwise operations only make sense for integers. The result of bitwise operations is calculated as though carried out in two’s complement with an infinite number of sign bits
The priorities of the binary bitwise operations are all lower than the numeric operations and higher than the comparisons; the unary operation >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 68 has the same priority as the other unary numeric operations (>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 69 and >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 70)
This table lists the bitwise operations sorted in ascending priority
Operation
Result
Notes
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 71
bitwise or of x and y
(4)
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 72
bitwise exclusive or of x and y
(4)
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 73
bitwise and of x and y
(4)
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 74
x shifted left by n bits
(1)(2)
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 75
x shifted right by n bits
(1)(3)
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 76
the bits of x inverted
Notes
Negative shift counts are illegal and cause a to be raised
A left shift by n bits is equivalent to multiplication by >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 78
A right shift by n bits is equivalent to floor division by >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 78
Performing these calculations with at least one extra sign extension bit in a finite two’s complement representation (a working bit-width of >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 80 or more) is sufficient to get the same result as if there were an infinite number of sign bits
Additional Methods on Integer Types
The int type implements the . In addition, it provides a few more methods
int. bit_length()Return the number of bits necessary to represent an integer in binary, excluding the sign and leading zeros
>>> n = -37 >>> bin(n) '-0b100101' >>> n.bit_length() 6
Lebih tepatnya, jika >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 82 bukan nol, maka >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 83 adalah bilangan bulat positif unik >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 84 sehingga >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 85. Equivalently, when >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 23 is small enough to have a correctly rounded logarithm, then >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 87. If >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 82 is zero, then >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 83 returns def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 42
Equivalent to
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6
New in version 3. 1
int. bit_count()Return the number of ones in the binary representation of the absolute value of the integer. This is also known as the population count. Example
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3
Equivalent to
def bit_count(self): return bin(self).count("1")
New in version 3. 10
int. to_bytes(length=1 , byteorder='big' , * , signed=False)Return an array of bytes representing an integer
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'
The integer is represented using length bytes, and defaults to 1. An dimunculkan jika bilangan bulat tidak dapat diwakili dengan jumlah byte yang diberikan
The byteorder argument determines the byte order used to represent the integer, and defaults to >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 92. If byteorder is >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 92, the most significant byte is at the beginning of the byte array. 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. If signed is def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 and a negative integer is given, an is raised. The default value for signed is def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38
The default values can be used to conveniently turn an integer into a single byte object. However, when using the default arguments, don’t try to convert a value greater than 255 or you’ll get an
>>> (65).to_bytes() b'A'
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)
New in version 3. 2
Changed in version 3. 11. Added default argument values for >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 99 and def bit_count(self): return bin(self).count("1") 00.
classmethod int. from_bytes(bytes , byteorder='big' , * , signed=False)Return the integer represented by the given array of bytes
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680
The argument bytes must either be a or an iterable producing bytes
The byteorder argument determines the byte order used to represent the integer, and defaults to >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 92. If byteorder is >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 92, the most significant byte is at the beginning of the byte array. If byteorder is >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 94, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use as the byte order value
The signed argument indicates whether two’s complement is used to represent the integer
Equivalent to
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n
New in version 3. 2
Changed in version 3. 11. Added default argument value for def bit_count(self): return bin(self).count("1") 00.
int. as_integer_ratio()Return a pair of integers whose ratio is exactly equal to the original integer and with a positive denominator. The integer ratio of integers (whole numbers) is always the integer as the numerator and def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 55 as the denominator
New in version 3. 8
Metode Tambahan di Float
The float type implements the . float also has the following additional methods
float. as_integer_ratio()Return a pair of integers whose ratio is exactly equal to the original float and with a positive denominator. Raises on infinities and a on NaNs
float. is_integer()Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56 if the float instance is finite with integral value, and def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 otherwise
>>> (-2.0).is_integer() True >>> (3.2).is_integer() False
Two methods support conversion to and from hexadecimal strings. Since Python’s floats are stored internally as binary numbers, converting a float to or from a decimal string usually involves a small rounding error. In contrast, hexadecimal strings allow exact representation and specification of floating-point numbers. This can be useful when debugging, and in numerical work
float. hex()Return a representation of a floating-point number as a hexadecimal string. For finite floating-point numbers, this representation will always include a leading def bit_count(self): return bin(self).count("1") 12 and a trailing def bit_count(self): return bin(self).count("1") 13 and exponent
classmethod float. fromhex(s)Class method to return the float represented by a hexadecimal string s. The string s may have leading and trailing whitespace
Note that is an instance method, while is a class method
A hexadecimal string takes the form
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 0
where the optional def bit_count(self): return bin(self).count("1") 16 may by either >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 69 or >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 70, def bit_count(self): return bin(self).count("1") 19 and def bit_count(self): return bin(self).count("1") 20 are strings of hexadecimal digits, and def bit_count(self): return bin(self).count("1") 21 is a decimal integer with an optional leading sign. Case is not significant, and there must be at least one hexadecimal digit in either the integer or the fraction. This syntax is similar to the syntax specified in section 6. 4. 4. 2 of the C99 standard, and also to the syntax used in Java 1. 5 onwards. In particular, the output of is usable as a hexadecimal floating-point literal in C or Java code, and hexadecimal strings produced by C’s def bit_count(self): return bin(self).count("1") 23 format character or Java’s def bit_count(self): return bin(self).count("1") 24 are accepted by
Note that the exponent is written in decimal rather than hexadecimal, and that it gives the power of 2 by which to multiply the coefficient. For example, the hexadecimal string def bit_count(self): return bin(self).count("1") 26 represents the floating-point number def bit_count(self): return bin(self).count("1") 27, or def bit_count(self): return bin(self).count("1") 28
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 1
Applying the reverse conversion to def bit_count(self): return bin(self).count("1") 28 gives a different hexadecimal string representing the same number
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 2
Hashing of numeric types
For numbers >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 82 and def bit_count(self): return bin(self).count("1") 31, possibly of different types, it’s a requirement that def bit_count(self): return bin(self).count("1") 32 whenever def bit_count(self): return bin(self).count("1") 33 (see the method documentation for more details). For ease of implementation and efficiency across a variety of numeric types (including , , and ) Python’s hash for numeric types is based on a single mathematical function that’s defined for any rational number, and hence applies to all instances of and , and all finite instances of and . Essentially, this function is given by reduction modulo def bit_count(self): return bin(self).count("1") 43 for a fixed prime def bit_count(self): return bin(self).count("1") 43. The value of def bit_count(self): return bin(self).count("1") 43 is made available to Python as the def bit_count(self): return bin(self).count("1") 46 attribute of
CPython implementation detail. Currently, the prime used is def bit_count(self): return bin(self).count("1") 48 on machines with 32-bit C longs and def bit_count(self): return bin(self).count("1") 49 on machines with 64-bit C longs
Here are the rules in detail
If def bit_count(self): return bin(self).count("1") 50 is a nonnegative rational number and def bit_count(self): return bin(self).count("1") 51 is not divisible by def bit_count(self): return bin(self).count("1") 43, define def bit_count(self): return bin(self).count("1") 53 as def bit_count(self): return bin(self).count("1") 54, where def bit_count(self): return bin(self).count("1") 55 gives the inverse of def bit_count(self): return bin(self).count("1") 51 modulo def bit_count(self): return bin(self).count("1") 43
If def bit_count(self): return bin(self).count("1") 50 is a nonnegative rational number and def bit_count(self): return bin(self).count("1") 51 is divisible by def bit_count(self): return bin(self).count("1") 43 (but def bit_count(self): return bin(self).count("1") 61 is not) then def bit_count(self): return bin(self).count("1") 51 has no inverse modulo def bit_count(self): return bin(self).count("1") 43 and the rule above doesn’t apply; in this case define def bit_count(self): return bin(self).count("1") 53 to be the constant value def bit_count(self): return bin(self).count("1") 65
If def bit_count(self): return bin(self).count("1") 50 is a negative rational number define def bit_count(self): return bin(self).count("1") 53 as def bit_count(self): return bin(self).count("1") 68. If the resulting hash is >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 41, replace it with def bit_count(self): return bin(self).count("1") 70
The particular values def bit_count(self): return bin(self).count("1") 65 and def bit_count(self): return bin(self).count("1") 72 are used as hash values for positive infinity or negative infinity (respectively)
For a number def bit_count(self): return bin(self).count("1") 74, the hash values of the real and imaginary parts are combined by computing def bit_count(self): return bin(self).count("1") 75, reduced modulo def bit_count(self): return bin(self).count("1") 76 so that it lies in def bit_count(self): return bin(self).count("1") 77. Again, if the result is >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 41, it’s replaced with def bit_count(self): return bin(self).count("1") 70
To clarify the above rules, here’s some example Python code, equivalent to the built-in hash, for computing the hash of a rational number, , or
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 3
Iterator Types
Python supports a concept of iteration over containers. Ini diimplementasikan menggunakan dua metode berbeda; . Sequences, described below in more detail, always support the iteration methods
One method needs to be defined for container objects to provide support
container. __iter__()Return an object. The object is required to support the iterator protocol described below. If a container supports different types of iteration, additional methods can be provided to specifically request iterators for those iteration types. (An example of an object supporting multiple forms of iteration would be a tree structure which supports both breadth-first and depth-first traversal. ) This method corresponds to the slot of the type structure for Python objects in the Python/C API
The iterator objects themselves are required to support the following two methods, which together form the iterator protocol
iterator. __iter__()Return the object itself. This is required to allow both containers and iterators to be used with the and statements. This method corresponds to the slot of the type structure for Python objects in the Python/C API
iterator. __next__()Return the next item from the . If there are no further items, raise the exception. This method corresponds to the slot of the type structure for Python objects in the Python/C API
Python defines several iterator objects to support iteration over general and specific sequence types, dictionaries, and other more specialized forms. Jenis spesifik tidak penting di luar penerapan protokol iterator
Once an iterator’s method raises , it must continue to do so on subsequent calls. Implementations that do not obey this property are deemed broken
Generator Types
Python’s s provide a convenient way to implement the iterator protocol. If a container object’s def bit_count(self): return bin(self).count("1") 90 method is implemented as a generator, it will automatically return an iterator object (technically, a generator object) supplying the def bit_count(self): return bin(self).count("1") 90 and methods. More information about generators can be found in
Sequence Types — , ,
There are three basic sequence types. lists, tuples, and range objects. Additional sequence types tailored for processing of and are described in dedicated sections
Common Sequence Operations
The operations in the following table are supported by most sequence types, both mutable and immutable. ABC disediakan untuk mempermudah penerapan operasi ini dengan benar pada tipe urutan kustom
Tabel ini mencantumkan operasi urutan yang diurutkan dalam prioritas menaik. Dalam tabel, s dan t adalah urutan dari tipe yang sama, n, i, j dan k adalah bilangan bulat dan x adalah objek arbitrer yang memenuhi batasan tipe dan nilai apa pun yang diberlakukan oleh s
Operasi def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 98 dan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 99 memiliki prioritas yang sama dengan operasi pembanding. Operasi >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 _69 (penggabungan) dan >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 00 (pengulangan) memiliki prioritas yang sama dengan operasi numerik yang sesuai.
Operation
Result
Notes
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' _01
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56 jika item s sama dengan x, jika tidak def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38
(1)
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' _04
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 jika item s sama dengan x, jika tidak def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56
(1)
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' _07
gabungan dari s dan t
(6)(7)
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' _08 atau >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 09
setara dengan menambahkan s ke dirinya sendiri sebanyak n kali
(2)(7)
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' _10
item ke-i dari s, asal 0
(3)
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' _11
potongan s dari i ke j
(3)(4)
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' _12
slice of s from i to j with step k
(3)(5)
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' _13
length of s
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 14
smallest item of s
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 15
largest item of s
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 16
index of the first occurrence of x in s (at or after index i and before index j)
(8)
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 17
total number of occurrences of x in s
Sequences of the same type also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length. (For full details see in the language reference. )
Forward and reversed iterators over mutable sequences access values using an index. That index will continue to march forward (or backward) even if the underlying sequence is mutated. The iterator terminates only when an or a is encountered (or when the index drops below zero)
Notes
While the def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 98 and def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 99 operations are used only for simple containment testing in the general case, some specialised sequences (such as , and ) also use them for subsequence testing
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 4
Values of n less than def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 42 are treated as def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 42 (which yields an empty sequence of the same type as s). Note that items in the sequence s are not copied; they are referenced multiple times. This often haunts new Python programmers; consider
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 5
What has happened is that >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 27 is a one-element list containing an empty list, so all three elements of >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 28 are references to this single empty list. Modifying any of the elements of >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 29 modifies this single list. You can create a list of different lists this way
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 6
Further explanation is available in the FAQ entry
If i or j is negative, the index is relative to the end of sequence s. >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 30 or >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 31 is substituted. But note that >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 32 is still def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 42
The slice of s from i to j is defined as the sequence of items with index k such that >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 34. If i or j is greater than >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 13, use >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 13. If i is omitted or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31, use def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 42. If j is omitted or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31, use >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 13. If i is greater than or equal to j, the slice is empty
The slice of s from i to j with step k is defined as the sequence of items with index >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 41 such that >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 42. In other words, the indices are >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 43, >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 44, >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 45, >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 46 and so on, stopping when j is reached (but never including j). When k is positive, i and j are reduced to >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 13 if they are greater. When k is negative, i and j are reduced to >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 48 if they are greater. If i or j are omitted or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31, they become “end” values (which end depends on the sign of k). Note, k cannot be zero. If k is def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31, it is treated like def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 55
Concatenating immutable sequences always results in a new object. This means that building up a sequence by repeated concatenation will have a quadratic runtime cost in the total sequence length. To get a linear runtime cost, you must switch to one of the alternatives below
if concatenating objects, you can build a list and use at the end or else write to an instance and retrieve its value when complete
if concatenating objects, you can similarly use or , or you can do in-place concatenation with a object. objects are mutable and have an efficient overallocation mechanism
if concatenating objects, extend a instead
for other types, investigate the relevant class documentation
Some sequence types (such as ) only support item sequences that follow specific patterns, and hence don’t support sequence concatenation or repetition
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 63 raises when x is not found in s. Not all implementations support passing the additional arguments i and j. These arguments allow efficient searching of subsections of the sequence. Passing the extra arguments is roughly equivalent to using >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 65, only without copying any data and with the returned index being relative to the start of the sequence rather than the start of the slice
Jenis Urutan yang Tidak Dapat Diubah
The only operation that immutable sequence types generally implement that is not also implemented by mutable sequence types is support for the built-in
This support allows immutable sequences, such as instances, to be used as keys and stored in and instances
Attempting to hash an immutable sequence that contains unhashable values will result in
Mutable Sequence Types
The operations in the following table are defined on mutable sequence types. The ABC is provided to make it easier to correctly implement these operations on custom sequence types
In the table s is an instance of a mutable sequence type, t is any iterable object and x is an arbitrary object that meets any type and value restrictions imposed by s (for example, only accepts integers that meet the value restriction >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 74)
Operation
Result
Notes
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 75
item i of s is replaced by x
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 76
slice of s from i to j is replaced by the contents of the iterable t
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 77
same as >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 78
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 79
the elements of >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 12 are replaced by those of t
(1)
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 81
removes the elements of >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 12 from the list
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 83
appends x to the end of the sequence (same as >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 84)
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 85
removes all items from s (same as >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 86)
(5)
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 87
membuat salinan s yang dangkal (sama seperti >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 88)
(5)
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 89 or >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 90
extends s with the contents of t (for the most part the same as >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 91)
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 92
updates s with its contents repeated n times
(6)
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 93
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
hapus item pertama dari s di mana >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 10 sama dengan x
(3)
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 99
membalikkan item s di tempat
(4)
Notes
t harus memiliki panjang yang sama dengan irisan yang diganti
Argumen opsional saya default ke >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 41, sehingga secara default item terakhir dihapus dan dikembalikan
>>> (65).to_bytes() b'A' _01 muncul ketika x tidak ditemukan di s
Metode >>> (65).to_bytes() b'A' _03 memodifikasi urutan di tempat untuk penghematan ruang saat membalikkan urutan besar. Untuk mengingatkan pengguna bahwa itu beroperasi dengan efek samping, itu tidak mengembalikan urutan terbalik
>>> (65).to_bytes() b'A' _04 dan >>> (65).to_bytes() b'A' 05 disertakan untuk konsistensi dengan antarmuka wadah yang dapat berubah yang tidak mendukung operasi pemotongan (seperti dan ). >>> (65).to_bytes() b'A' _05 bukan bagian dari ABC, tetapi sebagian besar kelas urutan konkrit yang dapat diubah menyediakannya
Baru di versi 3. 3. >>> (65).to_bytes() b'A' 04 dan >>> (65).to_bytes() b'A' 05 metode.
Nilai n adalah bilangan bulat, atau implementasi objek. Nilai nol dan negatif dari n menghapus urutan. Item dalam urutan tidak disalin;
Daftar
Daftar adalah urutan yang dapat diubah, biasanya digunakan untuk menyimpan koleksi item yang homogen (di mana tingkat kesamaan yang tepat akan bervariasi berdasarkan aplikasi)
kelas daftar([dapat diubah])Daftar dapat dibangun dalam beberapa cara
Menggunakan sepasang tanda kurung siku untuk menunjukkan daftar kosong. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _49
Using square brackets, separating items with commas. >>> (65).to_bytes() b'A' _15, >>> (65).to_bytes() b'A' 16
Menggunakan pemahaman daftar. >>> (65).to_bytes() b'A' _17
Menggunakan konstruktor tipe. >>> (65).to_bytes() b'A' _18 atau >>> (65).to_bytes() b'A' 19
Konstruktor membuat daftar yang itemnya sama dan dalam urutan yang sama dengan item iterable. iterable dapat berupa urutan, wadah yang mendukung iterasi, atau objek iterator. Jika iterable sudah menjadi daftar, salinan dibuat dan dikembalikan, mirip dengan >>> (65).to_bytes() b'A' 20. Misalnya, >>> (65).to_bytes() b'A' _21 mengembalikan >>> (65).to_bytes() b'A' 22 dan >>> (65).to_bytes() b'A' 23 mengembalikan >>> (65).to_bytes() b'A' 24. Jika tidak ada argumen yang diberikan, konstruktor membuat daftar kosong baru, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 49
Banyak operasi lain juga menghasilkan daftar, termasuk bawaan
Daftar mengimplementasikan semua operasi urutan dan. Daftar juga menyediakan metode tambahan berikut
urutkan(* , kunci=None, reverse=False)Metode ini mengurutkan daftar di tempat, hanya 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 74 perbandingan antar item. Pengecualian tidak ditekan - jika ada operasi pembandingan yang gagal, seluruh operasi pengurutan akan gagal (dan daftar kemungkinan akan ditinggalkan dalam keadaan dimodifikasi sebagian)
menerima dua argumen yang hanya bisa dilewatkan oleh kata kunci ()
kunci menentukan fungsi dari satu argumen yang digunakan untuk mengekstrak kunci perbandingan dari setiap elemen daftar (misalnya, >>> (65).to_bytes() b'A' 29). Kunci yang sesuai dengan setiap item dalam daftar dihitung satu kali dan kemudian digunakan untuk keseluruhan proses penyortiran. Nilai default def bit_length(self): 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 berarti item daftar diurutkan secara langsung tanpa menghitung nilai kunci terpisah
Utilitas tersedia untuk mengonversi 2. fungsi x gaya cmp ke fungsi tombol
terbalik adalah nilai boolean. Jika diatur 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 _56, maka elemen daftar diurutkan seolah-olah setiap perbandingan dibalik
Metode ini memodifikasi urutan di tempat untuk penghematan ruang saat menyortir urutan besar. Untuk mengingatkan pengguna bahwa itu beroperasi dengan efek samping, itu tidak mengembalikan urutan yang diurutkan (gunakan untuk secara eksplisit meminta contoh daftar yang diurutkan baru)
Metode ini dijamin stabil. Pengurutan stabil jika menjamin untuk tidak mengubah urutan relatif elemen yang sebanding — ini berguna untuk menyortir dalam beberapa lintasan (misalnya, mengurutkan berdasarkan departemen, kemudian berdasarkan tingkat gaji)
Untuk contoh penyortiran dan tutorial penyortiran singkat, lihat
Detail implementasi CPython. Saat daftar sedang diurutkan, efek dari mencoba mengubah, atau bahkan memeriksa, daftar tidak ditentukan. Implementasi C dari Python membuat daftar tampak kosong selama durasi, dan muncul jika dapat mendeteksi bahwa daftar telah dimutasi selama pengurutan
Tupel
Tupel adalah urutan yang tidak dapat diubah, biasanya digunakan untuk menyimpan kumpulan data heterogen (seperti 2-tupel yang dihasilkan oleh built-in). Tuple juga digunakan untuk kasus-kasus di mana urutan data homogen yang tidak dapat diubah diperlukan (seperti memungkinkan penyimpanan dalam atau contoh)
kelas tuple([dapat diubah])Tuple dapat dibangun dalam beberapa cara
Menggunakan sepasang tanda kurung untuk menunjukkan tuple kosong. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _48
Menggunakan tanda koma untuk singleton tuple. >>> (65).to_bytes() b'A' _40 atau >>> (65).to_bytes() b'A' 41
Memisahkan item dengan koma. >>> (65).to_bytes() b'A' _42 atau >>> (65).to_bytes() b'A' 43
Menggunakan built-in. >>> (65).to_bytes() b'A' _44 atau >>> (65).to_bytes() b'A' 46
Konstruktor membuat tuple yang itemnya sama dan dalam urutan yang sama dengan item iterable. iterable dapat berupa urutan, wadah yang mendukung iterasi, atau objek iterator. Jika iterable sudah menjadi tuple, dikembalikan tidak berubah. Misalnya, >>> (65).to_bytes() b'A' _47 mengembalikan >>> (65).to_bytes() b'A' 48 dan >>> (65).to_bytes() b'A' 49 mengembalikan >>> (65).to_bytes() b'A' 50. Jika tidak ada argumen yang diberikan, konstruktor membuat tupel kosong baru, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 48
Perhatikan bahwa sebenarnya koma yang membuat tuple, bukan tanda kurung. Tanda kurung adalah opsional, kecuali dalam kasus tupel kosong, atau ketika diperlukan untuk menghindari ambiguitas sintaksis. Misalnya, >>> (65).to_bytes() b'A' _52 adalah pemanggilan fungsi dengan tiga argumen, sedangkan >>> (65).to_bytes() b'A' 53 adalah pemanggilan fungsi dengan 3-tuple sebagai satu-satunya argumen
Tuple mengimplementasikan semua operasi urutan
Untuk kumpulan data yang heterogen dimana akses berdasarkan nama lebih jelas daripada akses berdasarkan indeks, mungkin merupakan pilihan yang lebih tepat daripada objek tupel sederhana
Rentang
The type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in loops
kelas rentang(berhenti)class range(start, stop[, step])Argumen untuk konstruktor rentang harus bilangan bulat (baik bawaan atau objek apa pun yang mengimplementasikan metode khusus). Jika argumen step dihilangkan, defaultnya adalah def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 55. Jika argumen mulai dihilangkan, defaultnya adalah def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 42. Jika langkahnya nol, dinaikkan
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
Untuk langkah negatif, isi rentang masih ditentukan oleh rumus >>> (65).to_bytes() b'A' 63, tetapi batasannya adalah >>> (65).to_bytes() b'A' 64 dan >>> (65).to_bytes() b'A' 68
Objek rentang akan kosong jika >>> (65).to_bytes() b'A' 69 tidak memenuhi batasan nilai. Rentang memang mendukung indeks negatif, tetapi ini ditafsirkan sebagai pengindeksan dari akhir urutan yang ditentukan oleh indeks positif
Rentang berisi nilai absolut yang lebih besar dari yang diizinkan, tetapi beberapa fitur (seperti ) dapat meningkat
Contoh jangkauan
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _7
Rentang menerapkan semua operasi urutan kecuali penggabungan dan pengulangan (karena fakta bahwa objek rentang hanya dapat mewakili urutan yang mengikuti pola yang ketat dan pengulangan dan penggabungan biasanya akan melanggar pola itu)
awalNilai parameter awal (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 42 jika parameter tidak diberikan)
berhentiNilai parameter berhenti
melangkahNilai parameter langkah (atau def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 55 jika parameter tidak diberikan)
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
Rentang objek mengimplementasikan ABC, dan menyediakan fitur seperti uji penahanan, pencarian indeks elemen, pemotongan, dan dukungan untuk indeks negatif (lihat )
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _8
Menguji objek rentang untuk kesetaraan dengan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 78 dan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 79 membandingkannya sebagai urutan. Artinya, dua objek rentang dianggap sama jika mewakili urutan nilai yang sama. (Perhatikan bahwa dua objek rentang yang membandingkan sama mungkin memiliki perbedaan , dan atribut, misalnya >>> (65).to_bytes() b'A' 88 atau >>> (65).to_bytes() b'A' 89. )
Berubah di versi 3. 2. Implementasikan Urutan ABC. Mendukung pemotongan dan indeks negatif. Uji objek untuk keanggotaan dalam waktu konstan alih-alih mengulangi semua item.
Berubah di versi 3. 3. Tentukan ‘==' dan ‘. =' untuk membandingkan berbagai objek berdasarkan urutan nilai yang mereka tetapkan (alih-alih membandingkan berdasarkan identitas objek).
Baru di versi 3. 3. The , dan atribut.
Lihat juga
Resep linspace menunjukkan cara mengimplementasikan versi rentang lambat yang cocok untuk aplikasi floating point
Jenis Urutan Teks —
Data tekstual dalam Python ditangani dengan objek, atau string. String tidak dapat diubah dari poin kode Unicode. Literal string ditulis dalam berbagai cara
Kutipan tunggal. >>> (65).to_bytes() b'A' _96
Kutipan ganda. >>> (65).to_bytes() b'A' _97
Triple dikutip. >>> (65).to_bytes() b'A' _98, >>> (65).to_bytes() b'A' 99
String yang dikutip tiga kali lipat dapat menjangkau beberapa baris - semua spasi yang terkait akan disertakan dalam literal string
Literal string yang merupakan bagian dari ekspresi tunggal dan hanya memiliki spasi putih di antaranya akan secara implisit dikonversi menjadi literal string tunggal. Yaitu, def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': 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
Lihat lebih lanjut tentang berbagai bentuk literal string, termasuk urutan escape yang didukung, dan awalan >>> (65).to_bytes() b'A' 62 (“mentah”) yang menonaktifkan sebagian besar pemrosesan urutan escape
String juga dapat dibuat dari objek lain menggunakan konstruktor
Karena tidak ada tipe "karakter" yang terpisah, pengindeksan string menghasilkan string dengan panjang 1. Yaitu, untuk string s yang tidak kosong, def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': 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
Berubah di versi 3. 3. Untuk kompatibilitas mundur dengan seri Python 2, awalan def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': 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 sekali lagi diizinkan pada literal string. Itu tidak berpengaruh pada arti literal string dan tidak dapat digabungkan dengan awalan >>> (65).to_bytes() b'A' 62.
kelas str(objek='')class str(object=b'', encoding='utf-8', errors='strict')Mengembalikan versi objek. Jika objek tidak tersedia, kembalikan string kosong. Jika tidak, perilaku def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _33 bergantung pada apakah penyandian atau kesalahan diberikan, sebagai berikut
Jika tidak ada penyandian atau kesalahan yang diberikan, def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': 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 mengembalikan , yang merupakan representasi string "informal" atau objek yang dapat dicetak dengan baik. Untuk objek string, ini adalah string itu sendiri. Jika objek tidak memiliki metode, maka kembali ke kembali
Jika setidaknya satu pengkodean atau kesalahan diberikan, objek harus berupa (mis. g. atau ). Dalam hal ini, jika objek adalah (atau ) objek, maka ________121______18 setara dengan. Jika tidak, objek bytes yang mendasari objek buffer diperoleh sebelum dipanggil. Lihat dan untuk informasi tentang objek penyangga
Melewati objek tanpa argumen pengkodean atau kesalahan termasuk dalam kasus pertama mengembalikan representasi string informal (lihat juga opsi baris perintah ke Python). 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 _9
Untuk informasi lebih lanjut tentang kelas >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' _22 dan metodenya, lihat dan bagian di bawah ini. Untuk menghasilkan string yang diformat, lihat bagian dan. Selain itu, lihat bagian
Metode Untai
String mengimplementasikan semua operasi urutan, bersama dengan metode tambahan yang dijelaskan di bawah ini
String juga mendukung dua gaya pemformatan string, satu memberikan tingkat fleksibilitas dan penyesuaian yang besar (lihat , dan ) dan yang lainnya berdasarkan pemformatan gaya 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 yang menangani rentang jenis yang lebih sempit dan sedikit lebih sulit untuk digunakan dengan benar, tetapi seringkali
Bagian pustaka standar mencakup sejumlah modul lain yang menyediakan berbagai utilitas terkait teks (termasuk dukungan ekspresi reguler dalam modul)
str. kapitalisasi()Kembalikan salinan string dengan karakter pertamanya dikapitalisasi dan sisanya dengan huruf kecil
Berubah di versi 3. 8. Karakter pertama sekarang dimasukkan ke dalam huruf judul bukan huruf besar. Artinya, karakter seperti digraf hanya akan memiliki huruf kapital pertama, bukan karakter penuh.
str. casefold()Kembalikan salinan string yang dilipat-lipat. String casefolded dapat digunakan untuk pencocokan caseless
Pelipatan huruf mirip dengan huruf kecil tetapi lebih agresif karena dimaksudkan untuk menghapus semua perbedaan huruf besar-kecil dalam sebuah string. Misalnya, huruf kecil Jerman def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': 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 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) 29. Karena sudah menggunakan huruf kecil, tidak akan melakukan apa pun untuk def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': 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;
Algoritme pelipatan kasus dijelaskan di bagian 3. 13 dari Standar Unicode
Baru di versi 3. 3
str. pusat(lebar[ , fillchar])Kembali terpusat dalam string lebar panjang. Padding dilakukan menggunakan fillchar yang ditentukan (defaultnya adalah spasi ASCII). String asli dikembalikan jika lebarnya kurang dari atau sama dengan >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 13
str. hitung(sub[ , start[, end]])Kembalikan jumlah kejadian substring yang tidak tumpang tindih dalam rentang [mulai, akhir]. Argumen opsional awal dan akhir ditafsirkan sebagai notasi irisan
Jika sub kosong, kembalikan jumlah string kosong di antara karakter yang merupakan panjang string ditambah satu
str. enkode(enkode=', errors='strict')Kembalikan string yang disandikan ke
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
kesalahan mengontrol bagaimana kesalahan pengkodean ditangani. Jika def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': 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 (default), pengecualian dimunculkan. Nilai lain yang mungkin adalah def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) _39, def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 40, def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': 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 dan nama lain yang terdaftar melalui. Lihat detailnya
Untuk alasan kinerja, nilai kesalahan tidak diperiksa validitasnya kecuali jika kesalahan pengkodean benar-benar terjadi, diaktifkan atau digunakan
Berubah di versi 3. 1. Menambahkan dukungan untuk argumen kata kunci.
Berubah di versi 3. 9. Nilai argumen kesalahan sekarang dicentang masuk dan masuk.
str. diakhiri dengan(akhiran[ , start[, end]])Kembalikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _56 jika string diakhiri dengan akhiran yang ditentukan, jika tidak, kembalikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38. sufiks juga bisa menjadi sekumpulan sufiks yang harus dicari. Dengan start opsional, uji mulai pada posisi itu. Dengan ujung opsional, berhentilah membandingkan pada posisi itu
str. perluas tab(ukuran tab=8)Kembalikan salinan string tempat semua karakter tab diganti dengan satu atau beberapa spasi, bergantung pada kolom saat ini dan ukuran tab yang diberikan. Posisi tab terjadi setiap karakter ukuran tab (default adalah 8, memberikan posisi tab pada kolom 0, 8, 16 dan seterusnya). Untuk memperluas string, kolom saat ini disetel ke nol dan string diperiksa karakter demi karakter. Jika karakternya adalah 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), 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 karakternya adalah baris baru (def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': 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) atau 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), karakter tersebut akan disalin dan kolom saat ini disetel ulang ke nol. Karakter lain apa pun disalin tidak berubah dan kolom saat ini bertambah satu terlepas dari bagaimana karakter direpresentasikan saat dicetak
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 0
str. temukan(sub[ , start[, end]])Kembalikan indeks terendah dalam string tempat substring sub ditemukan di dalam irisan def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': 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. Argumen opsional awal dan akhir ditafsirkan sebagai notasi irisan. Kembalikan >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 _41 jika sub tidak ditemukan
Catatan
Metode ini sebaiknya digunakan hanya jika Anda perlu mengetahui posisi sub. Untuk memeriksa apakah sub adalah substring atau bukan, gunakan operator
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 1
str. format(*args , **kwargs)Lakukan operasi pemformatan string. The string on which this method is called can contain literal text or replacement fields delimited by braces def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 50. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 2
See for a description of the various formatting options that can be specified in format strings
Catatan
When formatting a number (, , , and subclasses) with the def bit_count(self): return bin(self).count("1") 51 type (ex. def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 59), the function temporarily sets the def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 60 locale to the def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 61 locale to decode def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 62 and def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 63 fields of def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 64 if they are non-ASCII or longer than 1 byte, and the def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 61 locale is different than the def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 60 locale. This temporary change affects other threads
Changed in version 3. 7. When formatting a number with the def bit_count(self): return bin(self).count("1") 51 type, the function sets temporarily the def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 60 locale to the def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 61 locale in some cases.
str. format_map(mapping)Similar to def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 70, except that def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 71 is used directly and not copied to a . This is useful if for example def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 71 is a dict subclass
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 3
New in version 3. 2
str. index(sub[ , start[ , end]])Like , but raise when the substring is not found
str. isalnum()Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56 if all characters in the string are alphanumeric and there is at least one character, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 otherwise. A character def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 78 is alphanumeric if one of the following returns def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56. def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 80, def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 81, def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 82, or def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 83
str. isalpha()Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56 if all characters in the string are alphabetic and there is at least one character, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 otherwise. Alphabetic characters are those characters defined in the Unicode character database as “Letter”, i. e. , those with general category property being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is different from the “Alphabetic” property defined in the Unicode Standard
str. isascii()Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56 if the string is empty or all characters in the string are ASCII, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 otherwise. ASCII characters have code points in the range U+0000-U+007F
New in version 3. 7
str. isdecimal()Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56 if all characters in the string are decimal characters and there is at least one character, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 otherwise. Decimal characters are those that can be used to form numbers in base 10, e. g. U+0660, ARABIC-INDIC DIGIT ZERO. Formally a decimal character is a character in the Unicode General Category “Nd”
str. isdigit()Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56 if all characters in the string are digits and there is at least one character, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal
str. isidentifier()Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56 if the string is a valid identifier according to the language definition, section
Call to test whether string def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 94 is a reserved identifier, such as and
Example
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 4
str. islower()Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56 if all cased characters in the string are lowercase and there is at least one cased character, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 otherwise
str. isnumeric()Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56 if all characters in the string are numeric characters, and there is at least one character, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 otherwise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e. g. U+2155, VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric
str. isprintable()Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56 if all characters in the string are printable or the string is empty, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 otherwise. Nonprintable characters are those characters defined in the Unicode character database as “Other” or “Separator”, excepting the ASCII space (0x20) which is considered printable. (Note that printable characters in this context are those which should not be escaped when is invoked on a string. It has no bearing on the handling of strings written to or . )
str. isspace()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 hanya ada karakter spasi putih dalam string dan setidaknya ada satu karakter, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 jika tidak
A character is whitespace if in the Unicode character database (see ), either its general category is >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 09 (“Separator, space”), or its bidirectional class is one of >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 10, >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 11, or >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 12
str. istitle()Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56 if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 otherwise
str. isupper()Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56 if all cased characters in the string are uppercase and there is at least one cased character, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 otherwise
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 5
str. join(iterable)Return a string which is the concatenation of the strings in iterable. A will be raised if there are any non-string values in iterable, including objects. The separator between elements is the string providing this method
str. ljust(width[ , fillchar])Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 13
str. lower()Return a copy of the string with all the cased characters converted to lowercase
The lowercasing algorithm used is described in section 3. 13 of the Unicode Standard
str. lstrip([chars])Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. Jika dihilangkan atau def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _31, argumen chars default untuk menghapus spasi. Argumen chars bukanlah awalan;
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 6
Lihat metode yang akan menghapus satu string awalan daripada semua kumpulan karakter. Misalnya
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 7
statis str. maketrans(x[ , y[, z]])Metode statis ini mengembalikan tabel terjemahan yang dapat digunakan
Jika hanya ada satu argumen, itu harus berupa kamus yang memetakan ordinal Unicode (bilangan bulat) atau karakter (string dengan panjang 1) ke ordinal Unicode, string (dengan panjang arbitrer) atau def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31. Kunci karakter kemudian akan dikonversi menjadi ordinal
Jika ada dua argumen, keduanya harus berupa string dengan panjang yang sama, dan dalam kamus yang dihasilkan, setiap karakter di x akan dipetakan ke karakter pada posisi yang sama di y. If there is a third argument, it must be a string, whose characters will be mapped to def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31 in the result
str. partition(sep)Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings
str. removeprefix(prefix , /)If the string starts with the prefix string, return >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 25. Otherwise, return a copy of the original string
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 8
New in version 3. 9
str. removesuffix(suffix , /)If the string ends with the suffix string and that suffix is not empty, return >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 26. Otherwise, return a copy of the original string
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 9
New in version 3. 9
str. ganti(lama , baru[, count])Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced
str. rfind(sub[ , start[ , end]])Return the highest index in the string where substring sub is found, such that sub is contained within def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 49. Optional arguments start and end are interpreted as in slice notation. Return >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 41 on failure
str. rindex(sub[ , start[ , end]])Like but raises when the substring sub is not found
str. rjust(width[ , fillchar])Return the string right justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 13
str. rpartition(sep)Split the string at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself
str. rsplit(sep=None , maxsplit=- 1)Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31, any whitespace string is a separator. Except for splitting from the right, behaves like which is described in detail below
str. rstrip([chars])Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31, the chars argument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped
def bit_count(self): return bin(self).count("1") 0
See for a method that will remove a single suffix string rather than all of a set of characters. For example
def bit_count(self): return bin(self).count("1") 1
str. split(sep=None , maxsplit=- 1)Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 37 elements). If maxsplit is not specified or >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 41, then there is no limit on the number of splits (all possible splits are made)
If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 39 returns >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 40). The sep argument may consist of multiple characters (for example, >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 41 returns >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 42). Splitting an empty string with a specified separator returns >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 43
For example
def bit_count(self): return bin(self).count("1") 2
If sep is not specified or is def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31, a different splitting algorithm is applied. runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31 separator returns def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 49
For example
def bit_count(self): return bin(self).count("1") 3
str. splitlines(keepends=False)Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true
Metode ini terbagi pada batas garis berikut. In particular, the boundaries are a superset of
Representation
Description
def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 47
Line Feed
def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 48
Carriage Return
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 49
Carriage Return + Line Feed
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 50 or >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 51
Line Tabulation
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 52 or >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 53
Form Feed
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 54
File Separator
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 55
Group Separator
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 56
Record Separator
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 57
Next Line (C1 Control Code)
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 58
Line Separator
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 59
Paragraph Separator
Changed in version 3. 2. >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 50 and >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 52 added to list of line boundaries.
For example
def bit_count(self): return bin(self).count("1") 4
Unlike when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line
def bit_count(self): return bin(self).count("1") 5
For comparison, >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 63 gives
def bit_count(self): return bin(self).count("1") 6
str. startswith(prefix[ , start[ , end]])Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56 if string starts with the prefix, otherwise return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38. awalan juga bisa menjadi kumpulan awalan yang harus dicari. With optional start, test string beginning at that position. With optional end, stop comparing string at that position
str. strip([karakter])Kembalikan salinan string dengan karakter awal dan akhir dihapus. The chars argument is a string specifying the set of characters to be removed. If omitted or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped
def bit_count(self): return bin(self).count("1") 7
The outermost leading and trailing chars argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in chars. A similar action takes place on the trailing end. For example
def bit_count(self): return bin(self).count("1") 8
str. swapcase()Kembalikan salinan string dengan karakter huruf besar yang diubah menjadi huruf kecil dan sebaliknya. Note that it is not necessarily true that >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 67
str. title()Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase
For example
def bit_count(self): return bin(self).count("1") 9
The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 0
The function does not have this problem, as it splits words on spaces only
Alternatively, a workaround for apostrophes can be constructed using regular expressions
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 1
str. translate(table)Return a copy of the string in which each character has been mapped through the given translation table. The table must be an object that implements indexing via >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 69, typically a or . When indexed by a Unicode ordinal (an integer), the table object can do any of the following. return a Unicode ordinal or a string, to map the character to one or more other characters; return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31, to delete the character from the return string; or raise a exception, to map the character to itself
You can use to create a translation map from character-to-character mappings in different formats
See also the module for a more flexible approach to custom character mappings
str. upper()Return a copy of the string with all the cased characters converted to uppercase. Note that >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 74 might be def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 if def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 94 contains uncased characters or if the Unicode category of the resulting character(s) is not “Lu” (Letter, uppercase), but e. g. “Lt” (Letter, titlecase)
The uppercasing algorithm used is described in section 3. 13 of the Unicode Standard
str. zfill(width)Return a copy of the string left filled with ASCII >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 77 digits to make a string of length width. A leading sign prefix (>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 78/>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 79) is handled by inserting the padding after the sign character rather than before. The original string is returned if width is less than or equal to >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 13
For example
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 2
def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 26-style String Formatting
Catatan
The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer , the interface, or may help avoid these errors. Each of these alternatives provides their own trade-offs and benefits of simplicity, flexibility, and/or extensibility
String objects have one unique built-in operation. the >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 83 operator (modulo). This is also known as the string formatting or interpolation operator. Given >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 84 (where format is a string), >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 83 conversion specifications in format are replaced with zero or more elements of values. The effect is similar to using the >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 86 in the C language
If format requires a single argument, values may be a single non-tuple object. Otherwise, values must be a tuple with exactly the number of items specified by the format string, or a single mapping object (for example, a dictionary)
A conversion specifier contains two or more characters and has the following components, which must occur in this order
The >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 87 character, which marks the start of the specifier
Mapping key (optional), consisting of a parenthesised sequence of characters (for example, >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 88)
Conversion flags (optional), which affect the result of some conversion types
Minimum field width (optional). If specified as an >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 89 (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision
Precision (optional), given as a >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 90 (dot) followed by the precision. If specified as >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 89 (an asterisk), the actual precision is read from the next element of the tuple in values, and the value to convert comes after the precision
Length modifier (optional)
Conversion type
Jika argumen yang benar adalah kamus (atau jenis pemetaan lainnya), maka format dalam string harus menyertakan kunci pemetaan dalam tanda kurung ke dalam kamus yang dimasukkan tepat setelah karakter >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 87. The mapping key selects the value to be formatted from the mapping. For example
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 3
In this case no >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 00 specifiers may occur in a format (since they require a sequential parameter list)
The conversion flag characters are
Flag
Meaning
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 94
The value conversion will use the “alternate form” (where defined below)
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 77
The conversion will be zero padded for numeric values
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 79
The converted value is left adjusted (overrides the >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 77 conversion if both are given)
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 98
(a space) A blank should be left before a positive number (or empty string) produced by a signed conversion
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 78
A sign character (>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 78 or >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 79) will precede the conversion (overrides a “space” flag)
A length modifier (def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 02, def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 03, or def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 04) may be present, but is ignored as it is not necessary for Python – so e. g. def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 05 is identical to def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 06
The conversion types are
Conversion
Meaning
Notes
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 07
Signed integer decimal
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 08
Signed integer decimal
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 09
Signed octal value
(1)
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 10
Obsolete type – it is identical to def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 07
(6)
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 12
Signed hexadecimal (lowercase)
(2)
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 13
Signed hexadecimal (uppercase)
(2)
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 14
Floating point exponential format (lowercase)
(3)
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n _15
Floating point exponential format (uppercase)
(3)
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 16
Floating point decimal format
(3)
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 17
Floating point decimal format
(3)
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 18
Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise
(4)
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 19
Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise
(4)
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 20
Single character (accepts integer or single character string)
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n _21
String (mengonversi objek Python apa pun menggunakan )
(5)
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 23
String (mengonversi objek Python apa pun menggunakan )
(5)
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n _25
String (mengonversi objek Python apa pun menggunakan )
(5)
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 87
No argument is converted, results in a >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 87 character in the result
Notes
The alternate form causes a leading octal specifier (def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 29) to be inserted before the first digit
The alternate form causes a leading def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 30 or def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 31 (depending on whether the def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 12 or def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 13 format was used) to be inserted before the first digit
The alternate form causes the result to always contain a decimal point, even if no digits follow it
The precision determines the number of digits after the decimal point and defaults to 6
The alternate form causes the result to always contain a decimal point, and trailing zeroes are not removed as they would otherwise be
The precision determines the number of significant digits before and after the decimal point and defaults to 6
If precision is def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 34, the output is truncated to def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 34 characters
See PEP 237
Since Python strings have an explicit length, def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 36 conversions do not assume that def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 37 is the end of the string
Changed in version 3. 1. def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 38 conversions for numbers whose absolute value is over 1e50 are no longer replaced by def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 39 conversions.
Binary Sequence Types — , ,
The core built-in types for manipulating binary data are and . They are supported by which uses the to access the memory of other binary objects without needing to make a copy
The module supports efficient storage of basic data types like 32-bit integers and IEEE754 double-precision floating values
Bytes Objects
Bytes objects are immutable sequences of single bytes. Since many major binary protocols are based on the ASCII text encoding, bytes objects offer several methods that are only valid when working with ASCII compatible data and are closely related to string objects in a variety of other ways
class bytes([source[ , encoding[ , errors]]])Firstly, the syntax for bytes literals is largely the same as that for string literals, except that a def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 47 prefix is added
Single quotes. def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 48
Double quotes. def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 49
Triple quoted. def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 50, def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 51
Only ASCII characters are permitted in bytes literals (regardless of the declared source code encoding). Any binary values over 127 must be entered into bytes literals using the appropriate escape sequence
As with string literals, bytes literals may also use a >>> (65).to_bytes() b'A' 62 prefix to disable processing of escape sequences. See for more about the various forms of bytes literal, including supported escape sequences
While bytes literals and representations are based on ASCII text, bytes objects actually behave like immutable sequences of integers, with each value in the sequence restricted such that def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 53 (attempts to violate this restriction will trigger ). This is done deliberately to emphasise that while many binary formats include ASCII based elements and can be usefully manipulated with some text-oriented algorithms, this is not generally the case for arbitrary binary data (blindly applying text processing algorithms to binary data formats that are not ASCII compatible will usually lead to data corruption)
In addition to the literal forms, bytes objects can be created in a number of other ways
A zero-filled bytes object of a specified length. def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 55
From an iterable of integers. def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 56
Copying existing binary data via the buffer protocol. def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 57
Also see the built-in
Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal numbers are a commonly used format for describing binary data. Accordingly, the bytes type has an additional class method to read data in that format
classmethod fromhex(string)This class method returns a bytes object, decoding the given string object. The string must contain two hexadecimal digits per byte, with ASCII whitespace being ignored
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 4
Changed in version 3. 7. now skips all ASCII whitespace in the string, not just spaces.
A reverse conversion function exists to transform a bytes object into its hexadecimal representation
hex([sep[ , bytes_per_sep]])Return a string object containing two hexadecimal digits for each byte in the instance
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 5
Jika Anda ingin membuat string hex lebih mudah dibaca, Anda dapat menentukan parameter sep pemisah karakter tunggal untuk disertakan dalam output. By default, this separator will be included between each byte. A second optional bytes_per_sep parameter controls the spacing. Positive values calculate the separator position from the right, negative values from the left
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 6
New in version 3. 5
Changed in version 3. 8. now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output.
Since bytes objects are sequences of integers (akin to a tuple), for a bytes object b, def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 61 will be an integer, while def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 62 will be a bytes object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1)
The representation of bytes objects uses the literal format (def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 63) since it is often more useful than e. g. def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 64. You can always convert a bytes object into a list of integers using def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 65
Bytearray Objects
objects are a mutable counterpart to objects
class bytearray([source[ , encoding[ , errors]]])There is no dedicated literal syntax for bytearray objects, instead they are always created by calling the constructor
Creating an empty instance. def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 68
Creating a zero-filled instance with a given length. def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 69
From an iterable of integers. def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 70
Copying existing binary data via the buffer protocol. def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 71
As bytearray objects are mutable, they support the sequence operations in addition to the common bytes and bytearray operations described in
Also see the built-in
Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal numbers are a commonly used format for describing binary data. Accordingly, the bytearray type has an additional class method to read data in that format
classmethod fromhex(string)This class method returns bytearray object, decoding the given string object. The string must contain two hexadecimal digits per byte, with ASCII whitespace being ignored
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 7
Changed in version 3. 7. now skips all ASCII whitespace in the string, not just spaces.
A reverse conversion function exists to transform a bytearray object into its hexadecimal representation
hex([sep[ , bytes_per_sep]])Return a string object containing two hexadecimal digits for each byte in the instance
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 8
New in version 3. 5
Changed in version 3. 8. Similar to , now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output.
Since bytearray objects are sequences of integers (akin to a list), for a bytearray object b, def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 61 will be an integer, while def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 62 will be a bytearray object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1)
The representation of bytearray objects uses the bytes literal format (def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 78) since it is often more useful than e. g. def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 79. You can always convert a bytearray object into a list of integers using def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 65
Bytes and Bytearray Operations
Both bytes and bytearray objects support the sequence operations. They interoperate not just with operands of the same type, but with any . Due to this flexibility, they can be freely mixed in operations without causing errors. However, the return type of the result may depend on the order of operands
Catatan
Metode pada objek byte dan bytearray tidak menerima string sebagai argumennya, sama seperti metode pada string tidak menerima byte sebagai argumennya. 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
Catatan
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. hitung(sub[ , . start[, end]])bytearray.count(sub[ , start[ , end]])Return the number of non-overlapping occurrences of subsequence sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation
The subsequence to search for may be any or an integer in the range 0 to 255
If sub is empty, returns the number of empty slices between characters which is the length of the bytes object plus one
Changed in version 3. 3. Also accept an integer in the range 0 to 255 as the subsequence.
bytes. removeprefix(prefix , /)bytearray. removeprefix(prefix , /)If the binary data starts with the prefix string, return def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 81. Otherwise, return a copy of the original binary data
>>> (65).to_bytes() b'A' 1
The prefix may be any
Catatan
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
New in version 3. 9
bytes. removesuffix(suffix , /)bytearray. removesuffix(suffix , /)If the binary data ends with the suffix string and that suffix is not empty, return def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 82. Otherwise, return a copy of the original binary data
>>> (65).to_bytes() b'A' 2
The suffix may be any
Catatan
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
New in version 3. 9
bytes. decode(encoding='utf-8' , errors='strict')bytearray. decode(encoding='utf-8' , errors='strict')Return the bytes decoded to a
encoding defaults to def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 36; see for possible values
errors controls how decoding errors are handled. If def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 37 (the default), a exception is raised. 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
Catatan
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
Berubah di versi 3. 1. Menambahkan dukungan untuk argumen kata kunci.
Berubah di versi 3. 9. Nilai argumen kesalahan sekarang dicentang masuk dan masuk.
bytes. endswith(suffix[ , start[ , end]])bytearray. endswith(suffix[ , start[ , end]])Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56 if the binary data ends with the specified suffix, otherwise return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position
The suffix(es) to search for may be any
bytes. find(sub[ , start[ , end]])bytearray. find(sub[ , start[ , end]])Return the lowest index in the data where the subsequence sub is found, such that sub is contained in the slice def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 49. Optional arguments start and end are interpreted as in slice notation. Return >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 41 if sub is not found
The subsequence to search for may be any or an integer in the range 0 to 255
Catatan
Metode ini sebaiknya digunakan hanya jika Anda perlu mengetahui posisi sub. Untuk memeriksa apakah sub adalah substring atau bukan, gunakan 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. bergabung(dapat diubah)Return a bytes or bytearray object which is the concatenation of the binary data sequences in iterable. A will be raised if there are any values in iterable that are not , including objects. The separator between elements is the contents of the bytes or bytearray object providing this method
static bytes. maketrans(from , to)static bytearray. maketrans(from , to)This static method returns a translation table usable for that will map each character in from into the character at the same position in to; from and to must both be and have the same length
New in version 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
Catatan
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
bytes. rfind(sub[ , start[ , end]])bytearray. rfind(sub[ , start[ , end]])Return the highest index in the sequence where the subsequence sub is found, such that sub is contained within def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 49. Optional arguments start and end are interpreted as in slice notation. Return >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 41 on failure
The subsequence to search for may be any or an integer in the range 0 to 255
Changed in version 3. 3. Also accept an integer in the range 0 to 255 as the subsequence.
bytes. rindex(sub[ , start[ , end]])bytearray. rindex(sub[ , start[ , end]])Like but raises when the subsequence sub is not found
The subsequence to search for may be any or an integer in the range 0 to 255
Changed in version 3. 3. Also accept an integer in the range 0 to 255 as the subsequence.
bytes. rpartition(sep)bytearray. rpartition(sep)Split the sequence at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself or its bytearray copy, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty bytes or bytearray objects, followed by a copy of the original sequence
The separator to search for may be any
bytes. startswith(prefix[ , start[ , end]])bytearray. startswith(prefix[ , start[ , end]])Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56 if the binary data starts with the specified prefix, otherwise return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38. prefix can also be a tuple of prefixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position
Awalan yang akan dicari dapat berupa apa saja
bytes. translate(table , / , delete=b'')bytearray. translate(table , / , delete=b'')Return a copy of the bytes or bytearray object where all bytes occurring in the optional argument delete are removed, and the remaining bytes have been mapped through the given translation table, which must be a bytes object of length 256
You can use the method to create a translation table
Set the table argument to def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31 for translations that only delete characters
>>> (65).to_bytes() b'A' 4
Changed in version 3. 6. delete sekarang didukung sebagai argumen kata kunci.
The following methods on bytes and bytearray objects have default behaviours that assume the use of ASCII compatible binary formats, but can still be used with arbitrary binary data by passing appropriate arguments. Note that all of the bytearray methods in this section do not operate in place, and instead produce new objects
bytes. center(width[ , fillbyte])bytearray. pusat(lebar[ , 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
Catatan
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
bytes. ljust(width[ , fillbyte])bytearray. ljust(width[ , fillbyte])Return a copy of the object left justified in a sequence of length width. Padding is done using the specified fillbyte (default is an ASCII space). For objects, the original sequence is returned if width is less than or equal to >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 13
Catatan
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
bytes. lstrip([chars])bytearray. lstrip([chars])Return a copy of the sequence with specified leading bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31, the chars argument defaults to removing ASCII whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped
>>> (65).to_bytes() b'A' 5
The binary sequence of byte values to remove may be any . See for a method that will remove a single prefix string rather than all of a set of characters. For example
>>> (65).to_bytes() b'A' 6
Catatan
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
bytes. rjust(width[ , fillbyte])bytearray. rjust(width[ , fillbyte])Return a copy of the object right justified in a sequence of length width. Padding is done using the specified fillbyte (default is an ASCII space). For objects, the original sequence is returned if width is less than or equal to >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 13
Catatan
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
bytes. rsplit(sep=None , maxsplit=- 1)bytearray. rsplit(sep=None , maxsplit=- 1)Split the binary sequence into subsequences of the same type, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31, any subsequence consisting solely of ASCII whitespace is a separator. Except for splitting from the right, behaves like which is described in detail below
bytes. rstrip([chars])bytearray. rstrip([chars])Return a copy of the sequence with specified trailing bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31, the chars argument defaults to removing ASCII whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped
>>> (65).to_bytes() b'A' 7
The binary sequence of byte values to remove may be any . See for a method that will remove a single suffix string rather than all of a set of characters. For example
>>> (65).to_bytes() b'A' 8
Catatan
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
bytes. split(sep=None , maxsplit=- 1)bytearray. pisah(sep=Tidak ada, maxsplit=- 1)Split the binary sequence into subsequences of the same type, using sep as the delimiter string. If maxsplit is given and non-negative, at most maxsplit splits are done (thus, the list will have at most >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 37 elements). If maxsplit is not specified or is >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 41, then there is no limit on the number of splits (all possible splits are made)
If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty subsequences (for example, >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 27 returns >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 28). The sep argument may consist of a multibyte sequence (for example, >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 29 returns >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 30). Splitting an empty sequence with a specified separator returns >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 31 or >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 32 depending on the type of object being split. The sep argument may be any
For example
>>> (65).to_bytes() b'A' 9
If sep is not specified or is def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31, a different splitting algorithm is applied. runs of consecutive ASCII whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the sequence has leading or trailing whitespace. Akibatnya, memisahkan urutan kosong atau urutan yang hanya terdiri dari spasi putih ASCII tanpa pemisah yang ditentukan mengembalikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 49
For example
def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) _0
byte. strip([karakter] . )bytearray.strip([karakter])Kembalikan salinan urutan dengan byte awal dan akhir yang ditentukan dihapus. Argumen chars adalah urutan biner yang menentukan kumpulan nilai byte yang akan dihapus - namanya mengacu pada fakta bahwa metode ini biasanya digunakan dengan karakter ASCII. Jika dihilangkan atau def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31, argumen chars default untuk menghapus spasi ASCII. 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
Urutan biner dari nilai byte yang akan dihapus dapat berupa apa saja
Catatan
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
Metode berikut pada objek byte dan bytearray mengasumsikan penggunaan format biner yang kompatibel dengan ASCII dan tidak boleh diterapkan pada data biner arbitrer. Perhatikan bahwa semua metode bytearray di bagian ini tidak beroperasi di tempat, dan malah menghasilkan objek baru
byte. kapitalisasi()bytearray. kapitalisasi()Kembalikan salinan urutan dengan setiap byte ditafsirkan sebagai karakter ASCII, dan byte pertama dikapitalisasi dan sisanya dengan huruf kecil. Nilai byte non-ASCII diteruskan tanpa perubahan
Catatan
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
byte. perluas tab(ukuran tab=8 . )bytearray.expandtabs(ukuran tab=8)Kembalikan salinan urutan di mana semua karakter tab ASCII diganti dengan satu atau lebih spasi ASCII, bergantung pada kolom saat ini dan ukuran tab yang diberikan. Posisi tab terjadi setiap byte tabsize (default adalah 8, memberikan posisi tab pada kolom 0, 8, 16 dan seterusnya). Untuk memperluas urutan, kolom saat ini diatur ke nol dan urutan diperiksa byte demi byte. Jika byte adalah karakter tab ASCII (>>> (-2.0).is_integer() True >>> (3.2).is_integer() False 36), satu atau lebih karakter spasi dimasukkan ke dalam hasil hingga kolom saat ini sama dengan posisi tab berikutnya. (Karakter tab itu sendiri tidak disalin. ) Jika byte saat ini adalah baris baru ASCII (>>> (-2.0).is_integer() True >>> (3.2).is_integer() False 37) atau carriage return (>>> (-2.0).is_integer() True >>> (3.2).is_integer() False 38), ini akan disalin dan kolom saat ini disetel ulang ke nol. Nilai byte lainnya disalin tidak berubah dan kolom saat ini bertambah satu terlepas dari bagaimana nilai byte direpresentasikan saat dicetak
def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) _2
Catatan
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
byte. isalnum()bytearray. isalnum()Kembalikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _56 jika semua byte dalam urutan adalah karakter ASCII abjad atau angka desimal ASCII dan urutannya tidak kosong, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 jika tidak. Karakter ASCII alfabetis adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 41. Digit desimal ASCII adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 42
For example
def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) _3
byte. isalpha()bytearray. isalpha()Kembalikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _56 jika semua byte dalam urutan adalah karakter ASCII abjad dan urutannya tidak kosong, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 jika tidak. Karakter ASCII alfabetis adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 41
For example
def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) _4
byte. isascii()bytearray. isascii()Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56 if the sequence is empty or all bytes in the sequence are ASCII, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 otherwise. Byte ASCII berada dalam kisaran 0-0x7F
New in version 3. 7
byte. isdigit()bytearray. angka()Kembalikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _56 jika semua byte dalam urutan adalah digit desimal ASCII dan urutannya tidak kosong, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 jika tidak. Digit desimal ASCII adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 42
For example
def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) _5
byte. lebih rendah()bytearray. lebih rendah()Kembalikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _56 jika setidaknya ada satu karakter ASCII huruf kecil dalam urutan dan tidak ada karakter ASCII huruf besar, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 jika tidak
For example
def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) _6
Karakter ASCII huruf kecil adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 53. Karakter ASCII huruf besar adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 54
byte. isspace()bytearray. isspace()Kembalikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _56 jika semua byte dalam urutan adalah spasi putih ASCII dan urutannya tidak kosong, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 jika tidak. Karakter spasi putih ASCII adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 57 (spasi, tab, baris baru, carriage return, tab vertikal, umpan formulir)
byte. istitle()bytearray. istitle()Kembalikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _56 jika urutannya adalah huruf judul ASCII dan urutannya tidak kosong, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 jika tidak. See for more details on the definition of “titlecase”
For example
def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 7
byte. persediaan()bytearray. supper()Kembalikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _56 jika setidaknya ada satu karakter ASCII alfabet huruf besar dalam urutan dan tidak ada karakter ASCII huruf kecil, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 jika tidak
For example
def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) _8
Karakter ASCII huruf kecil adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 53. Karakter ASCII huruf besar adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 54
byte. bawah()bytearray. lebih rendah()Kembalikan salinan urutan dengan semua karakter ASCII huruf besar yang dikonversi ke pasangan huruf kecil yang sesuai
For example
def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) _9
Karakter ASCII huruf kecil adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 53. Karakter ASCII huruf besar adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 54
Catatan
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
byte. splitlines(keepends=False . )bytearray.splitlines(keepends=False)Kembalikan daftar garis dalam urutan biner, putus pada batas garis ASCII. Metode ini menggunakan pendekatan pemisahan garis. Jeda baris tidak disertakan dalam daftar yang dihasilkan kecuali keepends diberikan dan benar
For example
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 _0
Unlike when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 _1
byte. swapcase()bytearray. swapcase()Kembalikan salinan urutan dengan semua karakter ASCII huruf kecil yang dikonversi ke pasangan huruf besar yang sesuai dan sebaliknya
For example
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 _2
Karakter ASCII huruf kecil adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 53. Karakter ASCII huruf besar adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 54
Tidak seperti , selalu demikian >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 71 untuk versi biner. Konversi kasus bersifat simetris dalam ASCII, meskipun hal itu umumnya tidak berlaku untuk poin kode Unicode arbitrer
Catatan
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
byte. judul()bytearray. judul()Mengembalikan versi huruf-huruf dari urutan biner di mana kata-kata dimulai dengan karakter ASCII huruf besar dan karakter yang tersisa adalah huruf kecil. Nilai byte tanpa huruf dibiarkan tidak dimodifikasi
For example
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 _3
Karakter ASCII huruf kecil adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 53. Karakter ASCII huruf besar adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 54. Semua nilai byte lainnya tidak di-uncase
The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 _4
Solusi untuk apostrof dapat dibangun menggunakan ekspresi reguler
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 _5
Catatan
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
byte. upper()bytearray. atas()Kembalikan salinan urutan dengan semua karakter ASCII huruf kecil yang dikonversi ke pasangan huruf besar yang sesuai
For example
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 _6
Karakter ASCII huruf kecil adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 53. Karakter ASCII huruf besar adalah nilai byte dalam urutan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 54
Catatan
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
byte. zisi(lebar)bytearray. zisi(lebar)Mengembalikan salinan urutan kiri diisi dengan ASCII >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 76 digit untuk membuat urutan panjang lebar. Prefiks tanda depan (>>> (-2.0).is_integer() True >>> (3.2).is_integer() False 77/ >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 78) ditangani dengan menyisipkan padding setelah karakter tanda, bukan sebelumnya. Untuk objek, urutan aslinya dikembalikan jika lebarnya kurang dari atau sama dengan >>> (-2.0).is_integer() True >>> (3.2).is_integer() False 80
For example
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 _7
Catatan
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) _ Pemformatan Byte 26 gaya
Catatan
Operasi pemformatan yang dijelaskan di sini menunjukkan berbagai keanehan yang menyebabkan sejumlah kesalahan umum (seperti gagal menampilkan tupel dan kamus dengan benar). Jika nilai yang dicetak mungkin berupa tupel atau kamus, bungkus dalam tupel
Objek byte (>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 23/>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 24) memiliki satu operasi bawaan yang unik. operator >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 _83 (modulo). Ini juga dikenal sebagai pemformatan byte atau operator interpolasi. Diberikan >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 _84 (di mana format adalah objek byte), >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 83 spesifikasi konversi dalam format diganti dengan nol atau lebih elemen nilai. Efeknya mirip dengan menggunakan >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 86 dalam bahasa C
Jika format memerlukan argumen tunggal, nilai mungkin merupakan objek non-tupel tunggal. Jika tidak, nilai harus berupa tupel dengan jumlah persis item yang ditentukan oleh objek format byte, atau objek pemetaan tunggal (misalnya, kamus)
A conversion specifier contains two or more characters and has the following components, which must occur in this order
The >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 87 character, which marks the start of the specifier
Mapping key (optional), consisting of a parenthesised sequence of characters (for example, >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 88)
Conversion flags (optional), which affect the result of some conversion types
Minimum field width (optional). If specified as an >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 89 (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision
Precision (optional), given as a >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 90 (dot) followed by the precision. If specified as >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 89 (an asterisk), the actual precision is read from the next element of the tuple in values, and the value to convert comes after the precision
Length modifier (optional)
Conversion type
When the right argument is a dictionary (or other mapping type), then the formats in the bytes object must include a parenthesised mapping key into that dictionary inserted immediately after the >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 87 character. Kunci pemetaan memilih nilai yang akan diformat dari pemetaan. Misalnya
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 _8
In this case no >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 00 specifiers may occur in a format (since they require a sequential parameter list)
The conversion flag characters are
Flag
Meaning
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 94
The value conversion will use the “alternate form” (where defined below)
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 77
The conversion will be zero padded for numeric values
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 79
The converted value is left adjusted (overrides the >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 77 conversion if both are given)
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 98
(a space) A blank should be left before a positive number (or empty string) produced by a signed conversion
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 78
A sign character (>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 78 or >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 79) will precede the conversion (overrides a “space” flag)
A length modifier (def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 02, def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 03, or def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 04) may be present, but is ignored as it is not necessary for Python – so e. g. def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 05 is identical to def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 06
The conversion types are
Conversion
Meaning
Notes
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 07
Signed integer decimal
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 08
Signed integer decimal
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 09
Signed octal value
(1)
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 10
Obsolete type – it is identical to def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 07
(8)
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 12
Signed hexadecimal (lowercase)
(2)
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 13
Signed hexadecimal (uppercase)
(2)
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 14
Floating point exponential format (lowercase)
(3)
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n _15
Floating point exponential format (uppercase)
(3)
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 16
Floating point decimal format
(3)
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 17
Floating point decimal format
(3)
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 18
Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise
(4)
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 19
Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise
(4)
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 20
Single byte (menerima objek integer atau single byte)
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _022
Byte (objek apa pun yang mengikuti atau memiliki def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 023)
(5)
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 23
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n _23 adalah alias untuk def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 022 dan hanya boleh digunakan untuk basis kode Python2/3
(6)
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n _25
Byte (mengonversi objek Python apa pun menggunakan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 028)
(5)
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n _21
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n _21 adalah alias untuk def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 25 dan hanya boleh digunakan untuk basis kode Python2/3
(7)
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 87
No argument is converted, results in a >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 87 character in the result
Notes
The alternate form causes a leading octal specifier (def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 29) to be inserted before the first digit
The alternate form causes a leading def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 30 or def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 31 (depending on whether the def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 12 or def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 13 format was used) to be inserted before the first digit
The alternate form causes the result to always contain a decimal point, even if no digits follow it
The precision determines the number of digits after the decimal point and defaults to 6
The alternate form causes the result to always contain a decimal point, and trailing zeroes are not removed as they would otherwise be
The precision determines the number of significant digits before and after the decimal point and defaults to 6
If precision is def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 34, the output is truncated to def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 34 characters
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _041 sudah usang, tetapi tidak akan dihapus selama 3. seri x
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _042 sudah usang, tetapi tidak akan dihapus selama 3. seri x
See PEP 237
Catatan
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
Lihat juga
PEP 461 - Menambahkan % pemformatan ke byte dan bytearray
New in version 3. 5
Tampilan Memori
objek memungkinkan kode Python untuk mengakses data internal objek yang mendukung tanpa menyalin
kelas memoryview(objek)Buat objek referensi itu. object must support the buffer protocol. 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. Mengubah ukuran tidak diperbolehkan
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n _1
One-dimensional memoryviews of hashable (read-only) types with formats ‘B’, ‘b’ or ‘c’ are also hashable. Hash didefinisikan sebagai def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _059
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n _2
Berubah di versi 3. 3. Tampilan memori satu dimensi sekarang dapat dipotong. Tampilan memori satu dimensi dengan format 'B', 'b' atau 'c' kini dapat di-hash.
Berubah di versi 3. 4. memoryview sekarang terdaftar secara otomatis dengan
Berubah di versi 3. 5. memoryview sekarang dapat diindeks dengan tuple bilangan bulat.
memiliki beberapa metode
__eq__(eksportir)Tampilan memori dan pengekspor PEP 3118 sama jika bentuknya sama dan jika semua nilai yang sesuai sama ketika kode format masing-masing operan ditafsirkan menggunakan sintaks
Untuk subset string format yang saat ini didukung oleh , def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 065 dan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 066 sama jika def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 067
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n _3
Jika salah satu string format tidak didukung oleh modul, maka objek akan selalu dibandingkan sebagai tidak sama (bahkan jika string format dan konten buffer identik)
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n _4
Perhatikan bahwa, seperti angka floating point, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 069 tidak berarti def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 070 untuk objek memoryview
Changed in version 3. 3. Versi sebelumnya membandingkan memori mentah dengan mengabaikan format item dan struktur array logis.
tobyte(pesanan='C' C- dan C-contiguous -> 1DFormat tujuan dibatasi ke format asli elemen tunggal dalam sintaks. 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
Baru di versi 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
Baru di versi 3. 3
nbytesdef bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _084. Ini adalah jumlah ruang dalam byte yang akan digunakan array dalam representasi yang berdekatan. Ini belum tentu sama dengan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _085
>>> (-2.0).is_integer() True >>> (3.2).is_integer() False _6
Array multi-dimensi
>>> (-2.0).is_integer() True >>> (3.2).is_integer() False _7
Baru di versi 3. 3
hanya bisa dibacaA bool indicating whether the memory is read only
formatString berisi format (dalam gaya modul) untuk setiap elemen dalam tampilan. Tampilan memori dapat dibuat dari pengekspor dengan string format arbitrer, tetapi beberapa metode (mis. g. ) dibatasi untuk format elemen tunggal asli
Berubah di versi 3. 3. format def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 088 sekarang ditangani sesuai dengan sintaks modul struct. Ini berarti bahwa def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _089.
itemsizeUkuran dalam byte dari setiap elemen tampilan memori
>>> (-2.0).is_integer() True >>> (3.2).is_integer() False _8
ndimBilangan bulat yang menunjukkan berapa banyak dimensi dari array multi-dimensi yang diwakili oleh memori
membentukSebuah tupel bilangan bulat panjang memberikan bentuk memori sebagai array N-dimensi
Berubah di versi 3. 3. Tuple kosong bukan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31 saat ndim = 0.
langkahTuple bilangan bulat dengan panjang pemberian ukuran dalam byte untuk mengakses setiap elemen untuk setiap dimensi array
Berubah di versi 3. 3. Tuple kosong bukan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31 saat ndim = 0.
suboffsets Digunakan secara internal untuk array gaya PIL. Nilai hanya bersifat informasional
c_contiguousBool yang menunjukkan apakah memori adalah C-
Baru di versi 3. 3
f_contiguousSebuah bool yang menunjukkan apakah memori tersebut adalah Fortran
Baru di versi 3. 3
berdekatanBool yang menunjukkan apakah memori itu
Baru di versi 3. 3
Jenis Setel — ,
Objek set adalah kumpulan objek berbeda yang tidak terurut. Penggunaan umum termasuk pengujian keanggotaan, menghapus duplikat dari suatu urutan, dan menghitung operasi matematika seperti persimpangan, penyatuan, perbedaan, dan perbedaan simetris. (Untuk container lain lihat built-in , , dan class, dan module. )
Seperti koleksi lainnya, set dukungan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 100, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 101, dan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 102. Menjadi koleksi yang tidak terurut, himpunan tidak merekam posisi elemen atau urutan penyisipan. Dengan demikian, set tidak mendukung pengindeksan, pemotongan, atau perilaku seperti urutan lainnya
Saat ini ada dua tipe set bawaan, dan. Jenisnya bisa berubah — isinya bisa diubah menggunakan metode seperti def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 106 dan >>> (65).to_bytes() b'A' 01. Since it is mutable, it has no hash value and cannot be used as either a dictionary key or as an element of another set. Jenisnya tidak dapat diubah dan — isinya tidak dapat diubah setelah dibuat;
Set yang tidak kosong (bukan set yang dibekukan) dapat dibuat dengan menempatkan daftar elemen yang dipisahkan koma di dalam kurung kurawal, misalnya. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _109, selain konstruktor
Konstruktor untuk kedua kelas bekerja sama
kelas set([dapat diubah])class frozenset([iterable])Kembalikan set baru atau objek set beku yang elemennya diambil dari iterable. Unsur-unsur suatu himpunan harus. Untuk merepresentasikan himpunan dari himpunan, himpunan bagian dalam harus berupa objek. Jika iterable tidak ditentukan, set kosong baru dikembalikan
Set dapat dibuat dengan beberapa cara
Gunakan daftar elemen yang dipisahkan koma di dalam kurung kurawal. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _109
Gunakan pemahaman yang ditetapkan. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _113
Gunakan konstruktor tipe. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 51, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 115, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 116
Contoh dari dan menyediakan operasi berikut
lensa)Mengembalikan jumlah elemen dalam set s (kardinalitas s)
x dalam sTest x for membership in s
x tidak dalam sUji x untuk non-keanggotaan dalam s
terpisah(lainnya)Kembalikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _56 jika himpunan tidak memiliki elemen yang sama dengan yang lain. Himpunan-himpunan saling lepas jika dan hanya jika perpotongannya adalah himpunan kosong
subset(lainnya)diatur lainnyaUji apakah himpunan tersebut merupakan superset yang tepat dari yang lain, yaitu, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 121
serikat(*lainnya)set | lainnya . .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') --> 6 128 demi def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 129 yang lebih mudah dibaca
Keduanya dan dukungan diatur untuk mengatur perbandingan. Dua himpunan adalah sama jika dan hanya jika setiap elemen dari setiap himpunan terkandung dalam yang lain (masing-masing merupakan subhimpunan dari yang lain). Himpunan kurang dari himpunan lain jika dan hanya jika himpunan pertama adalah himpunan bagian yang tepat dari himpunan kedua (adalah himpunan bagian, tetapi tidak sama). Himpunan lebih besar dari himpunan lain jika dan hanya jika himpunan pertama adalah superset yang tepat dari himpunan kedua (adalah superset, tetapi tidak sama)
Contoh dibandingkan dengan contoh berdasarkan anggotanya. Misalnya, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 134 mengembalikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56 dan begitu juga def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 136
Perbandingan subset dan kesetaraan tidak digeneralisasikan ke fungsi pengurutan total. For example, any two nonempty disjoint sets are not equal and are not subsets of each other, so all of the following return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 138, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 139, atau def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 140
Karena set hanya menentukan pengurutan parsial (hubungan subset), output dari metode ini tidak ditentukan untuk daftar set
Setel elemen, seperti kunci kamus, harus
Operasi biner yang menggabungkan instance dengan mengembalikan tipe operan pertama. Misalnya. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _144 mengembalikan instance dari
Tabel berikut mencantumkan operasi yang tersedia untuk yang tidak berlaku untuk instance yang tidak dapat diubah
perbarui(*lainnya)set |= lainnya . .Perbarui set, tambahkan elemen dari yang lainnya
intersection_update(*lainnya)set &= other & ...Perbarui set, pertahankan hanya elemen yang ditemukan di dalamnya dan yang lainnya
difference_update(*lainnya)set -= other | .Perbarui set, hapus elemen yang ditemukan di orang lain
symmetric_difference_update(other)set ^= 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()Hapus dan kembalikan elemen arbitrer dari set. Raises if the set is empty
jelas()Hapus semua elemen dari set
Perhatikan, versi non-operator dari , , , dan metode akan menerima iterable apa pun sebagai argumen
Perhatikan, argumen elem ke >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 00, , dan metode mungkin satu set. Untuk mendukung pencarian frozenset yang setara, yang sementara dibuat dari elem
Jenis Pemetaan —
Objek memetakan nilai ke objek arbitrer. Pemetaan adalah objek yang bisa berubah. Saat ini hanya ada satu jenis pemetaan standar, kamus. (Untuk container lain lihat built-in , , dan class, dan module. )
Kunci kamus adalah nilai yang hampir sewenang-wenang. Nilai yang bukan , yaitu nilai yang berisi daftar, kamus, atau tipe lain yang dapat diubah (yang dibandingkan dengan nilai, bukan dengan identitas objek) tidak boleh digunakan sebagai kunci. Nilai yang membandingkan sama (seperti def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _55, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 163, dan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56) dapat digunakan secara bergantian untuk mengindeks entri kamus yang sama
kelas dikt(**kwargs)class dict(mapping, **kwargs)class dict(iterable, **kwargs)Mengembalikan kamus baru yang diinisialisasi dari argumen posisi opsional dan kumpulan argumen kata kunci yang mungkin kosong
Kamus dapat dibuat dengan beberapa cara
Gunakan daftar def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 165 pasangan yang dipisahkan koma di dalam kurung kurawal. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 166 atau def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 167
Use a dict comprehension. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 50, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 169
Gunakan konstruktor tipe. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 170, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 171, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 172
Jika tidak ada argumen posisi yang diberikan, kamus kosong akan dibuat. Jika argumen posisi diberikan dan itu adalah objek pemetaan, kamus dibuat dengan pasangan kunci-nilai yang sama dengan objek pemetaan. Jika tidak, argumen posisi harus berupa objek. Setiap item dalam iterable harus merupakan iterable dengan tepat dua objek. Objek pertama dari setiap item menjadi kunci dalam kamus baru, dan objek kedua menjadi nilai yang sesuai. Jika kunci muncul lebih dari sekali, nilai terakhir untuk kunci tersebut menjadi nilai yang sesuai di kamus baru
Jika argumen kata kunci diberikan, argumen kata kunci dan nilainya ditambahkan ke kamus yang dibuat dari argumen posisi. Jika kunci yang ditambahkan sudah ada, nilai dari argumen kata kunci menggantikan nilai dari argumen posisi
Sebagai ilustrasi, contoh berikut semua mengembalikan kamus sama dengan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 173
>>> (-2.0).is_integer() True >>> (3.2).is_integer() False _9
Memberikan argumen kata kunci seperti pada contoh pertama hanya berfungsi untuk kunci yang merupakan pengidentifikasi Python yang valid. Jika tidak, kunci apa pun yang valid dapat digunakan
Ini adalah operasi yang didukung kamus (dan oleh karena itu, jenis pemetaan khusus juga harus didukung)
daftar(d)Mengembalikan daftar semua kunci yang digunakan dalam kamus d
meminjamkan)Return the number of items in the dictionary d
d[kunci]Kembalikan item d dengan key key. Menimbulkan jika kunci tidak ada di peta
Jika subkelas dict mendefinisikan metode def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 175 dan kunci tidak ada, operasi def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 176 memanggil metode itu dengan kunci kunci sebagai argumen. Operasi def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 176 kemudian mengembalikan atau menaikkan apa pun yang dikembalikan atau dimunculkan oleh panggilan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 178. Tidak ada operasi atau metode lain yang memanggil def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 175. Jika def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _175 tidak ditentukan, dinaikkan. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _175 harus menjadi metode;
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _00
Contoh di atas menunjukkan bagian dari implementasi. Metode def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _184 yang berbeda digunakan oleh
d[key] = nilaiTetapkan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _176 ke nilai
del d[key]Hapus def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _176 dari d. Menimbulkan jika kunci tidak ada di peta
kunci di dKembalikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _56 jika d memiliki kunci kunci, selain itu def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38
kunci bukan di dEquivalent to def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 191
iter(d)Kembalikan iterator di atas kunci kamus. Ini adalah jalan pintas untuk def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _192
jelas()Hapus semua item dari kamus
salin()Kembalikan salinan kamus yang dangkal
classmethod fromkeys(dapat diubah[, value])Buat kamus baru dengan kunci dari iterable dan nilai disetel ke nilai
adalah metode kelas yang mengembalikan kamus baru. nilai default ke def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _31. Semua nilai merujuk hanya pada satu contoh, jadi umumnya tidak masuk akal jika nilai menjadi objek yang dapat diubah seperti daftar kosong. Untuk mendapatkan nilai yang berbeda, gunakan a sebagai gantinya
dapatkan(kunci[ , default])Kembalikan nilai untuk kunci jika kunci ada di kamus, kalau tidak default. Jika default tidak diberikan, defaultnya adalah def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31, sehingga metode ini tidak pernah memunculkan
item()Kembalikan tampilan baru item kamus (def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 197 pasang). Lihat
kunci()Return a new view of the dictionary’s keys. Lihat
pop(key[ , default])Jika kunci ada di kamus, hapus dan kembalikan nilainya, jika tidak, kembalikan default. Jika default tidak diberikan dan kunci tidak ada dalam kamus, a dimunculkan
popitem()Hapus dan kembalikan pasangan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _197 dari kamus. Pasangan dikembalikan dalam urutan LIFO
berguna untuk mengulang kamus secara destruktif, seperti yang sering digunakan dalam algoritme set. Jika kamus kosong, pemanggilan memunculkan a
Berubah di versi 3. 7. Pesanan LIFO sekarang dijamin. Di versi sebelumnya, akan mengembalikan pasangan kunci/nilai arbitrer.
terbalik(d)Kembalikan iterator terbalik di atas kunci kamus. Ini adalah jalan pintas untuk def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _204
New in version 3. 8
setdefault(kunci[ , default])Jika kunci ada di kamus, kembalikan nilainya. Jika tidak, masukkan kunci dengan nilai default dan kembalikan default. default defaults to def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31
perbarui([lainnya])Perbarui kamus dengan pasangan kunci/nilai dari yang lain, menimpa kunci yang sudah ada. Kembalikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _31
menerima objek kamus lain atau iterable dari pasangan kunci/nilai (sebagai tupel atau iterable lainnya dengan panjang dua). Jika argumen kata kunci ditentukan, kamus kemudian diperbarui dengan pasangan kunci/nilai tersebut. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _208
nilai()Kembalikan tampilan baru dari nilai kamus. Lihat
Perbandingan kesetaraan antara satu tampilan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 209 dan lainnya akan selalu mengembalikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38. Ini juga berlaku saat membandingkan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _209 dengan dirinya sendiri
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _01
d . lainnyaBuat kamus baru dengan gabungan kunci dan nilai d dan lainnya, yang keduanya harus berupa kamus. Nilai-nilai lain diprioritaskan ketika d dan kunci berbagi lainnya
New in version 3. 9
d . = lainnyaPerbarui kamus d dengan kunci dan nilai dari yang lain, yang dapat berupa a atau an dari pasangan kunci/nilai. The values of other take priority when d and other share keys
New in version 3. 9
Dictionaries compare equal if and only if they have the same def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 197 pairs (regardless of ordering). Order comparisons (‘’) raise .
Kamus mempertahankan urutan penyisipan. Perhatikan bahwa memperbarui kunci tidak memengaruhi urutan. Kunci yang ditambahkan setelah penghapusan dimasukkan di bagian akhir
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _02
Berubah di versi 3. 7. Urutan kamus dijamin menjadi urutan penyisipan. Perilaku ini merupakan detail implementasi CPython dari 3. 6.
Tampilan kamus dan kamus dapat dibalik
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _03
Berubah di versi 3. 8. Kamus sekarang dapat dibalik.
Lihat juga
dapat digunakan untuk membuat tampilan read-only dari a
Objek tampilan kamus
Objek yang dikembalikan oleh , dan adalah objek tampilan. Mereka memberikan tampilan dinamis pada entri kamus, yang berarti bahwa saat kamus berubah, tampilan mencerminkan perubahan ini
Tampilan kamus dapat diulangi untuk menghasilkan datanya masing-masing, dan mendukung pengujian keanggotaan
len(tampilan dikt)Kembalikan jumlah entri dalam kamus
iter(dictview)Mengembalikan iterator di atas kunci, nilai, atau item (diwakili sebagai tupel def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 197) di kamus
Kunci dan nilai diulang dalam urutan penyisipan. Ini memungkinkan pembuatan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _220 pasang menggunakan. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _222. Cara lain untuk membuat daftar yang sama adalah def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 223
Mengulangi tampilan sambil menambahkan atau menghapus entri dalam kamus dapat meningkatkan atau gagal mengulang semua entri
Berubah di versi 3. 7. Urutan kamus dijamin menjadi urutan penyisipan.
x in 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') --> 6 197)
terbalik (dictview)Mengembalikan iterator terbalik di atas kunci, nilai, atau item kamus. Tampilan akan diulang dalam urutan terbalik dari penyisipan
Berubah di versi 3. 8. Tampilan kamus kini dapat dibalik.
dictview. pemetaanKembalikan a yang membungkus kamus asli yang dirujuk oleh tampilan
New in version 3. 10
Tampilan kunci seperti set karena entri mereka unik dan dapat di-hash. Jika semua nilai dapat di-hash, sehingga def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _197 pasangan unik dan dapat di-hash, maka tampilan item juga seperti set. (Tampilan nilai tidak diperlakukan sebagai set-like karena entri umumnya tidak unik. ) Untuk tampilan set-like, semua operasi yang ditentukan untuk kelas dasar abstrak tersedia (misalnya, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 78, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 74, atau def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 232)
Contoh penggunaan tampilan kamus
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 04
Jenis Manajer Konteks
Pernyataan Python mendukung konsep konteks runtime yang ditentukan oleh pengelola konteks. Ini diimplementasikan menggunakan sepasang metode yang memungkinkan kelas yang ditentukan pengguna untuk menentukan konteks runtime yang dimasukkan sebelum badan pernyataan dieksekusi dan keluar saat pernyataan berakhir
pengelola konteks. __masuk__()Masukkan konteks runtime dan kembalikan objek ini atau objek lain yang terkait dengan konteks runtime. Nilai yang dikembalikan oleh metode ini terikat pada pengidentifikasi dalam klausa def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 234 menggunakan manajer konteks ini
Contoh manajer konteks yang mengembalikan dirinya sendiri adalah a. Objek file mengembalikan dirinya sendiri dari __enter__() agar dapat digunakan sebagai ekspresi konteks dalam pernyataan
Contoh pengelola konteks yang mengembalikan objek terkait adalah yang dikembalikan oleh. Manajer ini menyetel konteks desimal aktif ke salinan konteks desimal asli dan kemudian mengembalikan salinannya. Ini memungkinkan perubahan dilakukan pada konteks desimal saat ini di badan pernyataan tanpa memengaruhi kode di luar pernyataan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 081
pengelola konteks. __exit__(exc_type , exc_val, exc_tb)Keluar dari konteks runtime dan kembalikan flag Boolean yang menunjukkan jika ada pengecualian yang terjadi harus ditekan. Jika pengecualian terjadi saat menjalankan isi pernyataan, argumen berisi jenis pengecualian, nilai, dan informasi traceback. Jika tidak, ketiga argumen tersebut adalah def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31
Mengembalikan nilai sebenarnya dari metode ini akan menyebabkan pernyataan menekan pengecualian dan melanjutkan eksekusi dengan pernyataan segera setelah pernyataan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 081. Otherwise the exception continues propagating after this method has finished executing. Pengecualian yang terjadi selama eksekusi metode ini akan menggantikan setiap pengecualian yang terjadi di badan pernyataan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 081
Pengecualian yang diteruskan tidak boleh dimunculkan kembali secara eksplisit - sebagai gantinya, metode ini harus mengembalikan nilai salah untuk menunjukkan bahwa metode berhasil diselesaikan dan tidak ingin menekan pengecualian yang dimunculkan. Ini memungkinkan kode manajemen konteks untuk dengan mudah mendeteksi apakah suatu metode benar-benar gagal atau tidak
Python mendefinisikan beberapa manajer konteks untuk mendukung sinkronisasi utas yang mudah, penutupan cepat file atau objek lain, dan manipulasi yang lebih sederhana dari konteks aritmatika desimal aktif. Jenis spesifik tidak diperlakukan secara khusus di luar penerapan protokol manajemen konteksnya. Lihat modul untuk beberapa contoh
Python dan dekorator menyediakan cara mudah untuk mengimplementasikan protokol ini. Jika fungsi generator didekorasi dengan dekorator, itu akan mengembalikan manajer konteks yang mengimplementasikan metode yang diperlukan dan, daripada iterator yang dihasilkan oleh fungsi generator yang tidak didekorasi
Perhatikan bahwa tidak ada slot khusus untuk salah satu metode ini dalam struktur tipe untuk objek Python di Python/C API. Jenis ekstensi yang ingin mendefinisikan metode ini harus menyediakannya sebagai metode normal yang dapat diakses Python. Dibandingkan dengan biaya tambahan untuk menyiapkan konteks runtime, biaya tambahan dari pencarian kamus kelas tunggal dapat diabaikan
Ketik Jenis Anotasi — ,
Tipe bawaan inti untuk adalah dan
Tipe Alias Generik
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _252 objek umumnya dibuat oleh sebuah kelas. Mereka paling sering digunakan dengan , seperti atau. For example, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 255 is a def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 252 object created by subscripting the def bit_count(self): return bin(self).count("1") 93 class with the argument . def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _252 objek dimaksudkan terutama untuk digunakan bersama
Catatan
Biasanya hanya mungkin untuk membuat subskrip kelas jika kelas tersebut mengimplementasikan metode khusus
Objek def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _252 bertindak sebagai proxy untuk a , mengimplementasikan generik berparameter
Untuk kelas wadah, argumen yang diberikan ke salah satu kelas dapat menunjukkan jenis elemen yang dikandung objek. Misalnya, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _262 dapat digunakan dalam anotasi tipe untuk menandakan a yang semua elemennya bertipe
Untuk kelas yang mendefinisikan tetapi bukan wadah, argumen yang diberikan ke langganan kelas akan sering menunjukkan tipe kembalian dari satu atau lebih metode yang didefinisikan pada objek. Misalnya, dapat digunakan pada tipe data dan tipe data
Jika def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _269, >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 82 akan menjadi objek di mana nilai pengembalian def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 271 dan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 272 keduanya akan bertipe. Kita dapat merepresentasikan objek semacam ini dalam anotasi tipe dengan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 252 def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 275
Jika def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 276, (perhatikan def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n 47 untuk ), def bit_count(self): return bin(self).count("1") 31 juga akan menjadi turunan dari def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 280, tetapi nilai pengembalian def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 281 dan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 282 akan bertipe. Dalam anotasi tipe, kami akan mewakili variasi objek ini dengan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 284
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _252 objek adalah turunan dari kelas, yang juga dapat digunakan untuk membuat objek def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 252 secara langsung
T[X, Y, . ]Membuat def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _252 yang mewakili tipe def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 289 yang diparameterisasi oleh tipe X, Y, dan lainnya bergantung pada def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 289 yang digunakan. Misalnya, sebuah fungsi mengharapkan elemen yang mengandung
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _05
Contoh lain untuk objek, menggunakan a , yang merupakan tipe generik yang mengharapkan dua parameter tipe yang mewakili tipe kunci dan tipe nilai. Dalam contoh ini, fungsi mengharapkan >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 68 dengan kunci tipe dan nilai tipe
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _06
Fungsi bawaan dan tidak menerima tipe def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 252 untuk argumen kedua mereka
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _07
Runtime Python tidak berlaku. Ini meluas ke tipe generik dan parameter tipenya. Saat membuat objek wadah dari def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _252, elemen dalam wadah tidak dicentang berdasarkan jenisnya. Misalnya, kode berikut tidak dianjurkan, tetapi akan berjalan tanpa kesalahan
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _08
Selanjutnya, parameter generik menghapus parameter tipe selama pembuatan objek
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _09
Memanggil atau pada generik menunjukkan tipe parameter
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _10
Metode wadah umum akan memunculkan pengecualian untuk melarang kesalahan seperti def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 304
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _11
Namun, ekspresi seperti itu valid saat digunakan. Indeks harus memiliki elemen sebanyak item variabel tipe dalam objek def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 252
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _12
Kelas Generik Standar
Kelas pustaka standar berikut mendukung generik berparameter. This list is non-exhaustive
Atribut Khusus dari def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 252 objek
Semua obat generik berparameter mengimplementasikan atribut read-only khusus
generikal. __origin__Atribut ini menunjuk pada kelas generik non-parameter
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _13
generikal. __args__Atribut ini adalah (mungkin dengan panjang 1) dari tipe generik yang diteruskan ke kelas generik asli
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _14
generikal. __parameters__Atribut ini adalah tuple yang dihitung dengan malas (mungkin kosong) dari variabel tipe unik yang ditemukan di def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 306
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _15
Catatan
Objek def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _252 dengan parameter mungkin tidak benar def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 365 setelah substitusi karena dimaksudkan terutama untuk pemeriksaan tipe statis
generikal. __unpacked__Boolean yang benar jika alias telah dibongkar menggunakan operator >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' 00 (lihat )
Baru di versi 3. 11
Lihat juga
PEP 484 - Type HintsMemperkenalkan kerangka kerja Python untuk anotasi tipe
PEP 585 - Ketik Generik Petunjuk Dalam Koleksi StandarMemperkenalkan kemampuan untuk membuat parameter kelas perpustakaan standar secara native, asalkan mereka menerapkan metode kelas khusus
, DanDokumentasi tentang cara mengimplementasikan kelas generik yang dapat diparameterisasi saat runtime dan dipahami oleh pemeriksa tipe statis
New in version 3. 9
Tipe Serikat
Objek gabungan memegang nilai operasi def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 371 (bitwise atau) pada banyak. Jenis ini dimaksudkan terutama untuk. Ekspresi tipe gabungan memungkinkan sintaks petunjuk tipe yang lebih bersih dibandingkan dengan
X . Y . .Mendefinisikan objek gabungan yang menampung tipe X, Y, dan seterusnya. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _373 berarti X atau Y. Ini setara dengan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _374. Misalnya, fungsi berikut mengharapkan argumen bertipe or
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _16
union_object == lainnyaUnion objects can be tested for equality with other union objects. Details
isinstance(obj, union_object)issubclass(obj, union_object)
Serikat pekerja diratakan
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _17
Jenis redundan dihapus
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _18
Saat membandingkan serikat pekerja, pesanan diabaikan
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _19
Ini kompatibel dengan
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _20
Jenis opsional dapat dieja sebagai gabungan dengan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _21
Panggilan ke dan juga didukung dengan objek gabungan
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _22
Namun, objek gabungan yang berisi tidak dapat digunakan
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _23
Jenis yang terpapar pengguna untuk objek gabungan dapat diakses dari dan digunakan untuk pemeriksaan. Objek tidak dapat dibuat dari jenisnya
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _24
Catatan
Metode def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 383 untuk objek tipe ditambahkan untuk mendukung sintaks def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 373. Jika metaclass mengimplementasikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _383, Union dapat menimpanya
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 25
Lihat juga
PEP 604 – PEP mengusulkan sintaks def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 373 dan tipe Union
New in version 3. 10
Jenis Bawaan Lainnya
Penerjemah mendukung beberapa jenis objek lainnya. Sebagian besar hanya mendukung satu atau dua operasi
Modul
Satu-satunya operasi khusus pada modul adalah akses atribut. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 387, di mana m adalah modul dan nama mengakses nama yang didefinisikan dalam tabel simbol m. Atribut modul dapat ditugaskan ke. (Perhatikan bahwa pernyataan tersebut bukan, sebenarnya, operasi pada objek modul; def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 389 tidak memerlukan objek modul bernama foo untuk ada, melainkan membutuhkan definisi (eksternal) untuk modul bernama foo di suatu tempat. )
Atribut khusus dari setiap modul adalah. Ini adalah kamus yang berisi tabel simbol modul. Memodifikasi kamus ini sebenarnya akan mengubah tabel simbol modul, tetapi penugasan langsung ke atribut tidak dimungkinkan (Anda dapat menulis def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 392, yang mendefinisikan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 393 menjadi def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 55, tetapi Anda tidak dapat menulis def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 395). Memodifikasi secara langsung tidak disarankan
Modul yang dibangun ke dalam juru bahasa ditulis seperti ini. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _397. Jika diambil dari file, ditulis sebagai def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 398
Kelas dan Contoh Kelas
Lihat dan untuk ini
Fungsi
Function objects are created by function definitions. Satu-satunya operasi pada objek fungsi adalah memanggilnya. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _399
Sebenarnya ada dua jenis objek fungsi. built-in functions and user-defined functions. Both support the same operation (to call the function), but the implementation is different, hence the different object types
Lihat untuk informasi lebih lanjut
Metode
Metode adalah fungsi yang dipanggil menggunakan notasi atribut. There are two flavors. built-in methods (such as def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 400 on lists) and class instance methods. Built-in methods are described with the types that support them
If you access a method (a function defined in a class namespace) through an instance, you get a special object. a bound method (also called instance method) object. When called, it will add the def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 401 argument to the argument list. Metode terikat memiliki dua atribut read-only khusus. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _402 adalah objek tempat metode beroperasi, dan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 403 adalah fungsi yang mengimplementasikan metode. Memanggil def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 404 sama persis dengan menelepon def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 405
Seperti objek fungsi, objek metode terikat mendukung mendapatkan atribut arbitrer. Namun, karena atribut metode sebenarnya disimpan pada objek fungsi yang mendasarinya (def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 406), menyetel atribut metode pada metode terikat tidak diperbolehkan. Mencoba untuk mengatur atribut pada hasil metode dimunculkan. Untuk menyetel atribut metode, Anda perlu menyetelnya secara eksplisit pada objek fungsi yang mendasarinya
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _26
Lihat untuk informasi lebih lanjut
Objek Kode
Objek kode digunakan oleh implementasi untuk mewakili kode Python yang dapat dieksekusi “pseudo-compiled” seperti badan fungsi. Mereka berbeda dari objek fungsi karena tidak berisi referensi ke lingkungan eksekusi globalnya. Code objects are returned by the built-in function and can be extracted from function objects through their def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 409 attribute. Lihat juga modul
Mengakses def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _409 memunculkan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 412 dengan argumen def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 413 dan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 414
Objek kode dapat dieksekusi atau dievaluasi dengan meneruskannya (alih-alih string sumber) ke atau fungsi bawaan
Lihat untuk informasi lebih lanjut
Ketik Objek
Jenis objek mewakili berbagai jenis objek. Jenis objek diakses oleh fungsi bawaan. Tidak ada operasi khusus pada tipe. Modul standar menentukan nama untuk semua tipe bawaan standar
Jenis ditulis seperti ini. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _419
Objek Null
Objek ini dikembalikan oleh fungsi yang tidak mengembalikan nilai secara eksplisit. Ini tidak mendukung operasi khusus. Tepatnya ada satu objek nol, bernama def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 31 (nama bawaan). def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _421 menghasilkan singleton yang sama
Itu ditulis sebagai def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _31
Objek Ellipsis
Objek ini biasa digunakan dengan mengiris (lihat ). Ini tidak mendukung operasi khusus. Tepatnya ada satu objek elipsis, bernama (nama bawaan). def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 424 produces the singleton
Itu ditulis sebagai def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _423 atau def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 427
Objek NotImplemented
Objek ini dikembalikan dari perbandingan dan operasi biner ketika mereka diminta untuk beroperasi pada jenis yang tidak mereka dukung. Lihat untuk informasi lebih lanjut. Tepatnya ada satu objek def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _428. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _429 menghasilkan instance tunggal
Itu ditulis sebagai def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _428
Nilai Boolean
Nilai Boolean adalah dua objek konstan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 dan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56. Mereka digunakan untuk mewakili nilai kebenaran (walaupun nilai lain juga dapat dianggap salah atau benar). Dalam konteks numerik (misalnya ketika digunakan sebagai argumen untuk operator aritmatika), masing-masing berperilaku seperti bilangan bulat 0 dan 1. Fungsi bawaan dapat digunakan untuk mengonversi nilai apa pun menjadi Boolean, jika nilainya dapat diartikan sebagai nilai kebenaran (lihat bagian di atas)
Mereka masing-masing ditulis sebagai def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 38 dan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 56
Objek Internal
Lihat untuk informasi ini. Ini menggambarkan objek bingkai tumpukan, objek traceback, dan objek irisan
Atribut Khusus
Implementasinya menambahkan beberapa atribut read-only khusus ke beberapa tipe objek, jika relevan. Beberapa di antaranya tidak dilaporkan oleh fungsi bawaan
objek. __dict__Kamus atau objek pemetaan lain yang digunakan untuk menyimpan atribut objek (dapat ditulis).
contoh. __kelas__Kelas tempat instance kelas berada
kelas. __basis__Tuple kelas dasar dari objek kelas
definisi. __nama__Nama kelas, fungsi, metode, deskriptor, atau instance generator
definisi. __qualname__Kelas, fungsi, metode, deskriptor, atau instance generator
Baru di versi 3. 3
kelas. __mro__Atribut ini adalah kumpulan kelas yang dipertimbangkan saat mencari kelas dasar selama resolusi metode
kelas. mro()Metode ini dapat diganti oleh metaclass untuk menyesuaikan urutan resolusi metode untuk instansnya. Ini disebut pada instantiasi kelas, dan hasilnya disimpan di
kelas. __subkelas__()Setiap kelas menyimpan daftar referensi lemah ke subkelas langsungnya. Metode ini mengembalikan daftar semua referensi yang masih hidup. Daftar ini dalam urutan definisi. Contoh
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _27
Batasan panjang konversi string bilangan bulat
CPython memiliki batas global untuk mengonversi antara dan untuk memitigasi penolakan serangan layanan. Batasan ini hanya berlaku untuk basis angka desimal atau non-pangkat-dua lainnya. Konversi heksadesimal, oktal, dan biner tidak terbatas. Batasnya dapat dikonfigurasi
Jenis dalam Python adalah angka panjang acak yang disimpan dalam bentuk biner (umumnya dikenal sebagai "bignum"). Tidak ada algoritma yang dapat mengubah string menjadi bilangan bulat biner atau bilangan bulat biner menjadi string dalam waktu linier, kecuali basisnya adalah kekuatan 2. Bahkan algoritma paling terkenal untuk basis 10 memiliki kompleksitas sub-kuadrat. Mengonversi nilai besar seperti def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _441 dapat memakan waktu lebih dari satu detik pada CPU yang cepat
Membatasi ukuran konversi menawarkan cara praktis untuk menghindari CVE-2020-10735
Batas diterapkan pada jumlah karakter digit dalam string input atau output ketika algoritma konversi non-linear akan dilibatkan. Underscores and the sign are not counted towards the limit
Ketika suatu operasi akan melebihi batas, a dinaikkan
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _28
Batas default adalah 4300 digit seperti yang disediakan di. Batas terendah yang dapat dikonfigurasi adalah 640 digit seperti yang disediakan di
Verifikasi
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _29
Baru di versi 3. 11
API yang terpengaruh
Pembatasan hanya berlaku untuk konversi yang berpotensi lambat antara dan atau
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _448 dengan basis default 10
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _449 untuk semua basis yang bukan pangkat 2
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _450
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _451
konversi string lainnya ke basis 10, misalnya def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 452, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 453, atau def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 454
Batasan tidak berlaku untuk fungsi dengan algoritme linier
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _449 dengan basis 2, 4, 8, 16, atau 32
Dan
, ,
untuk bilangan hex, oktal, dan biner
ke
ke
Konfigurasi batas
Before Python starts up you can use an environment variable or an interpreter command line flag to configure the limit
, e. g. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _466 untuk menetapkan batas ke 640 atau def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 467 untuk menonaktifkan batasan
, e. g. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _469
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _470 berisi nilai atau. Jika env var dan opsi def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _473 disetel, opsi def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 473 diutamakan. Nilai -1 menunjukkan bahwa keduanya tidak disetel, sehingga nilai def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 443 digunakan selama inisialisasi
Dari kode, Anda dapat memeriksa batas saat ini dan menetapkan batas baru menggunakan API ini
dan merupakan pengambil dan penyetel untuk batas lebar juru bahasa. Subinterpreter memiliki batasnya sendiri
Informasi tentang default dan minimum dapat ditemukan di
adalah batas default yang dikompilasi
adalah nilai terendah yang diterima untuk batas (selain 0 yang menonaktifkannya)
Baru di versi 3. 11
Peringatan
Menetapkan batas rendah dapat menyebabkan masalah. Meskipun jarang, ada kode yang berisi konstanta integer dalam desimal di sumbernya yang melebihi ambang batas minimum. Konsekuensi dari pengaturan batas adalah bahwa kode sumber Python yang berisi literal bilangan bulat desimal lebih lama dari batas akan mengalami kesalahan selama penguraian, biasanya pada waktu startup atau waktu impor atau bahkan pada waktu instalasi - kapan saja def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 482 yang diperbarui belum ada untuk . A workaround for source that contains such large constants is to convert them to def bit_count(self): return bin(self).count("1") 12 hexadecimal form as it has no limit
Uji aplikasi Anda secara menyeluruh jika Anda menggunakan batas rendah. Pastikan pengujian Anda berjalan dengan batas yang ditetapkan lebih awal melalui lingkungan atau tanda sehingga itu berlaku selama startup dan bahkan selama langkah instalasi apa pun yang dapat memanggil Python untuk melakukan prekompilasi def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 484 sumber ke def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 482 file
Konfigurasi yang disarankan
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _443 default diharapkan wajar untuk sebagian besar aplikasi. Jika aplikasi Anda memerlukan batas yang berbeda, setel dari titik masuk utama Anda menggunakan kode agnostik versi Python karena API ini ditambahkan dalam rilis patch keamanan di versi sebelum 3. 11
Example
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _30
Jika Anda perlu menonaktifkannya sepenuhnya, setel ke def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 42
Catatan kaki
Informasi tambahan tentang metode khusus ini dapat ditemukan di Manual Referensi Python ()
Akibatnya, daftar def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 _488 dianggap sama dengan def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 489, dan demikian pula untuk tupel
Mereka harus memilikinya karena parser tidak dapat mengetahui jenis operan
4(,,,)Karakter huruf kapital adalah karakter dengan properti kategori umum menjadi salah satu dari "Lu" (Huruf, huruf besar), "Ll" (Huruf, huruf kecil), atau "Lt" (Huruf, huruf judul)
5(,)Untuk memformat tuple saja, Anda harus menyediakan tuple tunggal yang satu-satunya elemennya adalah tuple yang akan diformat
Bagaimana cara mengubah string menjadi array biner dengan Python?
Untuk mengonversi string ke biner, pertama-tama kita menambahkan nilai ASCII individual string ke daftar ( l ) menggunakan fungsi ord(_string). This function gives the ASCII value of the string (i.e., ord(H) = 72 , ord(e) = 101). Then, from the list of ASCII values we can convert them to binary using bin(_integer) .How do you convert a string to a byte array in Python?
We can use the built-in Bytes class in Python to convert a string to bytes. cukup teruskan string sebagai input pertama dari konstruktor kelas Bytes dan kemudian teruskan penyandian sebagai argumen kedua . Mencetak objek menunjukkan representasi tekstual yang mudah digunakan, tetapi data yang terkandung di dalamnya dalam byte.Bagaimana cara mengonversi string menjadi array array dengan Python?
Anda melakukannya dengan menggunakan fungsi list() bawaan dan meneruskan string yang diberikan sebagai argumen ke fungsi . Teks " Belajar Python. " memiliki spasi putih di depan dan di belakang, spasi putih di antara kata "Belajar" dan "Python", dan spasi putih di antara kata "Python" dan tanda seru.Bagaimana cara mengubah string biner menjadi bilangan bulat dengan Python?
Dalam hal ini, kita menggunakan fungsi bawaan yang disebut int . Fungsi ini mengambil string yang ingin kita ubah sebagai argumen pertama dan basis angka sebagai argumen kedua. Karena di sini kita berurusan dengan bilangan biner, maka basisnya adalah 2. Metode ini kemudian mengembalikan nilai integer dari string biner.