Toán tử logic nào không thể được sử dụng với chuỗi trong Python?
Một số lớp bộ sưu tập có thể thay đổi. Các phương thức cộng, trừ hoặc sắp xếp lại các thành viên của chúng tại chỗ và không trả về một mục cụ thể, không bao giờ trả về chính thể hiện của bộ sưu tập nhưng def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631 Show
Một số hoạt động được hỗ trợ bởi một số loại đối tượng; . Hàm thứ hai được sử dụng ngầm khi một đối tượng được viết bởi hàm Kiểm tra giá trị thậtBất kỳ đối tượng nào cũng có thể được kiểm tra giá trị thực, để sử dụng trong một hoặc điều kiện hoặc dưới dạng toán hạng của các phép toán Boolean bên dưới Theo mặc định, một đối tượng được coi là đúng trừ khi lớp của nó định nghĩa phương thức def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 637 trả về def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 hoặc phương thức def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 639 trả về 0 khi được gọi với đối tượng. Dưới đây là hầu hết các đối tượng tích hợp được coi là sai
Các phép toán và hàm dựng sẵn có kết quả Boolean luôn trả về def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 642 hoặc def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 nếu sai và def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 655 hoặc def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 nếu đúng, trừ khi có quy định khác. (Ngoại lệ quan trọng. các phép toán Boolean def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 657 và def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 658 luôn trả về một trong các toán hạng của chúng. ) Phép toán Boolean — def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 58, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 57, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6 61Đây là các phép toán Boolean, được sắp xếp theo mức độ ưu tiên tăng dần Hoạt động Kết quả ghi chú def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 662 nếu x sai, thì y, ngược lại 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') --> 663 nếu x sai, thì x, ngược lại 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') --> 664 nếu x sai, thì def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656, ngược lại thì def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 (3) ghi chú
so sánhCó tám thao tác so sánh trong Python. Tất cả chúng đều có cùng mức độ ưu tiên (cao hơn so với các phép toán Boolean). So sánh có thể được xâu chuỗi tùy ý; Bảng này tóm tắt các hoạt động so sánh Hoạt động Nghĩ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') --> 674 hoàn toàn ít hơn def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 675 nhỏ hơn hoặc bằng def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 676 tuyệt đối lớn hơn def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 677 lớn hơn hoặc bằng def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 678 bình đẳng def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 679 không công bằng def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 680 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') --> 681 negated object identity Các đối tượng thuộc các loại khác nhau, ngoại trừ các loại số khác nhau, không bao giờ so sánh bằng nhau. 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') --> 678 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') --> 674, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 675, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 676 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') --> 677 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() 300 method Numeric Types — , ,There are three distinct numeric types. integers, floating point numbers, and complex numbers. In addition, Booleans are a subtype of integers. Integers have unlimited precision. Floating point numbers are usually implemented using double in C; information about the precision and internal representation of floating point numbers for the machine on which your program is running is available in . Complex numbers have a real and imaginary part, which are each a floating point number. To extract these parts from a complex number z, use >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 305 and >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 306. (The standard library includes the additional numeric types , for rationals, and , for floating-point numbers with user-definable precision. ) Numbers are created by numeric literals or as the result of built-in functions and operators. Unadorned integer literals (including hex, octal and binary numbers) yield integers. Numeric literals containing a decimal point or an exponent sign yield floating point numbers. Appending >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 309 or >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 310 to a numeric literal yields an imaginary number (a complex number with a zero real part) which you can add to an integer or float to get a complex number with real and imaginary parts Python fully supports mixed arithmetic. when a binary arithmetic operator has operands of different numeric types, the operand with the “narrower” type is widened to that of the other, where integer is narrower than floating point, which is narrower than complex. A comparison between numbers of different types behaves as though the exact values of those numbers were being compared. The constructors , , and can be used to produce numbers of a specific type All numeric types (except complex) support the following operations (for priorities of the operations, see ) Hoạt động Kết quả ghi chú Full documentation >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 314 sum of x and y >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 315 difference of x and y >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 316 product of x and y >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 317 quotient of x and y >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 318 floored quotient of x and y (1) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 319 phần còn lại của >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 317 (2) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 321 x negated >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 322 x unchanged >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 323 absolute value or magnitude of x >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 325 x converted to integer (3)(6) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 327 x converted to floating point (4)(6) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 329 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() 331 conjugate of the complex number c >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 332 the pair >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 333 (2) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 335 x to the power y (5) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 337 x to the power y (5) ghi chú
All types ( and ) also include the following operations Hoạt động Kết quả x truncated to x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0 the greatest <= x the least >= x For additional numeric operations see the and modules Bitwise Operations on Integer TypesBitwise 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() 368 has the same priority as the other unary numeric operations ( >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 369 and >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 370) This table lists the bitwise operations sorted in ascending priority Hoạt động Kết quả ghi chú >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 371 bitwise or of x and y (4) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 372 bitwise exclusive or of x and y (4) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 373 bitwise and of x and y (4) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 374 x shifted left by n bits (1)(2) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 375 x shifted right by n bits (1)(3) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 376 the bits of x inverted ghi chú
Additional Methods on Integer TypesThe 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 More precisely, if >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 382 is nonzero, then >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 383 is the unique positive integer >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 384 such that >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 385. Equivalently, when >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 323 is small enough to have a correctly rounded logarithm, then >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 387. If >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 382 is zero, then >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 383 returns def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 642 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 is raised if the integer is not representable with the given number of bytes The byteorder argument determines the byte order used to represent the integer, and defaults to >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 392. If byteorder is >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 392, the most significant byte is at the beginning of the byte array. Nếu byteorder là >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 394, thì byte quan trọng nhất nằm ở cuối mảng byte Đối số đã ký xác định xem phần bù của hai có được sử dụng để biểu diễn số nguyên hay không. 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') --> 638 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') --> 638 Các giá trị mặc định có thể được sử dụng để biến một số nguyên thành một đối tượng byte đơn một cách thuận tiện. 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) Mới trong phiên bản 3. 2 Đã thay đổi trong phiên bản 3. 11. Đã thêm các giá trị đối số mặc định cho >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 399 và def bit_count(self): return bin(self).count("1")00. phương thức lớp int. từ_byte(byte , thứ tự byte='big', *, signed=False) Trả về số nguyên được đại diện bởi mảng byte đã cho >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680 Các byte đối số phải là một hoặc một byte tạo ra có thể lặp lại Đối số byteorder xác định thứ tự byte được sử dụng để biểu thị số nguyên và mặc định là >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 392. Nếu thứ tự byte là >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 392, thì byte quan trọng nhất nằm ở đầu mảng byte. Nếu byteorder là >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 394, thì byte quan trọng nhất nằm ở cuối mảng byte. Để yêu cầu thứ tự byte gốc của hệ thống máy chủ, hãy sử dụng làm giá trị thứ tự byte Đối số có dấu cho biết liệu phần bù hai có được sử dụng để biểu diễn số nguyên hay không 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 Mới trong phiên bản 3. 2 Đã thay đổi trong phiên bản 3. 11. Đã thêm giá trị đối số mặc định cho def bit_count(self): return bin(self).count("1")00. int. as_integer_ratio() Trả về một cặp số nguyên có tỷ lệ chính xác bằng số nguyên ban đầu và có mẫu số dương. Tỷ lệ nguyên của các số nguyên (số nguyên) luôn là số nguyên làm tử số và def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 655 làm mẫu số Mới trong phiên bản 3. 8 Phương pháp bổ sung trên FloatKiểu float thực hiện. float cũng có các phương thức bổ sung sau nổi. as_integer_ratio()Trả về một cặp số nguyên có tỷ lệ chính xác bằng số float ban đầu và có mẫu số dương. Tăng trên vô số và trên NaN nổi. is_integer()Trả về def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 nếu đối tượng float là hữu hạn với giá trị nguyên và ngược lại là def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 >>> (-2.0).is_integer() True >>> (3.2).is_integer() False Hai phương pháp hỗ trợ chuyển đổi sang và từ các chuỗi thập lục phân. Vì số float của Python được lưu trữ bên trong dưới dạng số nhị phân, nên việc chuyển đổi số float thành hoặc từ chuỗi thập phân thường liên quan đến một lỗi làm tròn nhỏ. Ngược lại, các chuỗi thập lục phân cho phép biểu diễn và đặc tả chính xác các số dấu phẩy động. Điều này có thể hữu ích khi gỡ lỗi và trong công việc số nổi. hex()Trả về biểu diễn của số dấu phẩy động dưới dạng chuỗi thập lục phân. Đối với các số có dấu phẩy động hữu hạn, biểu diễn này sẽ luôn bao gồm một số ở đầu def bit_count(self): return bin(self).count("1")12 và một số sau ____113_______13 và số mũphương thức lớp phao. từ hex(s) Phương thức lớp để trả về số float được biểu thị bằng chuỗi thập lục phân s. Chuỗi s có thể có khoảng trắng ở đầu và cuối Lưu ý rằng đó là một phương thức cá thể, trong khi đó là một phương thức lớp Một chuỗi thập lục phân có dạng def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 60 trong đó tùy chọn def bit_count(self): return bin(self).count("1")16 có thể bằng cách hoặc là >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 369 hoặc là >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 370, def bit_count(self): return bin(self).count("1")19 và def bit_count(self): return bin(self).count("1")20 là các chuỗi chữ số thập lục phân và def bit_count(self): return bin(self).count("1")21 là số nguyên thập phân có dấu ở đầu tùy chọn. Trường hợp không đáng kể và phải có ít nhất một chữ số thập lục phân trong số nguyên hoặc phân số. Cú pháp này tương tự như cú pháp quy định tại mục 6. 4. 4. 2 của tiêu chuẩn C99 và cả cú pháp được sử dụng trong Java 1. 5 trở đi. Cụ thể, đầu ra của có thể sử dụng dưới dạng ký tự dấu phẩy động thập lục phân trong mã C hoặc Java và các chuỗi thập lục phân được tạo bởi ký tự định dạng __113_______23 của C hoặc ____113_______24 của Java được chấp nhận bởi Lưu ý rằng số mũ được viết dưới dạng thập phân chứ không phải thập lục phân và nó mang lại sức mạnh của 2 để nhân hệ số. Ví dụ: chuỗi thập lục phân def bit_count(self): return bin(self).count("1")26 đại diện cho số dấu phẩy động def bit_count(self): return bin(self).count("1")27 hoặc 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') --> 61 Áp dụng chuyển đổi ngược lại cho def bit_count(self): return bin(self).count("1")28 sẽ cho một chuỗi thập lục phân khác đại diện cho cùng một số def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 62 Băm các loại sốĐối với các số >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 382 và def bit_count(self): return bin(self).count("1")31, có thể thuộc các loại khác nhau, yêu cầu là ____113_______32 bất cứ khi nào def bit_count(self): return bin(self).count("1")33 (xem tài liệu về phương pháp để biết thêm chi tiết). Để dễ triển khai và hiệu quả trên nhiều loại số (bao gồm , và ) Hàm băm của Python cho các loại số dựa trên một hàm toán học duy nhất được xác định cho bất kỳ số hữu tỷ nào và do đó áp dụng cho tất cả các trường hợp của và , và tất cả các trường hợp hữu hạn . Về cơ bản, hàm này được cho bởi modulo rút gọn def bit_count(self): return bin(self).count("1")43 cho số nguyên tố cố định def bit_count(self): return bin(self).count("1")43. Giá trị của def bit_count(self): return bin(self).count("1")43 được cung cấp cho Python dưới dạng thuộc tính def bit_count(self): return bin(self).count("1")46 của Chi tiết triển khai CPython. Hiện tại, số nguyên tố được sử dụng là def bit_count(self): return bin(self).count("1")48 trên các máy có độ dài C 32 bit và def bit_count(self): return bin(self).count("1")49 trên các máy có độ dài C 64 bit Dưới đây là các quy tắc chi tiết
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') --> 63 Iterator TypesPython supports a concept of iteration over containers. This is implemented using two distinct methods; these are used to allow user-defined classes to support iteration. Sequences, described below in more detail, always support the iteration methods One method needs to be defined for container objects to provide support container. __iter__()Trả lại một đối tượng. The object is required to support the iterator protocol described below. Nếu một vùng chứa hỗ trợ các kiểu lặp khác nhau, thì có thể cung cấp các phương thức bổ sung để yêu cầu cụ thể các trình vòng lặp cho các kiểu lặp đó. (An example of an object supporting multiple forms of iteration would be a tree structure which supports both breadth-first and depth-first traversal. ) This method corresponds to the slot of the type structure for Python objects in the Python/C API The iterator objects themselves are required to support the following two methods, which together form the iterator protocol iterator. __iter__()Return the object itself. This is required to allow both containers and iterators to be used with the and statements. This method corresponds to the slot of the type structure for Python objects in the Python/C API iterator. __next__()Return the next item from the . If there are no further items, raise the exception. This method corresponds to the slot of the type structure for Python objects in the Python/C API Python defines several iterator objects to support iteration over general and specific sequence types, dictionaries, and other more specialized forms. The specific types are not important beyond their implementation of the iterator protocol Once an iterator’s method raises , it must continue to do so on subsequent calls. Implementations that do not obey this property are deemed broken Generator TypesPython’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 OperationsThe operations in the following table are supported by most sequence types, both mutable and immutable. The ABC is provided to make it easier to correctly implement these operations on custom sequence types This table lists the sequence operations sorted in ascending priority. In the table, s and t are sequences of the same type, n, i, j and k are integers and x is an arbitrary object that meets any type and value restrictions imposed by s The def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 698 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') --> 699 operations have the same priorities as the comparison operations. The >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 369 (concatenation) and >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'00 (repetition) operations have the same priority as the corresponding numeric operations. Hoạt động Kết quả ghi chú >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'01 def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if an item of s is equal to x, else def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 (1) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'04 def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 if an item of s is equal to x, else def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 (1) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'07 the concatenation of s and t (6)(7) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'08 or >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'09 equivalent to adding s to itself n times (2)(7) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'10 ith item of s, origin 0 (3) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'11 slice of s from i to j (3)(4) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'12 slice of s from i to j with step k (3)(5) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'13 length of s >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'14 mục nhỏ nhất của 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 chỉ số của lần xuất hiện đầu tiên của x trong s (tại hoặc sau chỉ số i và trước chỉ số 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) ghi chú
Immutable Sequence TypesThe only operation that immutable sequence types generally implement that is not also implemented by mutable sequence types is support for the built-in This support allows immutable sequences, such as instances, to be used as keys and stored in and instances Attempting to hash an immutable sequence that contains unhashable values will result in Mutable Sequence TypesThe operations in the following table are defined on mutable sequence types. The ABC is provided to make it easier to correctly implement these operations on custom sequence types In the table s is an instance of a mutable sequence type, t is any iterable object and x is an arbitrary object that meets any type and value restrictions imposed by s (for example, only accepts integers that meet the value restriction >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'74) Hoạt động Kết quả ghi chú >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'75 item i of s is replaced by x >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'76 slice of s from i to j is replaced by the contents of the iterable t >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'77 same as >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'78 >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'79 the elements of >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'12 are replaced by those of t (1) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'81 removes the elements of >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'12 from the list >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'83 appends x to the end of the sequence (same as >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'84) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'85 removes all items from s (same as >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'86) (5) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'87 creates a shallow copy of s (same as >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'88) (5) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'89 or >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'90 extends s with the contents of t (for the most part the same as >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'91) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'92 updates s with its contents repeated n times (6) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'93 inserts x into s at the index given by i (same as >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'94) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'95 or >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'96 retrieves the item at i and also removes it from s (2) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'97 remove the first item from s where >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'10 is equal to x (3) >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'99 reverses the items of s in place (4) ghi chú
ListsLists are mutable sequences, typically used to store collections of homogeneous items (where the precise degree of similarity will vary by application) class list([iterable])Lists may be constructed in several ways
The constructor builds a list whose items are the same and in the same order as iterable’s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a list, a copy is made and returned, similar to >>> (65).to_bytes() b'A'20. For example, >>> (65).to_bytes() b'A'21 returns >>> (65).to_bytes() b'A'22 and >>> (65).to_bytes() b'A'23 returns >>> (65).to_bytes() b'A'24. If no argument is given, the constructor creates a new empty list, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 649 Many other operations also produce lists, including the built-in Lists implement all of the and sequence operations. Lists also provide the following additional method sort(* , key=None , reverse=False)This method sorts the list in place, using only def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 674 comparisons between items. Exceptions are not suppressed - if any comparison operations fail, the entire sort operation will fail (and the list will likely be left in a partially modified state) accepts two arguments that can only be passed by keyword () key specifies a function of one argument that is used to extract a comparison key from each list element (for example, >>> (65).to_bytes() b'A'29). The key corresponding to each item in the list is calculated once and then used for the entire sorting process. The default value of def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631 means that list items are sorted directly without calculating a separate key value The utility is available to convert a 2. x style cmp function to a key function reverse is a boolean value. If set to def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656, then the list elements are sorted as if each comparison were reversed This method modifies the sequence in place for economy of space when sorting a large sequence. To remind users that it operates by side effect, it does not return the sorted sequence (use to explicitly request a new sorted list instance) The method is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade) For sorting examples and a brief sorting tutorial, see CPython implementation detail. While a list is being sorted, the effect of attempting to mutate, or even inspect, the list is undefined. The C implementation of Python makes the list appear empty for the duration, and raises if it can detect that the list has been mutated during a sort TuplesTuples are immutable sequences, typically used to store collections of heterogeneous data (such as the 2-tuples produced by the built-in). Tuples are also used for cases where an immutable sequence of homogeneous data is needed (such as allowing storage in a or instance) class tuple([iterable])Tuples may be constructed in a number of ways
The constructor builds a tuple whose items are the same and in the same order as iterable’s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. Nếu iterable đã là một Tuple, nó sẽ được trả về không thay đổi. For example, >>> (65).to_bytes() b'A'47 returns >>> (65).to_bytes() b'A'48 and >>> (65).to_bytes() b'A'49 returns >>> (65).to_bytes() b'A'50. If no argument is given, the constructor creates a new empty tuple, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 648 Note that it is actually the comma which makes a tuple, not the parentheses. The parentheses are optional, except in the empty tuple case, or when they are needed to avoid syntactic ambiguity. For example, >>> (65).to_bytes() b'A'52 is a function call with three arguments, while >>> (65).to_bytes() b'A'53 is a function call with a 3-tuple as the sole argument Tuples implement all of the sequence operations Đối với các bộ sưu tập dữ liệu không đồng nhất trong đó truy cập theo tên rõ ràng hơn truy cập theo chỉ mục, có thể là lựa chọn phù hợp hơn so với đối tượng tuple đơn giản RangesThe type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in loops class range(stop)class range(start , stop[ , step])The arguments to the range constructor must be integers (either built-in or any object that implements the special method). If the step argument is omitted, it defaults to def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 655. If the start argument is omitted, it defaults to def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 642. If step is zero, is raised For a positive step, the contents of a range >>> (65).to_bytes() b'A'62 are determined by the formula >>> (65).to_bytes() b'A'63 where >>> (65).to_bytes() b'A'64 and >>> (65).to_bytes() b'A'65 For a negative step, the contents of the range are still determined by the formula >>> (65).to_bytes() b'A'63, but the constraints are >>> (65).to_bytes() b'A'64 and >>> (65).to_bytes() b'A'68 A range object will be empty if >>> (65).to_bytes() b'A'69 does not meet the value constraint. Ranges do support negative indices, but these are interpreted as indexing from the end of the sequence determined by the positive indices Ranges containing absolute values larger than are permitted but some features (such as ) may raise Range examples def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 67 Ranges implement all of the sequence operations except concatenation and repetition (due to the fact that range objects can only represent sequences that follow a strict pattern and repetition and concatenation will usually violate that pattern) startThe value of the start parameter (or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 642 if the parameter was not supplied)stop The value of the stop parameter stepThe value of the step parameter (or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 655 if the parameter was not supplied) The advantage of the type over a regular or is that a object will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores the >>> (65).to_bytes() b'A'79, >>> (65).to_bytes() b'A'80 and >>> (65).to_bytes() b'A'81 values, calculating individual items and subranges as needed) Range objects implement the ABC, and provide features such as containment tests, element index lookup, slicing and support for negative indices (see ) def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 68 Testing range objects for equality with def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 678 and def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 679 compares them as sequences. That is, two range objects are considered equal if they represent the same sequence of values. (Note that two range objects that compare equal might have different , and attributes, for example >>> (65).to_bytes() b'A'88 or >>> (65).to_bytes() b'A'89. ) Changed in version 3. 2. Implement the Sequence ABC. Support slicing and negative indices. Test objects for membership in constant time instead of iterating through all items. Changed in version 3. 3. Define ‘==’ and ‘. =’ to compare range objects based on the sequence of values they define (instead of comparing based on object identity). New in version 3. 3. The , and attributes. See also
Text Sequence Type —Textual data in Python is handled with objects, or strings. Strings are immutable of Unicode code points. String literals are written in a variety of ways
Triple quoted strings may span multiple lines - all associated whitespace will be included in the string literal String literals that are part of a single expression and have only whitespace between them will be implicitly converted to a single string literal. That is, def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)00 See for more about the various forms of string literal, including supported escape sequences, and the >>> (65).to_bytes() b'A'62 (“raw”) prefix that disables most escape sequence processing Strings may also be created from other objects using the constructor Since there is no separate “character” type, indexing a string produces strings of length 1. That is, for a non-empty string s, def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)03 There is also no mutable string type, but or can be used to efficiently construct strings from multiple fragments Changed in version 3. 3. For backwards compatibility with the Python 2 series, the def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)06 prefix is once again permitted on string literals. It has no effect on the meaning of string literals and cannot be combined with the >>> (65).to_bytes() b'A'62 prefix. class str(object='')class str(object=b'' , encoding='utf-8' , errors='strict') Return a version of object. If object is not provided, returns the empty string. Otherwise, the behavior of def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 633 depends on whether encoding or errors is given, as follows If neither encoding nor errors is given, def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)09 returns , which is the “informal” or nicely printable string representation of object. For string objects, this is the string itself. If object does not have a method, then falls back to returning If at least one of encoding or errors is given, object should be a (e. g. or ). In this case, if object is a (or ) object, then def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)18 is equivalent to . Mặt khác, đối tượng byte bên dưới đối tượng bộ đệm được lấy trước khi gọi. See and for information on buffer objects Passing a object to without the encoding or errors arguments falls under the first case of returning the informal string representation (see also the command-line option to Python). For example def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 69 For more information on the >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'22 class and its methods, see and the section below. To output formatted strings, see the and sections. In addition, see the section String MethodsStrings implement all of the sequence operations, along with the additional methods described below Strings also support two styles of string formatting, one providing a large degree of flexibility and customization (see , and ) and the other based on C def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)26 style formatting that handles a narrower range of types and is slightly harder to use correctly, but is often faster for the cases it can handle () The section of the standard library covers a number of other modules that provide various text related utilities (including regular expression support in the module) str. capitalize()Return a copy of the string with its first character capitalized and the rest lowercased Changed in version 3. 8. The first character is now put into titlecase rather than uppercase. This means that characters like digraphs will only have their first letter capitalized, instead of the full character. str. casefold()Return a casefolded copy of the string. Casefolded strings may be used for caseless matching Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)28 is equivalent to def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)29. Since it is already lowercase, would do nothing to def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)28; converts it to def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)29 The casefolding algorithm is described in section 3. 13 of the Unicode Standard New in version 3. 3 str. center(width[ , fillchar])Return centered in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'13str. count(sub[ , start[ , end]]) Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation If sub is empty, returns the number of empty strings between characters which is the length of the string plus one str. encode(encoding='utf-8' , errors='strict')Return the string encoded to encoding defaults to def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)36; see for possible values errors controls how encoding errors are handled. If def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)37 (the default), a exception is raised. Other possible values are def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)39, def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)40, def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)41, def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)42 and any other name registered via . See for details For performance reasons, the value of errors is not checked for validity unless an encoding error actually occurs, is enabled or a is used Changed in version 3. 1. Added support for keyword arguments. Changed in version 3. 9. The value of the errors argument is now checked in and in . str. endswith(suffix[ , start[ , end]])Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if the string ends with the specified suffix, otherwise return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that positionstr. expandtabs(tabsize=8) Return a copy of the string where all tab characters are replaced by one or more spaces, depending on the current column and the given tab size. Tab positions occur every tabsize characters (default is 8, giving tab positions at columns 0, 8, 16 and so on). To expand the string, the current column is set to zero and the string is examined character by character. Nếu ký tự là một 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), một hoặc nhiều ký tự khoảng trắng sẽ được chèn vào kết quả cho đến khi cột hiện tại bằng với vị trí tab tiếp theo. (The tab character itself is not copied. ) If the character is a newline ( def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)47) or return ( def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)48), it is copied and the current column is reset to zero. Any other character is copied unchanged and the current column is incremented by one regardless of how the character is represented when printed >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 30str. find(sub[ , start[ , end]]) Return the lowest index in the string where substring sub is found within the slice def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)49. Optional arguments start and end are interpreted as in slice notation. Return >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 341 if sub is not found Note Phương pháp này chỉ nên được sử dụng nếu bạn cần biết vị trí của phụ. To check if sub is a substring or not, use the operator >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 31str. format(*args , **kwargs) Thực hiện thao tác định dạng chuỗi. The string on which this method is called can contain literal text or replacement fields delimited by braces def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 650. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 32 See for a description of the various formatting options that can be specified in format strings Note When formatting a number (, , , and subclasses) with the def bit_count(self): return bin(self).count("1")51 type (ex. def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)59), the function temporarily sets the def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)60 locale to the def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)61 locale to decode def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)62 and def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)63 fields of def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)64 if they are non-ASCII or longer than 1 byte, and the def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)61 locale is different than the def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)60 locale. This temporary change affects other threads Changed in version 3. 7. When formatting a number with the def bit_count(self): return bin(self).count("1")51 type, the function sets temporarily the def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)60 locale to the def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)61 locale in some cases. str. format_map(mapping) Similar to def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)70, except that def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)71 is used directly and not copied to a . This is useful if for example def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)71 is a dict subclass >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 33 Mới trong phiên bản 3. 2 str. index(sub[ , start[ , end]])Like , but raise when the substring is not found str. isalnum()Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if all characters in the string are alphanumeric and there is at least one character, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 otherwise. A character def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)78 is alphanumeric if one of the following returns def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656. def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)80, def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)81, def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)82, or def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)83str. isalpha() Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if all characters in the string are alphabetic and there is at least one character, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 otherwise. Alphabetic characters are those characters defined in the Unicode character database as “Letter”, i. e. , those with general category property being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is different from the “Alphabetic” property defined in the Unicode Standardstr. isascii() Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if the string is empty or all characters in the string are ASCII, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 otherwise. ASCII characters have code points in the range U+0000-U+007F New in version 3. 7 str. isdecimal()Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if all characters in the string are decimal characters and there is at least one character, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 otherwise. Decimal characters are those that can be used to form numbers in base 10, e. g. U+0660, ARABIC-INDIC DIGIT ZERO. Formally a decimal character is a character in the Unicode General Category “Nd”str. isdigit() Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if all characters in the string are digits and there is at least one character, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimalstr. isidentifier() Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if the string is a valid identifier according to the language definition, section Call to test whether string def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)94 is a reserved identifier, such as and Example >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 34str. islower() Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if all cased characters in the string are lowercase and there is at least one cased character, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 otherwisestr. isnumeric() Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if all characters in the string are numeric characters, and there is at least one character, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 otherwise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e. g. U+2155, VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numericstr. isprintable() Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if all characters in the string are printable or the string is empty, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 otherwise. Các ký tự không in được là những ký tự được định nghĩa trong cơ sở dữ liệu ký tự Unicode là “Khác” hoặc “Dấu phân cách”, ngoại trừ khoảng trống ASCII (0x20) được coi là có thể in được. (Note that printable characters in this context are those which should not be escaped when is invoked on a string. It has no bearing on the handling of strings written to or . )str. isspace() Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if there are only whitespace characters in the string and there is at least one character, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 otherwise A character is whitespace if in the Unicode character database (see ), either its general category is >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168009 (“Separator, space”), or its bidirectional class is one of >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168010, >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168011, or >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168012str. istitle() Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 otherwisestr. isupper() Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if all cased characters in the string are uppercase and there is at least one cased character, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 otherwise >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 35str. join(iterable) Return a string which is the concatenation of the strings in iterable. A will be raised if there are any non-string values in iterable, including objects. The separator between elements is the string providing this method str. ljust(width[ , fillchar])Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'13str. lower() Return a copy of the string with all the cased characters converted to lowercase The lowercasing algorithm used is described in section 3. 13 of the Unicode Standard str. lstrip([chars])Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631, the chars argument defaults to removing whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 36 See for a method that will remove a single prefix string rather than all of a set of characters. For example >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 37static str. maketrans(x[ , y[ , z]]) This static method returns a translation table usable for If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631. Character keys will then be converted to ordinals If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631 in the resultstr. partition(sep) Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings str. removeprefix(prefix , /)If the string starts with the prefix string, return >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168025. Otherwise, return a copy of the original string >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 38 New in version 3. 9 str. removesuffix(suffix , /)If the string ends with the suffix string and that suffix is not empty, return >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168026. Nếu không, hãy trả về một bản sao của chuỗi gốc >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 39 New in version 3. 9 str. replace(old , new[ , count])Return a copy of the string with all occurrences of substring old replaced by new. Nếu số lượng đối số tùy chọn được cung cấp, chỉ những lần xuất hiện đầu tiên được thay thế str. rfind(sub[ , start[ , end]])Return the highest index in the string where substring sub is found, such that sub is contained within def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)49. Optional arguments start and end are interpreted as in slice notation. Return >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 341 on failurestr. rindex(sub[ , start[ , end]]) Like but raises when the substring sub is not found str. rjust(width[ , fillchar])Return the string right justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'13str. rpartition(sep) Split the string at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself str. rsplit(sep=None , maxsplit=- 1)Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631, any whitespace string is a separator. Except for splitting from the right, behaves like which is described in detail belowstr. rstrip([chars]) Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631, the chars argument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped def bit_count(self): return bin(self).count("1")0 See for a method that will remove a single suffix string rather than all of a set of characters. For example def bit_count(self): return bin(self).count("1")1str. split(sep=None , maxsplit=- 1) 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') 1671168037 elements). If maxsplit is not specified or >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 341, then there is no limit on the number of splits (all possible splits are made) If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168039 returns >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168040). The sep argument may consist of multiple characters (for example, >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168041 returns >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168042). Splitting an empty string with a specified separator returns >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168043 For example def bit_count(self): return bin(self).count("1")2 If sep is not specified or is def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631, a different splitting algorithm is applied. 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') --> 631 separator returns def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 649 For example def bit_count(self): return bin(self).count("1")3str. splitlines(keepends=False) Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true This method splits on the following line boundaries. In particular, the boundaries are a superset of Representation Description def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)47 Line Feed def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)48 Carriage Return >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168049 Carriage Return + Line Feed >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168050 or >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168051 Line Tabulation >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168052 or >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168053 Form Feed >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168054 File Separator >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168055 Group Separator >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168056 Record Separator >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168057 Next Line (C1 Control Code) >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168058 Line Separator >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168059 Paragraph Separator Changed in version 3. 2. >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168050 and >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168052 added to list of line boundaries. For example def bit_count(self): return bin(self).count("1")4 Unlike when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line def bit_count(self): return bin(self).count("1")5 For comparison, >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168063 gives def bit_count(self): return bin(self).count("1")6str. startswith(tiền tố[ , start[, end]]) Trả về def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 nếu chuỗi bắt đầu bằng tiền tố, ngược lại trả về def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that positionstr. strip([chars]) Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped def bit_count(self): return bin(self).count("1")7 The outermost leading and trailing chars argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in chars. A similar action takes place on the trailing end. For example def bit_count(self): return bin(self).count("1")8str. swapcase() Return a copy of the string with uppercase characters converted to lowercase and vice versa. Note that it is not necessarily true that >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168067str. title() Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase For example def bit_count(self): return bin(self).count("1")9 The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'0 The function does not have this problem, as it splits words on spaces only Alternatively, a workaround for apostrophes can be constructed using regular expressions >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'1str. translate(table) Return a copy of the string in which each character has been mapped through the given translation table. The table must be an object that implements indexing via >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168069, typically a or . When indexed by a Unicode ordinal (an integer), the table object can do any of the following. return a Unicode ordinal or a string, to map the character to one or more other characters; return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631, to delete the character from the return string; or raise a exception, to map the character to itself You can use to create a translation map from character-to-character mappings in different formats See also the module for a more flexible approach to custom character mappings str. upper()Return a copy of the string with all the cased characters converted to uppercase. Note that >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168074 might be def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 if def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)94 contains uncased characters or if the Unicode category of the resulting character(s) is not “Lu” (Letter, uppercase), but e. g. “Lt” (Letter, titlecase) The uppercasing algorithm used is described in section 3. 13 of the Unicode Standard str. zfill(width)Return a copy of the string left filled with ASCII >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168077 digits to make a string of length width. A leading sign prefix ( >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168078/ >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168079) is handled by inserting the padding after the sign character rather than before. The original string is returned if width is less than or equal to >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'13 For example >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'2 def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 26-style String FormattingNote The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer , the interface, or may help avoid these errors. Each of these alternatives provides their own trade-offs and benefits of simplicity, flexibility, and/or extensibility String objects have one unique built-in operation. the >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168083 operator (modulo). This is also known as the string formatting or interpolation operator. Given >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168084 (where format is a string), >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168083 conversion specifications in format are replaced with zero or more elements of values. Hiệu quả tương tự như việc sử dụng >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168086 trong ngôn ngữ C If format requires a single argument, values may be a single non-tuple object. Otherwise, values must be a tuple with exactly the number of items specified by the format string, or a single mapping object (for example, a dictionary) A conversion specifier contains two or more characters and has the following components, which must occur in this order
When the right argument is a dictionary (or other mapping type), then the formats in the string must include a parenthesised mapping key into that dictionary inserted immediately after the >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168087 character. The mapping key selects the value to be formatted from the mapping. For example >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'3 In this case no >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'00 specifiers may occur in a format (since they require a sequential parameter list) The conversion flag characters are Flag Nghĩ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') 1671168094 The value conversion will use the “alternate form” (where defined below) >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168077 The conversion will be zero padded for numeric values >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168079 The converted value is left adjusted (overrides the >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168077 conversion if both are given) >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168098 (a space) A blank should be left before a positive number (or empty string) produced by a signed conversion >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168078 A sign character ( >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168078 or >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168079) will precede the conversion (overrides a “space” flag) A length modifier ( def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n02, def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n03, or def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n04) may be present, but is ignored as it is not necessary for Python – so e. g. def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n05 is identical to def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n06 The conversion types are Conversion Nghĩa ghi chú def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n07 Signed integer decimal def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n08 Signed integer decimal def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n09 Signed octal value (1) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n10 Obsolete type – it is identical to def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n07 (6) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n12 Signed hexadecimal (lowercase) (2) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n13 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 n14 Floating point exponential format (lowercase) (3) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n15 Floating point exponential format (uppercase) (3) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n16 Floating point decimal format (3) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n17 Floating point decimal format (3) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n18 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 n19 Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise (4) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n20 Single character (accepts integer or single character string) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n21 String (converts any Python object using ) (5) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n23 String (converts any Python object using ) (5) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n25 String (converts any Python object using ) (5) >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168087 No argument is converted, results in a >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168087 character in the result ghi chú
Vì các chuỗi Python có độ dài rõ ràng, các chuyển đổi củ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 n36 không cho rằng def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n37 là phần cuối của chuỗi Changed in version 3. 1. def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n38 conversions for numbers whose absolute value is over 1e50 are no longer replaced by def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n39 conversions. Binary Sequence Types — , ,The core built-in types for manipulating binary data are and . They are supported by which uses the to access the memory of other binary objects without needing to make a copy The module supports efficient storage of basic data types like 32-bit integers and IEEE754 double-precision floating values Bytes ObjectsBytes 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 n47 prefix is added
Only ASCII characters are permitted in bytes literals (regardless of the declared source code encoding). Any binary values over 127 must be entered into bytes literals using the appropriate escape sequence As with string literals, bytes literals may also use a >>> (65).to_bytes() b'A'62 prefix to disable processing of escape sequences. See for more about the various forms of bytes literal, including supported escape sequences While bytes literals and representations are based on ASCII text, bytes objects actually behave like immutable sequences of integers, with each value in the sequence restricted such that def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n53 (attempts to violate this restriction will trigger ). This is done deliberately to emphasise that while many binary formats include ASCII based elements and can be usefully manipulated with some text-oriented algorithms, this is not generally the case for arbitrary binary data (blindly applying text processing algorithms to binary data formats that are not ASCII compatible will usually lead to data corruption) In addition to the literal forms, bytes objects can be created in a number of other ways
Also see the built-in Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal numbers are a commonly used format for describing binary data. Accordingly, the bytes type has an additional class method to read data in that format classmethod fromhex(string)This class method returns a bytes object, decoding the given string object. The string must contain two hexadecimal digits per byte, with ASCII whitespace being ignored >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'4 Changed in version 3. 7. now skips all ASCII whitespace in the string, not just spaces. A reverse conversion function exists to transform a bytes object into its hexadecimal representation hex([sep[ , bytes_per_sep]])Return a string object containing two hexadecimal digits for each byte in the instance >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'5 If you want to make the hex string easier to read, you can specify a single character separator sep parameter to include in the output. By default, this separator will be included between each byte. A second optional bytes_per_sep parameter controls the spacing. Positive values calculate the separator position from the right, negative values from the left >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'6 New in version 3. 5 Changed in version 3. 8. now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output. Since bytes objects are sequences of integers (akin to a tuple), for a bytes object b, def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n61 will be an integer, while def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n62 will be a bytes object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1) The representation of bytes objects uses the literal format ( def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n63) since it is often more useful than e. g. def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n64. You can always convert a bytes object into a list of integers using def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n65 Bytearray Objectsobjects are a mutable counterpart to objects class bytearray([source[ , encoding[ , errors]]])There is no dedicated literal syntax for bytearray objects, instead they are always created by calling the constructor
As bytearray objects are mutable, they support the sequence operations in addition to the common bytes and bytearray operations described in Also see the built-in Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal numbers are a commonly used format for describing binary data. Accordingly, the bytearray type has an additional class method to read data in that format classmethod fromhex(string)This class method returns bytearray object, decoding the given string object. The string must contain two hexadecimal digits per byte, with ASCII whitespace being ignored >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'7 Changed in version 3. 7. now skips all ASCII whitespace in the string, not just spaces. A reverse conversion function exists to transform a bytearray object into its hexadecimal representation hex([sep[ , bytes_per_sep]])Return a string object containing two hexadecimal digits for each byte in the instance >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'8 New in version 3. 5 Đã thay đổi trong phiên bản 3. 8. Similar to , now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output. Since bytearray objects are sequences of integers (akin to a list), for a bytearray object b, def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n61 will be an integer, while def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n62 will be a bytearray object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1) The representation of bytearray objects uses the bytes literal format ( def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n78) since it is often more useful than e. g. def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n79. You can always convert a bytearray object into a list of integers using def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n65 Bytes and Bytearray OperationsBoth bytes and bytearray objects support the sequence operations. They interoperate not just with operands of the same type, but with any . Due to this flexibility, they can be freely mixed in operations without causing errors. However, the return type of the result may depend on the order of operands Note The methods on bytes and bytearray objects don’t accept strings as their arguments, just as the methods on strings don’t accept bytes as their arguments. For example, you have to write >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'9 and >>> (65).to_bytes() b'A'0 Some bytes and bytearray operations assume the use of ASCII compatible binary formats, and hence should be avoided when working with arbitrary binary data. These restrictions are covered below Note Using these ASCII based operations to manipulate binary data that is not stored in an ASCII based format may lead to data corruption The following methods on bytes and bytearray objects can be used with arbitrary binary data bytes. count(sub[ , start[ , end]])bytearray. count(sub[ , start[ , end]])Return the number of non-overlapping occurrences of subsequence sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation The subsequence to search for may be any or an integer in the range 0 to 255 If sub is empty, returns the number of empty slices between characters which is the length of the bytes object plus one Changed in version 3. 3. Also accept an integer in the range 0 to 255 as the subsequence. bytes. removeprefix(prefix , /)bytearray. 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 n81. Otherwise, return a copy of the original binary data >>> (65).to_bytes() b'A'1 The prefix may be any Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made New in version 3. 9 bytes. removesuffix(suffix , /)bytearray. removesuffix(suffix , /)If the binary data ends with the suffix string and that suffix is not empty, return def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n82. Otherwise, return a copy of the original binary data >>> (65).to_bytes() b'A'2 The suffix may be any Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made New in version 3. 9 bytes. decode(encoding='utf-8' , errors='strict')bytearray. decode(encoding='utf-8' , errors='strict')Return the bytes decoded to a encoding defaults to def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)36; see for possible values errors controls how decoding errors are handled. If def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)37 (the default), a exception is raised. Other possible values are def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)39, def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)40, and any other name registered via . See for details For performance reasons, the value of errors is not checked for validity unless a decoding error actually occurs, is enabled or a is used Note Passing the encoding argument to allows decoding any directly, without needing to make a temporary >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'23 or >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'24 object Changed in version 3. 1. Added support for keyword arguments. Changed in version 3. 9. The value of the errors argument is now checked in and in . 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') --> 656 if the binary data ends with the specified suffix, otherwise return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. Với đầu cuối tùy chọn, dừng so sánh tại vị trí đó The suffix(es) to search for may be any bytes. find(sub[ , start[ , end]])bytearray. find(sub[ , start[ , end]])Return the lowest index in the data where the subsequence sub is found, such that sub is contained in the slice def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)49. Optional arguments start and end are interpreted as in slice notation. Return >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 341 if sub is not found The subsequence to search for may be any or an integer in the range 0 to 255 Note Phương pháp này chỉ nên được sử dụng nếu bạn cần biết vị trí của phụ. To check if sub is a substring or not, use the operator >>> (65).to_bytes() b'A'3 Changed in version 3. 3. Also accept an integer in the range 0 to 255 as the subsequence. bytes. index(sub[ , start[ , end]])bytearray. index(sub[ , start[ , end]])Like , but raise when the subsequence is not found The subsequence to search for may be any or an integer in the range 0 to 255 Changed in version 3. 3. Also accept an integer in the range 0 to 255 as the subsequence. bytes. join(iterable)bytearray. join(iterable)Return a bytes or bytearray object which is the concatenation of the binary data sequences in iterable. A will be raised if there are any values in iterable that are not , including objects. The separator between elements is the contents of the bytes or bytearray object providing this method 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 Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made bytes. rfind(sub[ , start[ , end]])bytearray. rfind(sub[ , start[ , end]])Return the highest index in the sequence where the subsequence sub is found, such that sub is contained within def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)49. Optional arguments start and end are interpreted as in slice notation. Return >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 341 on failure The subsequence to search for may be any or an integer in the range 0 to 255 Changed in version 3. 3. Also accept an integer in the range 0 to 255 as the subsequence. bytes. rindex(sub[ , start[ , end]])bytearray. rindex(sub[ , start[ , end]])Like but raises when the subsequence sub is not found The subsequence to search for may be any or an integer in the range 0 to 255 Changed in version 3. 3. Also accept an integer in the range 0 to 255 as the subsequence. bytes. rpartition(sep)bytearray. rpartition(sep)Split the sequence at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself or its bytearray copy, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty bytes or bytearray objects, followed by a copy of the original sequence The separator to search for may be any bytes. startswith(prefix[ , start[ , end]])bytearray. startswith(prefix[ , start[ , end]])Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if the binary data starts with the specified prefix, otherwise return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638. prefix can also be a tuple of prefixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position The prefix(es) to search for may be any bytes. translate(table , / , delete=b'')bytearray. translate(table , / , delete=b'')Return a copy of the bytes or bytearray object where all bytes occurring in the optional argument delete are removed, and the remaining bytes have been mapped through the given translation table, which must be a bytes object of length 256 You can use the method to create a translation table Set the table argument to def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631 for translations that only delete characters >>> (65).to_bytes() b'A'4 Changed in version 3. 6. xóa hiện được hỗ trợ làm đối số từ khóa. The following methods on bytes and bytearray objects have default behaviours that assume the use of ASCII compatible binary formats, but can still be used with arbitrary binary data by passing appropriate arguments. Note that all of the bytearray methods in this section do not operate in place, and instead produce new objects bytes. center(width[ , fillbyte])bytearray. center(width[ , fillbyte])Return a copy of the object centered in a sequence of length width. Padding is done using the specified fillbyte (default is an ASCII space). Đối với các đối tượng, chuỗi ban đầu được trả về nếu chiều rộng nhỏ hơn hoặc bằng >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'13 Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made bytes. ljust(chiều rộng[ , . fillbyte])bytearray.ljust(width[ , fillbyte])Return a copy of the object left justified in a sequence of length width. Padding is done using the specified fillbyte (default is an ASCII space). For objects, the original sequence is returned if width is less than or equal to >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'13 Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made bytes. lstrip([chars])bytearray. lstrip([chars])Return a copy of the sequence with specified leading bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631, the chars argument defaults to removing ASCII whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped >>> (65).to_bytes() b'A'5 The binary sequence of byte values to remove may be any . See for a method that will remove a single prefix string rather than all of a set of characters. For example >>> (65).to_bytes() b'A'6 Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made bytes. rjust(width[ , fillbyte])bytearray. rjust(width[ , fillbyte])Return a copy of the object right justified in a sequence of length width. Padding is done using the specified fillbyte (default is an ASCII space). For objects, the original sequence is returned if width is less than or equal to >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'13 Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made bytes. rsplit(sep=None , maxsplit=- 1)bytearray. rsplit(sep=None , maxsplit=- 1)Split the binary sequence into subsequences of the same type, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631, any subsequence consisting solely of ASCII whitespace is a separator. Except for splitting from the right, behaves like which is described in detail belowbytes. rstrip([chars])bytearray. rstrip([chars]) Return a copy of the sequence with specified trailing bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631, the chars argument defaults to removing ASCII whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped >>> (65).to_bytes() b'A'7 The binary sequence of byte values to remove may be any . See for a method that will remove a single suffix string rather than all of a set of characters. For example >>> (65).to_bytes() b'A'8 Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made bytes. split(sep=None , maxsplit=- 1)bytearray. split(sep=None , maxsplit=- 1)Split the binary sequence into subsequences of the same type, using sep as the delimiter string. If maxsplit is given and non-negative, at most maxsplit splits are done (thus, the list will have at most >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168037 elements). If maxsplit is not specified or is >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 341, then there is no limit on the number of splits (all possible splits are made) 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() False27 returns >>> (-2.0).is_integer() True >>> (3.2).is_integer() False28). The sep argument may consist of a multibyte sequence (for example, >>> (-2.0).is_integer() True >>> (3.2).is_integer() False29 returns >>> (-2.0).is_integer() True >>> (3.2).is_integer() False30). Splitting an empty sequence with a specified separator returns >>> (-2.0).is_integer() True >>> (3.2).is_integer() False31 or >>> (-2.0).is_integer() True >>> (3.2).is_integer() False32 depending on the type of object being split. The sep argument may be any For example >>> (65).to_bytes() b'A'9 If sep is not specified or is def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631, a different splitting algorithm is applied. runs of consecutive ASCII whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the sequence has leading or trailing whitespace. Consequently, splitting an empty sequence or a sequence consisting solely of ASCII whitespace without a specified separator returns def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 649 For example def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)0bytes. strip([chars])bytearray. strip([chars]) Return a copy of the sequence with specified leading and trailing bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631, the chars argument defaults to removing ASCII whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)1 The binary sequence of byte values to remove may be any Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made The following methods on bytes and bytearray objects assume the use of ASCII compatible binary formats and should not be applied to arbitrary binary data. Note that all of the bytearray methods in this section do not operate in place, and instead produce new objects bytes. capitalize()bytearray. capitalize()Return a copy of the sequence with each byte interpreted as an ASCII character, and the first byte capitalized and the rest lowercased. Non-ASCII byte values are passed through unchanged Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made bytes. expandtabs(tabsize=8)bytearray. expandtabs(tabsize=8)Return a copy of the sequence where all ASCII tab characters are replaced by one or more ASCII spaces, depending on the current column and the given tab size. Tab positions occur every tabsize bytes (default is 8, giving tab positions at columns 0, 8, 16 and so on). To expand the sequence, the current column is set to zero and the sequence is examined byte by byte. If the byte is an ASCII tab character ( >>> (-2.0).is_integer() True >>> (3.2).is_integer() False36), one or more space characters are inserted in the result until the current column is equal to the next tab position. (The tab character itself is not copied. ) If the current byte is an ASCII newline ( >>> (-2.0).is_integer() True >>> (3.2).is_integer() False37) or carriage return ( >>> (-2.0).is_integer() True >>> (3.2).is_integer() False38), it is copied and the current column is reset to zero. Any other byte value is copied unchanged and the current column is incremented by one regardless of how the byte value is represented when printed def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)2 Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made bytes. isalnum()bytearray. isalnum()Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if all bytes in the sequence are alphabetical ASCII characters or ASCII decimal digits and the sequence is not empty, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 otherwise. Alphabetic ASCII characters are those byte values in the sequence >>> (-2.0).is_integer() True >>> (3.2).is_integer() False41. ASCII decimal digits are those byte values in the sequence >>> (-2.0).is_integer() True >>> (3.2).is_integer() False42 For example def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)3bytes. isalpha()bytearray. isalpha() Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if all bytes in the sequence are alphabetic ASCII characters and the sequence is not empty, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 otherwise. Alphabetic ASCII characters are those byte values in the sequence >>> (-2.0).is_integer() True >>> (3.2).is_integer() False41 For example def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)4bytes. 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') --> 656 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') --> 638 otherwise. ASCII bytes are in the range 0-0x7F New in version 3. 7 bytes. isdigit()bytearray. isdigit()Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if all bytes in the sequence are ASCII decimal digits and the sequence is not empty, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 otherwise. ASCII decimal digits are those byte values in the sequence >>> (-2.0).is_integer() True >>> (3.2).is_integer() False42 For example def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)5bytes. islower()bytearray. islower() Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if there is at least one lowercase ASCII character in the sequence and no uppercase ASCII characters, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 otherwise For example def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)6 Lowercase ASCII characters are those byte values in the sequence >>> (-2.0).is_integer() True >>> (3.2).is_integer() False53. Uppercase ASCII characters are those byte values in the sequence >>> (-2.0).is_integer() True >>> (3.2).is_integer() False54bytes. isspace()bytearray. isspace() Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if all bytes in the sequence are ASCII whitespace and the sequence is not empty, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 otherwise. ASCII whitespace characters are those byte values in the sequence >>> (-2.0).is_integer() True >>> (3.2).is_integer() False57 (space, tab, newline, carriage return, vertical tab, form feed)bytes. istitle()bytearray. tiêu đề() Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if the sequence is ASCII titlecase and the sequence is not empty, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 otherwise. See for more details on the definition of “titlecase” For example def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)7bytes. isupper()bytearray. isupper() Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if there is at least one uppercase alphabetic ASCII character in the sequence and no lowercase ASCII characters, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 otherwise For example def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)8 Lowercase ASCII characters are those byte values in the sequence >>> (-2.0).is_integer() True >>> (3.2).is_integer() False53. Uppercase ASCII characters are those byte values in the sequence >>> (-2.0).is_integer() True >>> (3.2).is_integer() False54bytes. lower()bytearray. lower() Trả về một bản sao của chuỗi với tất cả các ký tự ASCII chữ hoa được chuyển đổi thành chữ thường tương ứng của chúng For example def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)9 Lowercase ASCII characters are those byte values in the sequence >>> (-2.0).is_integer() True >>> (3.2).is_integer() False53. Uppercase ASCII characters are those byte values in the sequence >>> (-2.0).is_integer() True >>> (3.2).is_integer() False54 Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made byte. splitlines(keepends=False)bytearray. splitlines(keepends=False)Trả về danh sách các dòng trong chuỗi nhị phân, phá vỡ ranh giới dòng ASCII. Phương pháp này sử dụng phương pháp tách dòng. Ngắt dòng không được bao gồm trong danh sách kết quả trừ khi keepends được đưa ra và đúng 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') 167116800 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') 167116801byte. swapcase()bytearray. hoán đổi() Trả về một bản sao của chuỗi với tất cả các ký tự ASCII chữ thường được chuyển đổi thành chữ hoa tương ứng của chúng và ngược lại 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') 167116802 Lowercase ASCII characters are those byte values in the sequence >>> (-2.0).is_integer() True >>> (3.2).is_integer() False53. Uppercase ASCII characters are those byte values in the sequence >>> (-2.0).is_integer() True >>> (3.2).is_integer() False54 Không giống như , luôn luôn xảy ra trường hợp >>> (-2.0).is_integer() True >>> (3.2).is_integer() False71 đối với các phiên bản nhị phân. Chuyển đổi trường hợp là đối xứng trong ASCII, mặc dù điều đó thường không đúng đối với các điểm mã Unicode tùy ý Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made byte. tiêu đề()bytearray. tiêu đề()Trả về phiên bản có tiêu đề của chuỗi nhị phân trong đó các từ bắt đầu bằng ký tự ASCII viết hoa và các ký tự còn lại là chữ thường. Các giá trị byte chưa được khai thác không được sửa đổi For example >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 167116803 Các ký tự ASCII chữ thường là các giá trị byte trong chuỗi >>> (-2.0).is_integer() True >>> (3.2).is_integer() False53. Các ký tự ASCII chữ hoa là những giá trị byte trong chuỗi >>> (-2.0).is_integer() True >>> (3.2).is_integer() False54. Tất cả các giá trị byte khác đều không có vỏ 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') 167116804 Có thể xây dựng giải pháp thay thế cho dấu nháy đơn bằng cách sử dụng biểu thức chính quy >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 167116805 Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made byte. trên()bytearray. trên()Trả về một bản sao của chuỗi với tất cả các ký tự ASCII chữ thường được chuyển đổi thành chữ hoa tương ứng của chúng 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') 167116806 Lowercase ASCII characters are those byte values in the sequence >>> (-2.0).is_integer() True >>> (3.2).is_integer() False53. Uppercase ASCII characters are those byte values in the sequence >>> (-2.0).is_integer() True >>> (3.2).is_integer() False54 Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made byte. zfill(chiều rộng)bytearray. zfill(chiều rộng)Trả lại một bản sao của chuỗi còn lại được điền bằng ASCII >>> (-2.0).is_integer() True >>> (3.2).is_integer() False76 chữ số để tạo một chuỗi có chiều dài chiều rộng. Tiền tố dấu hiệu ở đầu ( >>> (-2.0).is_integer() True >>> (3.2).is_integer() False77/ >>> (-2.0).is_integer() True >>> (3.2).is_integer() False78) được xử lý bằng cách chèn phần đệm sau ký tự dấu hiệu thay vì trước. Đối với các đối tượng, chuỗi ban đầu được trả về nếu chiều rộng nhỏ hơn hoặc bằng >>> (-2.0).is_integer() True >>> (3.2).is_integer() False80 For example >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 167116807 Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made Định dạng byte kiểu 26 kiểu def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)Note Các hoạt động định dạng được mô tả ở đây thể hiện nhiều điểm kỳ quặc dẫn đến một số lỗi phổ biến (chẳng hạn như không hiển thị chính xác các bộ dữ liệu và từ điển). Nếu giá trị được in có thể là một bộ hoặc từ điển, hãy bọc nó trong một bộ Các đối tượng 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) có một thao tác tích hợp duy nhất. toán tử >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168083 (mô-đun). Điều này còn được gọi là định dạng byte hoặc toán tử nội suy. Cho trước >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168084 (trong đó định dạng là đối tượng byte), thông số kỹ thuật chuyển đổi củ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') 1671168083 ở định dạng được thay thế bằng 0 hoặc nhiều thành phần giá trị. Hiệu quả tương tự như việc sử dụng >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168086 trong ngôn ngữ C If format requires a single argument, values may be a single non-tuple object. Mặt khác, các giá trị phải là một bộ có số mục chính xác được chỉ định bởi đối tượng byte định dạng hoặc một đối tượng ánh xạ đơn lẻ (ví dụ: từ điển) A conversion specifier contains two or more characters and has the following components, which must occur in this order
Khi đối số bên phải là một từ điển (hoặc loại ánh xạ khác), thì các định dạng trong đối tượng byte phải bao gồm khóa ánh xạ trong ngoặc đơn vào từ điển đó được chèn ngay sau ký tự >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168087. Phím ánh xạ chọn giá trị được định dạng từ ánh xạ. Ví dụ >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 167116808 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 Nghĩ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') 1671168094 The value conversion will use the “alternate form” (where defined below) >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168077 The conversion will be zero padded for numeric values >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168079 The converted value is left adjusted (overrides the >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168077 conversion if both are given) >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168098 (a space) A blank should be left before a positive number (or empty string) produced by a signed conversion >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168078 A sign character ( >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168078 or >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168079) will precede the conversion (overrides a “space” flag) A length modifier ( def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n02, def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n03, or def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n04) may be present, but is ignored as it is not necessary for Python – so e. g. def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n05 is identical to def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n06 The conversion types are Conversion Nghĩa ghi chú def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n07 Signed integer decimal def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n08 Signed integer decimal def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n09 Signed octal value (1) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n10 Obsolete type – it is identical to def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n07 (8) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n12 Signed hexadecimal (lowercase) (2) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n13 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 n14 Floating point exponential format (lowercase) (3) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n15 Floating point exponential format (uppercase) (3) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n16 Floating point decimal format (3) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n17 Floating point decimal format (3) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n18 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 n19 Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise (4) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n20 Byte đơn (chấp nhận đối tượng số nguyên hoặc byte đơn) def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6022 Byte (bất kỳ đối tượng nào theo sau hoặc có def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6023) (5) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n23 def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n23 là bí danh củ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') --> 6022 và chỉ nên được sử dụng cho cơ sở mã Python2/3 (6) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n25 Byte (chuyển đổi bất kỳ đối tượng Python nào bằng cách sử dụng def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6028) (5) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n21 def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n21 là bí danh củ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 n25 và chỉ nên được sử dụng cho cơ sở mã Python2/3 (7) >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168087 No argument is converted, results in a >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168087 character in the result ghi chú
Note The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made See also PEP 461 - Thêm % định dạng vào byte và bytearray New in version 3. 5 Lượt xem bộ nhớcác đối tượng cho phép mã Python truy cập dữ liệu bên trong của một đối tượng hỗ trợ mà không cần sao chép lớp chế độ xem bộ nhớ(đối tượng)Tạo một đối tượng tham chiếu đó. object must support the buffer protocol. Built-in objects that support the buffer protocol include and A có khái niệm về một phần tử, là đơn vị bộ nhớ nguyên tử được xử lý bởi đối tượng gốc. Đối với nhiều loại đơn giản như and , một phần tử là một byte đơn, nhưng các loại khác chẳng hạn như có thể có các phần tử lớn hơn def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6051 bằng chiều dài của. Nếu def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6053, độ dài là 1. Nếu def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6054, độ dài bằng số phần tử trong khung nhìn. Đối với các kích thước cao hơn, độ dài bằng với độ dài của biểu diễn danh sách lồng nhau của chế độ xem. Thuộc tính sẽ cung cấp cho bạn số byte trong một phần tử A hỗ trợ cắt và lập chỉ mục để hiển thị dữ liệu của nó. Cắt một chiều sẽ dẫn đến một chế độ xem phụ >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 167116809 Nếu là một trong những công cụ xác định định dạng gốc từ mô-đun, thì việc lập chỉ mục với một số nguyên hoặc một bộ số nguyên cũng được hỗ trợ và trả về một phần tử với loại chính xác. Các lần xem bộ nhớ một chiều có thể được lập chỉ mục bằng một số nguyên hoặc một bộ một số nguyên. Các lần xem bộ nhớ đa chiều có thể được lập chỉ mục với các bộ số nguyên chính xác ndim trong đó ndim là số thứ nguyên. Các lần xem bộ nhớ không chiều có thể được lập chỉ mục với bộ dữ liệu trống Đây là một ví dụ với định dạng không phải 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 n0 Nếu đối tượng bên dưới có thể ghi được, chế độ xem bộ nhớ hỗ trợ gán lát cắt một chiều. Thay đổi kích thước không được phép def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n1 Chế độ xem bộ nhớ một chiều của các loại có thể băm (chỉ đọc) với định dạng 'B', 'b' hoặc 'c' cũng có thể băm được. Băm được định nghĩa là def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6059 def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n2 Đã thay đổi trong phiên bản 3. 3. One-dimensional memoryviews can now be sliced. Chế độ xem bộ nhớ một chiều với các định dạng 'B', 'b' hoặc 'c' hiện có thể băm được. Đã thay đổi trong phiên bản 3. 4. memoryview hiện được đăng ký tự động với Đã thay đổi trong phiên bản 3. 5. lượt xem bộ nhớ hiện có thể được lập chỉ mục với bộ số nguyên. có một số phương pháp __eq__(nhà xuất khẩu)Một chế độ xem bộ nhớ và một trình xuất PEP 3118 bằng nhau nếu hình dạng của chúng tương đương nhau và nếu tất cả các giá trị tương ứng đều bằng nhau khi mã định dạng tương ứng của toán hạng được diễn giải bằng cú pháp Đối với tập hợp con của các chuỗi định dạng hiện được hỗ trợ bởi , def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6065 và def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6066 bằng nhau nếu def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6067 def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n3 Nếu một trong hai chuỗi định dạng không được mô-đun hỗ trợ, thì các đối tượng sẽ luôn so sánh là không bằng nhau (ngay cả khi các chuỗi định dạng và nội dung bộ đệm giống hệt nhau) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n4 Lưu ý rằng, như với các số dấu phẩy động, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6069 không ngụ ý def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6070 đối với các đối tượng memoryview Đã thay đổi trong phiên bản 3. 3. Các phiên bản trước so sánh bộ nhớ thô bất kể định dạng mục và cấu trúc mảng logic. tobyte(thứ tự='C')Trả lại dữ liệu trong bộ đệm dưới dạng chuỗi ký tự. This is equivalent to calling the constructor on the memoryview def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n5 Đối với các mảng không liền kề, kết quả bằng với biểu diễn danh sách phẳng với tất cả các phần tử được chuyển đổi thành byte. hỗ trợ tất cả các chuỗi định dạng, kể cả những chuỗi không có trong cú pháp mô-đun Mới trong phiên bản 3. 8. thứ tự có thể là {‘C’, ‘F’, ‘A’}. Khi thứ tự là 'C' hoặc 'F', dữ liệu của mảng ban đầu được chuyển thành thứ tự C hoặc Fortran. Đối với các chế độ xem liền kề, 'A' trả về một bản sao chính xác của bộ nhớ vật lý. Đặc biệt, thứ tự Fortran trong bộ nhớ được giữ nguyên. Đối với các chế độ xem không liền kề, dữ liệu được chuyển đổi thành C trước. order=None giống với order=’C’. hex([sep[ , bytes_per_sep]])Trả về một đối tượng chuỗi chứa hai chữ số thập lục phân cho mỗi byte trong bộ đệm def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n6 New in version 3. 5 Đã thay đổi trong phiên bản 3. 8. Similar to , now supports optional sep and bytes_per_sep parameters to insert separators between bytes in the hex output. tolist()Return the data in the buffer as a list of elements def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n7 Đã thay đổi trong phiên bản 3. 3. hiện hỗ trợ tất cả các định dạng gốc ký tự đơn trong cú pháp mô-đun cũng như các biểu diễn đa chiều. chỉ đọc()Trả về phiên bản chỉ đọc của đối tượng memoryview. Đối tượng memoryview ban đầu không thay đổi def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n8 Mới trong phiên bản 3. 8 phát hành()Giải phóng bộ đệm cơ bản được hiển thị bởi đối tượng memoryview. Nhiều đối tượng thực hiện các hành động đặc biệt khi một chế độ xem được giữ trên chúng (ví dụ: chế độ xem sẽ tạm thời cấm thay đổi kích thước); Sau khi phương thức này được gọi, bất kỳ thao tác tiếp theo nào trên chế độ xem đều tăng a (ngoại trừ chính nó có thể được gọi nhiều lần) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n9 Giao thức quản lý bối cảnh có thể được sử dụng cho hiệu ứng tương tự, sử dụng câu lệnh def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6081 >>> (-2.0).is_integer() True >>> (3.2).is_integer() False0 Mới trong phiên bản 3. 2 truyền(định dạng[ , shape])Truyền chế độ xem bộ nhớ sang định dạng hoặc hình dạng mới. hình dạng mặc định là def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6082, có nghĩa là chế độ xem kết quả sẽ là một chiều. Giá trị trả về là một bộ nhớ mới, nhưng bản thân bộ đệm không được sao chép. Các phôi được hỗ trợ là 1D -> C- và C-tiếp giáp -> 1D The destination format is restricted to a single element native format in syntax. One of the formats must be a byte format (‘B’, ‘b’ or ‘c’). Độ dài byte của kết quả phải giống với độ dài ban đầu Truyền 1D/dài thành 1D/byte không dấu >>> (-2.0).is_integer() True >>> (3.2).is_integer() False1 Truyền 1D/byte không dấu thành 1D/char >>> (-2.0).is_integer() True >>> (3.2).is_integer() False2 Truyền 1D/byte thành 3D/int thành 1D/char đã ký >>> (-2.0).is_integer() True >>> (3.2).is_integer() False3 Truyền 1D/dài không dấu thành 2D/dài không dấu >>> (-2.0).is_integer() True >>> (3.2).is_integer() False4 New in version 3. 3 Đã thay đổi trong phiên bản 3. 5. Định dạng nguồn không còn bị hạn chế khi truyền sang chế độ xem byte. Ngoài ra còn có một số thuộc tính chỉ đọc có sẵn đối tượngĐối tượng cơ bản của memoryview >>> (-2.0).is_integer() True >>> (3.2).is_integer() False5 New in version 3. 3 nbytedef bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6084. Đây là lượng không gian tính bằng byte mà mảng sẽ sử dụng trong biểu diễn liền kề. Nó không nhất thiết phải bằng def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6085 >>> (-2.0).is_integer() True >>> (3.2).is_integer() False6 mảng nhiều chiều >>> (-2.0).is_integer() True >>> (3.2).is_integer() False7 New in version 3. 3 chỉ đọcMột bool cho biết bộ nhớ có ở chế độ chỉ đọc hay không định dạngMột chuỗi chứa định dạng (theo kiểu mô-đun) cho từng thành phần trong dạng xem. Một chế độ xem bộ nhớ có thể được tạo từ các trình xuất với các chuỗi định dạng tùy ý, nhưng một số phương thức (e. g. ) bị hạn chế đối với các định dạng phần tử đơn gốc Đã thay đổi trong phiên bản 3. 3. định dạng def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6088 hiện được xử lý theo cú pháp mô-đun cấu trúc. Điều này có nghĩa là def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6089. kích thước mục Kích thước tính bằng byte của từng phần tử của memoryview >>> (-2.0).is_integer() True >>> (3.2).is_integer() False8 Một số nguyên cho biết có bao nhiêu chiều của một mảng nhiều chiều mà bộ nhớ đại diện hình dạngMột bộ số nguyên có độ dài tạo ra hình dạng của bộ nhớ dưới dạng một mảng N chiều Đã thay đổi trong phiên bản 3. 3. An empty tuple instead of def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631 when ndim = 0. sải bước Một bộ số nguyên có độ dài đưa ra kích thước theo byte để truy cập từng phần tử cho từng chiều của mảng Đã thay đổi trong phiên bản 3. 3. An empty tuple instead of def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631 when ndim = 0. bù trừ Được sử dụng nội bộ cho các mảng kiểu PIL. Giá trị chỉ là thông tin c_contigiousMột bool cho biết liệu bộ nhớ có phải là C- New in version 3. 3 f_tiếp giápMột bool cho biết bộ nhớ có phải là Fortran hay không New in version 3. 3 tiếp giápMột bool cho biết liệu bộ nhớ có New in version 3. 3 Đặt loại — ,Một đối tượng tập hợp là một tập hợp không có thứ tự của các đối tượng riêng biệt. Các ứng dụng phổ biến bao gồm kiểm tra tư cách thành viên, loại bỏ các bản trùng lặp khỏi chuỗi và tính toán các phép toán như giao, hợp, hiệu và hiệu đối xứng. (Đối với các bộ chứa khác, hãy xem các lớp , , và tích hợp sẵn và mô-đun. ) Giống như các bộ sưu tập khác, các bộ hỗ trợ def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6100, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6101 và def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6102. Là một tập hợp không có thứ tự, các tập hợp không ghi vị trí phần tử hoặc thứ tự chèn. Theo đó, các bộ không hỗ trợ lập chỉ mục, cắt hoặc hành vi giống như trình tự khác There are currently two built-in set types, and . Loại có thể thay đổi — nội dung có thể được thay đổi bằng các phương thức như def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6106 và >>> (65).to_bytes() b'A'01. Vì nó có thể thay đổi nên nó không có giá trị băm và không thể được sử dụng làm khóa từ điển hoặc làm thành phần của tập hợp khác. Loại là bất biến và — không thể thay đổi nội dung của nó sau khi nó được tạo; Ví dụ: có thể tạo các tập hợp không trống (không phải tập hợp cố định) bằng cách đặt danh sách các phần tử được phân tách bằng dấu phẩy trong dấu ngoặc nhọn. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6109, ngoài hàm tạo Các hàm tạo cho cả hai lớp hoạt động như nhau lớp bộ([có thể lặp lại])class frozenset([iterable])Trả về một đối tượng set hoặc freezeset mới có các phần tử được lấy từ iterable. Các phần tử của một tập hợp phải. Để biểu diễn các tập hợp, các tập hợp bên trong phải là các đối tượng. Nếu iterable không được chỉ định, một bộ trống mới được trả về Các bộ có thể được tạo bằng nhiều cách
Các trường hợp và cung cấp các hoạt động sau (các) ống kínhReturn the number of elements in set s (cardinality of s) x in sKiểm tra x cho tư cách thành viên trong s x không vào sKiểm tra x cho người không phải là thành viên trong s isdisjoint(khác)Trả về def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 nếu tập hợp không có phần tử nào chung với tập hợp khác. Các tập hợp là rời nhau khi và chỉ khi giao của chúng là tập hợp rỗngissubset(other)set <= other Kiểm tra xem mọi phần tử trong tập hợp có thuộc tập hợp khác không đặt < khácKiểm tra xem tập hợp này có phải là tập con thích hợp của tập hợp khác hay không, nghĩa là, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6120issuperset(other)set >= other Kiểm tra xem mọi phần tử trong tập hợp khác có nằm trong tập hợp không đặt > khácKiểm tra xem tập hợp này có phải là tập hợp lớn nhất của tập hợp khác hay không, nghĩa là, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6121công đoàn(*những người khác)set | khác . . Return a new set with elements from the set and all others giao lộ(*các ngã tư khác)set & other & ...Trả về một tập hợp mới với các phần tử chung cho tập hợp và tất cả các phần tử khác sự khác biệt(*khác)set - other - ...Trả về một tập hợp mới với các phần tử trong tập hợp không có trong các phần tử khác symmetric_difference(khác)đặt ^ otherTrả về một tập hợp mới có các phần tử trong tập hợp này hoặc tập hợp khác nhưng không phải cả hai bản sao()Trả lại một bản sao nông của tập hợp Lưu ý, các phiên bản không phải toán tử của , , , , và các phương thức sẽ chấp nhận bất kỳ lần lặp nào làm đối số. Ngược lại, các đối tác dựa trên toán tử của chúng yêu cầu các đối số của chúng được đặt. Điều này loại bỏ các cấu trúc dễ bị lỗi như def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6128 để có thể đọc dễ dàng hơn def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6129 Cả hai và bộ hỗ trợ để đặt so sánh. Hai tập hợp bằng nhau khi và chỉ khi mọi phần tử của mỗi tập hợp đều chứa trong tập hợp kia (mỗi tập hợp này là tập con của tập hợp kia). Một tập hợp nhỏ hơn tập hợp khác khi và chỉ khi tập hợp đầu tiên là tập hợp con thực sự của tập hợp thứ hai (là tập hợp con, nhưng không bằng nhau). Một tập hợp lớn hơn tập hợp khác khi và chỉ khi tập hợp đầu tiên là tập hợp lớn nhất của tập hợp thứ hai (là tập hợp phụ, nhưng không bằng nhau) Các trường hợp được so sánh với các trường hợp dựa trên các thành viên của chúng. Ví dụ: def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6134 trả về def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 và def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6136 cũng vậy So sánh tập hợp con và đẳng thức không tổng quát hóa thành hàm sắp xếp tổng. Ví dụ: hai tập hợp khác nhau bất kỳ không rỗng thì không bằng nhau và không phải là tập con của nhau, vì vậy tất cả các giá trị sau trả về def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6138, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6139, hoặc def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6140 Vì các tập hợp chỉ xác định thứ tự một phần (mối quan hệ tập hợp con), nên đầu ra của phương thức không được xác định cho danh sách các tập hợp Các phần tử của tập hợp, chẳng hạn như các khóa từ điển, phải là Các hoạt động nhị phân kết hợp các trường hợp với trả về loại toán hạng đầu tiên. Ví dụ. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6144 trả về một thể hiện của Bảng sau đây liệt kê các hoạt động khả dụng không áp dụng cho các trường hợp bất biến của cập nhật(*khác)set |= other . .Cập nhật tập hợp, thêm các phần tử từ tất cả các phần tử khác intersection_update(*khác)set &= other & ...Cập nhật tập hợp, chỉ giữ lại các phần tử được tìm thấy trong đó và tất cả các phần tử khác difference_update(*khác)set -= other | .Cập nhật tập hợp, loại bỏ các phần tử được tìm thấy trong các tập hợp khác symmetric_difference_update(khác)đặt ^= otherCập nhật tập hợp, chỉ giữ lại các phần tử được tìm thấy trong một trong hai tập hợp chứ không phải trong cả hai add(elem)Thêm phần tử elem vào tập hợp xóa(elem)Xóa phần tử elem khỏi tập hợp. Tăng nếu elem không được chứa trong tập hợp loại bỏ(elem)Xóa phần tử elem khỏi tập hợp nếu có pop()Xóa và trả về một phần tử tùy ý khỏi tập hợp. Tăng nếu bộ trống xóa()Xóa tất cả các phần tử khỏi tập hợp Lưu ý, các phiên bản không phải toán tử của các phương thức , , và sẽ chấp nhận bất kỳ lần lặp nào làm đối số Lưu ý, đối số elem của phương thức >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 300, , và có thể là một tập hợp. Để hỗ trợ tìm kiếm một bộ đóng băng tương đương, một bộ tạm thời được tạo từ elem Các loại ánh xạ —Một đối tượng ánh xạ các giá trị tới các đối tượng tùy ý. Ánh xạ là các đối tượng có thể thay đổi. Hiện tại chỉ có một loại ánh xạ tiêu chuẩn, từ điển. (Đối với các bộ chứa khác, hãy xem các lớp , , và tích hợp sẵn và mô-đun. ) Các khóa của từ điển hầu như là các giá trị tùy ý. Các giá trị không phải là , nghĩa là các giá trị chứa danh sách, từ điển hoặc các loại có thể thay đổi khác (được so sánh theo giá trị thay vì theo danh tính đối tượng) có thể không được sử dụng làm khóa. Các giá trị so sánh bằng nhau (chẳng hạn như def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 655, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6163 và def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656) có thể được sử dụng thay thế cho nhau để lập chỉ mục cho cùng một mục từ điểnclass dict(**kwargs)class dict(mapping, **kwargs)class dict(iterable, **kwargs) Trả về một từ điển mới được khởi tạo từ một đối số vị trí tùy chọn và một bộ đối số từ khóa có thể trống Từ điển có thể được tạo ra bằng nhiều cách
Nếu không có đối số vị trí nào được đưa ra, một từ điển trống sẽ được tạo. Nếu một đối số vị trí được đưa ra và nó là một đối tượng ánh xạ, thì một từ điển sẽ được tạo với các cặp khóa-giá trị giống như đối tượng ánh xạ. Mặt khác, đối số vị trí phải là một đối tượng. Bản thân mỗi mục trong iterable phải là iterable với chính xác hai đối tượng. Đối tượng đầu tiên của mỗi mục trở thành một khóa trong từ điển mới và đối tượng thứ hai là giá trị tương ứng. Nếu một khóa xuất hiện nhiều lần, giá trị cuối cùng của khóa đó sẽ trở thành giá trị tương ứng trong từ điển mới Nếu các đối số từ khóa được đưa ra, thì các đối số từ khóa và giá trị của chúng sẽ được thêm vào từ điển được tạo từ đối số vị trí. Nếu một khóa đang được thêm đã xuất hiện, thì giá trị từ đối số từ khóa sẽ thay thế giá trị từ đối số vị trí Để minh họa, tất cả các ví dụ sau đều trả về một từ điển bằng def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6173 >>> (-2.0).is_integer() True >>> (3.2).is_integer() False9 Việc cung cấp các đối số từ khóa như trong ví dụ đầu tiên chỉ hoạt động đối với các khóa là mã định danh Python hợp lệ. Mặt khác, bất kỳ khóa hợp lệ nào cũng có thể được sử dụng Đây là các hoạt động mà từ điển hỗ trợ (và do đó, các loại ánh xạ tùy chỉnh cũng sẽ hỗ trợ) danh sách(d)Trả về danh sách tất cả các khóa được sử dụng trong từ điển d cho mượn)Trả về số mục trong từ điển d d[key]Trả lại mục của d bằng phím key. Tăng phím nếu không có trong bản đồ Nếu một lớp con của dict định nghĩa một phương thức def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6175 và không có khóa, thì thao tác def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6176 gọi phương thức đó với đối số là key key. Hoạt động def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6176 sau đó trả lại hoặc tăng bất cứ thứ gì được trả lại hoặc tăng bởi lệnh gọi def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6178. Không có hoạt động hoặc phương pháp nào khác gọi def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6175. Nếu def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6175 không được xác định, được nâng lên. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6175 phải là một phương thức; def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 600 Ví dụ trên cho thấy một phần của việc thực hiện. Một phương pháp def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6184 khác được sử dụng bởid[key] = giá trị Đặt def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6176 thành giá trịdel d[key] Xó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') --> 6176 khỏi d. Tăng phím nếu không có trong bản đồphím vào d Trả lại def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 nếu d có khóa chính, ngược lại def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638phím không vào d Tương đương với def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6191lặp đi lặp lại (d) Return an iterator over the keys of the dictionary. This is a shortcut for def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6192xóa() Xóa tất cả các mục khỏi từ điển bản sao()Trả lại một bản sao nông của từ điển phương thức lớp từ khóa(có thể lặp lại[, value])Tạo một từ điển mới với các khóa từ iterable và các giá trị được đặt thành giá trị là một phương thức lớp trả về một từ điển mới. giá trị mặc định là def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631. Tất cả các giá trị chỉ tham chiếu đến một thể hiện duy nhất, do đó, thông thường giá trị là một đối tượng có thể thay đổi chẳng hạn như một danh sách trống không có ý nghĩa gì. Để nhận các giá trị riêng biệt, hãy sử dụng thay thếlấy(khóa[ , default]) Trả về giá trị cho khóa nếu khóa có trong từ điển, nếu không thì mặc định. Nếu giá trị mặc định không được đưa ra, nó sẽ mặc định là def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631, do đó phương thức này không bao giờ tăngitem() Trả về chế độ xem mới cho các mục của từ điển ( def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6197 cặp). xemphím() Trả lại chế độ xem mới cho các khóa của từ điển. xem bật(phím[ , default])Nếu khóa nằm trong từ điển, hãy xóa nó và trả về giá trị của nó, nếu không thì trả về giá trị mặc định. Nếu giá trị mặc định không được cung cấp và khóa không có trong từ điển, a sẽ tăng popitem()Remove and return 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') --> 6197 pair from the dictionary. Các cặp được trả lại theo thứ tự LIFO rất hữu ích để lặp lại triệt để một từ điển, như thường được sử dụng trong các thuật toán tập hợp. Nếu từ điển trống, việc gọi sẽ tăng Đã thay đổi trong phiên bản 3. 7. Đơn hàng LIFO hiện đã được đảm bảo. Trong các phiên bản trước, sẽ trả về một cặp khóa/giá trị tùy ý. đảo ngược(d)Trả về một trình vòng lặp đảo ngược trên các khóa của từ điển. Đây là lối tắt cho def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6204 Mới trong phiên bản 3. 8 setdefault(key[ , default])Nếu khóa nằm trong từ điển, hãy trả về giá trị của nó. Nếu không, hãy chèn khóa có giá trị mặc định và trả về giá trị mặc định. mặc định mặc định là def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631cập nhật([khác]) Cập nhật từ điển với các cặp khóa/giá trị từ khác, ghi đè lên các khóa hiện có. Trả lại def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631 chấp nhận một đối tượng từ điển khác hoặc một cặp khóa/giá trị có thể lặp lại (dưới dạng bộ dữ liệu hoặc các lần lặp khác có độ dài hai). Nếu các đối số từ khóa được chỉ định, thì từ điển sẽ được cập nhật với các cặp khóa/giá trị đó. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6208giá trị() Trả lại chế độ xem mới về các giá trị của từ điển. xem So sánh bình đẳng giữa một chế độ xem def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6209 và chế độ xem khác sẽ luôn trả về def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638. Điều này cũng áp dụng khi so sánh def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6209 với chính nó def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 601d . khác Tạo một từ điển mới với các khóa và giá trị được hợp nhất của d và khác, cả hai phải là từ điển. Các giá trị của other được ưu tiên khi d và các khóa chia sẻ khác New in version 3. 9 d . = khácCập nhật từ điển d với các khóa và giá trị từ từ khác, có thể là a hoặc một trong các cặp khóa/giá trị. Các giá trị của other được ưu tiên khi d và các khóa chia sẻ khác New in version 3. 9 Dictionaries compare equal if and only if they have the same def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6197 pairs (regardless of ordering). Order comparisons (‘<’, ‘<=’, ‘>=’, ‘>’) raise . Từ điển bảo toàn thứ tự chèn. Lưu ý rằng việc cập nhật khóa không ảnh hưởng đến thứ tự. Các phím được thêm sau khi xóa được chèn vào cuối def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 602 Changed in version 3. 7. Thứ tự từ điển được đảm bảo là thứ tự chèn. Hành vi này là một chi tiết triển khai của CPython từ 3. 6. Từ điển và chế độ xem từ điển có thể đảo ngược def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 603 Đã thay đổi trong phiên bản 3. 8. Từ điển hiện có thể đảo ngược. See also có thể được sử dụng để tạo chế độ xem chỉ đọc của một Các đối tượng xem từ điểnCác đối tượng được trả về và là các đối tượng xem. Chúng cung cấp chế độ xem động cho các mục nhập của từ điển, có nghĩa là khi từ điển thay đổi, chế độ xem sẽ phản ánh những thay đổi này Chế độ xem từ điển có thể được lặp đi lặp lại để mang lại dữ liệu tương ứng và hỗ trợ kiểm tra tư cách thành viên len(dictview)Trả về số mục trong từ điển lặp đi lặp lại (dictview)Trả về một trình vòng lặp trên các khóa, giá trị hoặc mục (được biểu thị dưới dạng bộ dữ liệu củ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') --> 6197) trong từ điển Các khóa và giá trị được lặp lại theo thứ tự chèn. Điều này cho phép tạo ra các cặp def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6220 bằng cách sử dụng. ______________222. Một cách khác để tạo danh sách tương tự là def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6223 Lặp lại các dạng xem trong khi thêm hoặc xóa các mục trong từ điển có thể gây ra hoặc không thể lặp lại trên tất cả các mục Đã thay đổi trong phiên bản 3. 7. Thứ tự từ điển được đảm bảo là thứ tự chèn. x in dictviewTrả về def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 nếu x nằm trong các khóa, giá trị hoặc mục của từ điển cơ sở (trong trường hợp sau, x phải là bộ dữ liệu def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6197)đảo ngược (dictview) Trả về một trình lặp đảo ngược trên các khóa, giá trị hoặc mục của từ điển. Chế độ xem sẽ được lặp lại theo thứ tự ngược lại của phần chèn Đã thay đổi trong phiên bản 3. 8. Chế độ xem từ điển hiện có thể đảo ngược. chế độ xem chính tả. lập bản đồTrả lại a bao bọc từ điển gốc mà chế độ xem đề cập đến New in version 3. 10 Chế độ xem khóa giống như được đặt vì các mục nhập của chúng là duy nhất và có thể băm. Nếu tất cả các giá trị đều có thể băm, để các cặp def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6197 là duy nhất và có thể băm, thì chế độ xem các mục cũng giống như được đặt. (Chế độ xem giá trị không được coi là giống như tập hợp vì các mục thường không phải là duy nhất. ) Đối với các khung nhìn dạng tập hợp, tất cả các thao tác được định nghĩa cho lớp cơ sở trừu tượng đều khả dụng (ví dụ: def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 678, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 674 hoặc def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6232) Một ví dụ về việc sử dụng chế độ xem từ điển def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 604 Các loại trình quản lý bối cảnhCâu lệnh của Python hỗ trợ khái niệm bối cảnh thời gian chạy được xác định bởi trình quản lý bối cảnh. Điều này được thực hiện bằng cách sử dụng một cặp phương thức cho phép các lớp do người dùng định nghĩa xác định bối cảnh thời gian chạy được nhập vào trước khi phần thân câu lệnh được thực thi và thoát khi câu lệnh kết thúc trình quản lý ngữ cảnh. __enter__()Nhập bối cảnh thời gian chạy và trả về đối tượng này hoặc đối tượng khác liên quan đến bối cảnh thời gian chạy. Giá trị được phương thức này trả về được liên kết với mã định danh trong mệnh đề def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6234 của các câu lệnh sử dụng trình quản lý ngữ cảnh này An example of a context manager that returns itself is a . Các đối tượng tệp tự trả về từ __enter__() để cho phép được sử dụng làm biểu thức ngữ cảnh trong câu lệnh Một ví dụ về trình quản lý bối cảnh trả về một đối tượng liên quan là đối tượng được trả về bởi. Các trình quản lý này đặt ngữ cảnh thập phân đang hoạt động thành một bản sao của ngữ cảnh thập phân ban đầu rồi trả lại bản sao. Điều này cho phép thực hiện các thay đổi đối với ngữ cảnh thập phân hiện tại trong phần thân của câu lệnh mà không ảnh hưởng đến mã bên ngoài câu lệnh def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6081trình quản lý ngữ cảnh. __exit__(exc_type , exc_val, exc_tb) Thoát khỏi bối cảnh thời gian chạy và trả về một cờ Boolean cho biết liệu có nên loại bỏ bất kỳ ngoại lệ nào xảy ra hay không. Nếu một ngoại lệ xảy ra trong khi thực thi phần thân của câu lệnh, thì các đối số chứa loại ngoại lệ, giá trị và thông tin truy nguyên. Mặt khác, cả ba đối số đều là def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631 Trả về giá trị thực từ phương thức này sẽ khiến câu lệnh chặn ngoại lệ và tiếp tục thực hiện với câu lệnh ngay sau câu lệnh def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6081. Mặt khác, ngoại lệ tiếp tục lan truyền sau khi phương thức này thực hiện xong. Các ngoại lệ xảy ra trong quá trình thực thi phương thức này sẽ thay thế bất kỳ ngoại lệ nào xảy ra trong phần thân của câu lệnh def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6081 Ngoại lệ được truyền vào không bao giờ được gọi lại một cách rõ ràng - thay vào đó, phương thức này sẽ trả về một giá trị sai để cho biết rằng phương thức đã hoàn thành thành công và không muốn chặn ngoại lệ đã nêu. Điều này cho phép mã quản lý bối cảnh dễ dàng phát hiện xem một phương thức có thực sự bị lỗi hay không Python định nghĩa một số trình quản lý ngữ cảnh để hỗ trợ đồng bộ hóa luồng dễ dàng, đóng nhanh tệp hoặc các đối tượng khác và thao tác đơn giản hơn đối với ngữ cảnh số học thập phân đang hoạt động. Các loại cụ thể không được xử lý đặc biệt ngoài việc thực hiện giao thức quản lý ngữ cảnh. Xem mô-đun để biết một số ví dụ Python's và trình trang trí cung cấp một cách thuận tiện để triển khai các giao thức này. Nếu một hàm tạo được trang trí bằng trình tạo trang trí, thì nó sẽ trả về trình quản lý ngữ cảnh thực hiện các phương thức và cần thiết, thay vì trình vòng lặp được tạo bởi hàm tạo không được trang trí Note that there is no specific slot for any of these methods in the type structure for Python objects in the Python/C API. Extension types wanting to define these methods must provide them as a normal Python accessible method. So với chi phí thiết lập bối cảnh thời gian chạy, chi phí hoạt động của một tra cứu từ điển một lớp là không đáng kể Nhập các loại chú thích — ,Các loại tích hợp sẵn cốt lõi cho are và Loại bí danh chungdef bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6252 đối tượng thường được tạo bởi một lớp. Chúng thường được sử dụng với , chẳng hạn như hoặc. Ví dụ: def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6255 là một đối tượng def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6252 được tạo bằng cách đăng ký lớp def bit_count(self): return bin(self).count("1")93 với đối số. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6252 đối tượng được dự định chủ yếu để sử dụng với Note Nói chung, chỉ có thể đăng ký một lớp nếu lớp đó thực hiện phương thức đặc biệt Một đối tượng def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6252 hoạt động như một proxy cho một , triển khai các generic được tham số hóa Đối với một lớp chứa, (các) đối số được cung cấp cho một lớp có thể chỉ ra (các) loại phần tử mà một đối tượng chứa. Ví dụ: def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6262 có thể được sử dụng trong chú thích loại để biểu thị một trong đó tất cả các phần tử đều thuộc loại Đối với một lớp xác định nhưng không phải là vùng chứa, (các) đối số được cung cấp cho đăng ký của lớp thường sẽ chỉ ra (các) kiểu trả về của một hoặc nhiều phương thức được xác định trên một đối tượng. Ví dụ, có thể được sử dụng trên cả kiểu dữ liệu và kiểu dữ liệu
Các đối tượng def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6252 là các thể hiện của lớp, cũng có thể được sử dụng để tạo trực tiếp các đối tượng def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6252T[X, Y, . ] Tạo một def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6252 đại diện cho một loại def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6289 được tham số hóa bởi các loại X, Y, v.v. tùy thuộc vào def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6289 được sử dụng. Ví dụ: một hàm mong đợi một phần tử chứ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') --> 605 Một ví dụ khác cho các đối tượng, sử dụng a , là loại chung mong đợi hai tham số loại đại diện cho loại khóa và loại giá trị. Trong ví dụ này, hàm mong đợi mộ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'68 với các khóa thuộc loại và các giá trị thuộc loại def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 606 Các hàm dựng sẵn và không chấp nhận các loại def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6252 cho đối số thứ hai của chúng def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 607 Thời gian chạy Python không thực thi. Điều này mở rộng đến các loại chung và các tham số loại của chúng. Khi tạo đối tượng vùng chứa từ def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6252, các phần tử trong vùng chứa không được kiểm tra đối với loại của chúng. Ví dụ: đoạn mã sau không được khuyến khích nhưng sẽ chạy không có lỗi def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 608 Hơn nữa, các tham số loại được tham số hóa xóa các tham số loại trong quá trình tạo đối tượng def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 609 Gọi hoặc trên chung hiển thị loại được tham số hó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') --> 610 Phương pháp của các thùng chứa chung sẽ đưa ra một ngoại lệ để không cho phép các lỗi như def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6304 def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 611 Tuy nhiên, các biểu thức như vậy có giá trị khi được sử dụng. The index must have as many elements as there are type variable items in 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') --> 6252 object’s def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 612 Các lớp chung tiêu chuẩnCác lớp thư viện tiêu chuẩn sau đây hỗ trợ các generic được tham số hóa. danh sách này là không đầy đủ Thuộc tính đặc biệt của |