Python tìm chuỗi trong danh sách
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 nhận dạng đố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') --> 681 danh tính đối tượng phủ nhận 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. Toán 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') --> 678 luôn được xác định nhưng đối với một số loại đối tượng (ví dụ: đối tượng lớp) tương đương với. Các toán 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') --> 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 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') --> 677 chỉ được xác định khi chúng có ý nghĩa; Các thể hiện không giống nhau của một lớp thường được so sánh là không bằng nhau trừ khi lớp đó định nghĩa phương thức Các thể hiện của một lớp không thể được sắp xếp theo thứ tự đối với các thể hiện khác của cùng một lớp hoặc các loại đối tượng khác, trừ khi lớp đó định nghĩa đủ các phương thức , , , và (nói chung là đủ, nếu bạn muốn ý nghĩa quy ước của Không thể tùy chỉnh hành vi của toán tử và; Hai thao tác nữa có cùng mức ưu tiên cú pháp và , được hỗ trợ bởi các loại hoặc triển khai phương thức >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 300 Các loại số — , ,Có ba loại số riêng biệt. số nguyên, số dấu phẩy động và số phức. Ngoài ra, Booleans là một kiểu con của số nguyên. Số nguyên có độ chính xác không giới hạn. Số dấu phẩy động thường được triển khai bằng cách sử dụng double trong C; . Số phức có phần thực và phần ảo, mỗi phần là một số dấu chấm động. Để trích xuất các phần này từ một số phức z, hãy sử dụng >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 305 và >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 306. (Thư viện chuẩn bao gồm các loại số bổ sung , cho số hữu tỷ và , cho số dấu phẩy động với độ chính xác do người dùng xác định. ) Các số được tạo bởi các chữ số hoặc là kết quả của các hàm và toán tử tích hợp. Các số nguyên nguyên không tô điểm (bao gồm cả số hex, bát phân và nhị phân) mang lại số nguyên. Chữ số có chứa dấu thập phân hoặc dấu mũ mang lại số dấu phẩy động. Việc thêm >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 309 hoặc >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 310 vào một chữ số sẽ tạo ra một số ảo (một số phức có phần thực bằng 0) mà bạn có thể thêm vào một số nguyên hoặc dấu phẩy động để nhận được một số phức có phần thực và phần ảo Python hỗ trợ đầy đủ số học hỗn hợp. khi một toán tử số học nhị phân có các toán hạng thuộc các kiểu số khác nhau, thì toán hạng có loại "hẹp hơn" được mở rộng sang toán hạng kia, trong đó số nguyên hẹp hơn dấu phẩy động, hẹp hơn phức hợp. So sánh giữa các số thuộc các loại khác nhau hoạt động như thể các giá trị chính xác của các số đó đang được so sánh. Các hàm tạo , , và có thể được sử dụng để tạo các số thuộc một loại cụ thể Tất cả các loại số (ngoại trừ phức tạp) đều hỗ trợ các thao tác sau (để biết mức độ ưu tiên của các thao tác, xem phần ) Hoạt động Kết quả ghi chú tài liệu đầy đủ >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 314 tổng của x và y >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 315 sự khác biệt của x và y >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 316 sản phẩm của x và y >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 317 thương của x và y >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 318 thương số sàn của x và 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 phủ nhận >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 322 x không thay đổi >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 323 giá trị tuyệt đối hoặc độ lớn của x >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 325 x chuyển thành số nguyên (3)(6) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 327 x được chuyển đổi thành dấu phẩy động (4)(6) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 329 số phức có phần thực là phần ảo. tôi mặc định là không (6) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 331 liên hợp của số phức c >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 332 cặp >>> 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 lũy thừa y (5) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 337 x lũy thừa y (5) ghi chú
Tất cả các loại ( và ) cũng bao gồm các thao tác sau Hoạt động Kết quả x cắt ngắn thành x làm tròn đến n chữ số, làm tròn một nửa thành chẵn. Nếu n bị bỏ qua, nó mặc định là 0 lớn nhất <= x nhỏ nhất >= x Đối với các hoạt động số bổ sung, hãy xem và mô-đun Hoạt động Bitwise trên các loại số nguyênHoạt động bitwise chỉ có ý nghĩa đối với số nguyên. Kết quả của các hoạt động theo bit được tính toán như thể được thực hiện trong phần bù hai với số lượng bit dấu vô hạn Tất cả các ưu tiên của các phép toán bitwise nhị phân đều thấp hơn các phép toán số và cao hơn các phép so sánh; Bảng này liệt kê các hoạt động bitwise được sắp xếp theo mức độ ưu tiên tăng dần Hoạt động Kết quả ghi chú >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 371 bitwise hoặc của x và y (4) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 372 loại trừ theo bit hoặc của x và y (4) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 373 bitwise và của x và y (4) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 374 x dịch sang trái n bit (1)(2) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 375 x dịch sang phải n bit (1)(3) >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 376 các bit của x đảo ngược ghi chú
Các phương thức bổ sung trên các kiểu số nguyênKiểu int thực hiện. Ngoài ra nó còn cung cấp thêm một số phương pháp int. bit_length()Trả về số bit cần thiết để biểu diễn một số nguyên ở dạng nhị phân, không bao gồm dấu và các số 0 ở đầu >>> n = -37 >>> bin(n) '-0b100101' >>> n.bit_length() 6 Chính xác hơn, nếu >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 382 khác 0, thì >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 383 là số nguyên dương duy nhất >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 384 sao cho >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 385. Tương tự, khi >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 323 đủ nhỏ để có logarit được làm tròn chính xác, thì >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 387. Nếu >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 382 bằng 0, thì >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 383 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 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') --> 6 Mới trong phiên bản 3. 1 int. bit_count()Trả về số đơn vị trong biểu diễn nhị phân của giá trị tuyệt đối của số nguyên. Đây còn được gọi là số lượng dân số. Ví dụ >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3 Tương đương với def bit_count(self): return bin(self).count("1") Mới trong phiên bản 3. 10 int. to_byte(độ dài=1, byteorder='big', *, signed=False)Trả về một mảng byte đại diện cho một số nguyên >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' Số nguyên được biểu diễn bằng byte độ dài và mặc định là 1. An được nâng lên nếu số nguyên không thể biểu thị được với số byte đã cho Đố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 Đố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. Nếu được ký 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 và một số nguyên âm được đưa ra, thì an được nâng lên. Giá trị mặc định cho đã ký 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 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. Tuy nhiên, khi sử dụng các đối số mặc định, đừng cố chuyển đổi một giá trị lớn hơn 255, nếu không bạn sẽ nhận được một >>> (65).to_bytes() b'A' Tương đương với def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': 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 Tương đương vớ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 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
Để làm rõ các quy tắc trên, đây là một số mã Python ví dụ, tương đương với hàm băm tích hợp, để tính toán hàm băm của một số hữu tỷ, 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') --> 63 Các loại trình lặpPython hỗ trợ khái niệm lặp qua các vùng chứa. Điều này được thực hiện bằng hai phương pháp riêng biệt; . Các trình tự, được mô tả chi tiết hơn bên dưới, luôn hỗ trợ các phương pháp lặp Một phương thức cần được xác định cho các đối tượng vùng chứa để cung cấp hỗ trợ vùng chứa. __iter__()Trả lại một đối tượng. Đối tượng được yêu cầu hỗ trợ giao thức iterator được mô tả bên dưới. 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 lặp cho các kiểu lặp đó. (Ví dụ về một đối tượng hỗ trợ nhiều hình thức lặp sẽ là một cấu trúc cây hỗ trợ cả truyền tải theo chiều rộng và theo chiều sâu. ) Phương thức này tương ứng với vị trí của cấu trúc kiểu cho các đối tượng Python trong API Python/C Bản thân các đối tượng lặp được yêu cầu hỗ trợ hai phương thức sau, cùng nhau tạo thành giao thức lặp trình lặp. __iter__()Trả lại chính đối tượng. Điều này là bắt buộc để cho phép sử dụng cả bộ chứa và bộ lặp với câu lệnh và. Phương thức này tương ứng với vị trí của cấu trúc kiểu cho các đối tượng Python trong API Python/C trình lặp. __next__()Trả lại mục tiếp theo từ. Nếu không có mục nào khác, hãy đưa ra ngoại lệ. Phương thức này tương ứng với vị trí của cấu trúc kiểu cho các đối tượng Python trong API Python/C Python định nghĩa một số đối tượng trình lặp để hỗ trợ phép lặp qua các loại trình tự chung và cụ thể, từ điển và các dạng chuyên biệt hơn khác. Các loại cụ thể không quan trọng ngoài việc triển khai giao thức lặp Khi một phương thức của trình vòng lặp tăng lên, nó phải tiếp tục làm như vậy trong các lần gọi tiếp theo. Việc triển khai không tuân theo thuộc tính này được coi là bị hỏng Các loại máy phát điệnPython cung cấp một cách thuận tiện để triển khai giao thức lặp. Nếu phương thức def bit_count(self): return bin(self).count("1")90 của đối tượng vùng chứa được triển khai như một trình tạo, thì nó sẽ tự động trả về một đối tượng trình vòng lặp (về mặt kỹ thuật, một đối tượng trình tạo) cung cấp def bit_count(self): return bin(self).count("1")90 và các phương thức. Thông tin thêm về máy phát điện có thể được tìm thấy trong Các loại trình tự — , ,Có ba loại trình tự cơ bản. danh sách, bộ dữ liệu và đối tượng phạm vi. Các loại trình tự bổ sung được điều chỉnh để xử lý và được mô tả trong các phần dành riêng Hoạt động tuần tự phổ biếnCác hoạt động trong bảng sau được hỗ trợ bởi hầu hết các loại trình tự, cả có thể thay đổi và không thể thay đổi. ABC được cung cấp để giúp triển khai chính xác các thao tác này trên các loại trình tự tùy chỉnh dễ dàng hơn Bảng này liệt kê các hoạt động trình tự được sắp xếp theo mức độ ưu tiên tăng dần. Trong bảng, s và t là các chuỗi cùng loại, n, i, j và k là các số nguyên và x là một đối tượng tùy ý đáp ứng mọi hạn chế về loại và giá trị do s áp đặt Các phép toá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') --> 698 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') --> 699 có cùng mức độ ưu tiên như các phép toán so sánh. Các phép toán >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 369 (nối) và >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\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 (lặp lại) có cùng mức độ ưu tiên như các phép toán số tương ứng. 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 nếu một mục của s bằng x, 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') --> 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 nếu một phần tử của s bằng x, 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') --> 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 nối của s và 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 hoặc >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\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 tương đương với việc thêm s vào chính nó n lần (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 mục thứ i của s, gốc 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 lát s từ i đến 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 lát s từ i đến j với bước 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 chiều dài 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'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 mục lớn 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'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) (số 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 tổng số lần xuất hiện của x trong s Các chuỗi cùng loại cũng hỗ trợ so sánh. Cụ thể, các bộ dữ liệu và danh sách được so sánh theo từ điển bằng cách so sánh các phần tử tương ứng. Điều này có nghĩa là để so sánh bằng nhau, mọi phần tử phải so sánh bằng nhau và hai dãy phải cùng loại và có cùng độ dài. (Để biết đầy đủ chi tiết xem trong tài liệu tham khảo ngôn ngữ. ) Các trình vòng lặp chuyển tiếp và đảo ngược qua các chuỗi có thể thay đổi truy cập các giá trị bằng chỉ mục. Chỉ số đó sẽ tiếp tục tiến (hoặc lùi) ngay cả khi trình tự cơ bản bị đột biến. Trình vòng lặp chỉ kết thúc khi gặp an hoặc a (hoặc khi chỉ số giảm xuống dưới 0) ghi chú
Các loại trình tự bất biếnThao tác duy nhất mà các loại trình tự bất biến thường triển khai mà các loại trình tự có thể thay đổi cũng không triển khai là hỗ trợ cho trình tự tích hợp sẵn Hỗ trợ này cho phép các chuỗi bất biến, chẳng hạn như phiên bản, được sử dụng làm khóa và được lưu trữ trong và phiên bản Cố gắng băm một chuỗi bất biến có chứa các giá trị không thể băm được sẽ dẫn đến Các loại trình tự có thể thay đổiCác hoạt động trong bảng sau được xác định trên các loại trình tự có thể thay đổi. ABC được cung cấp để giúp triển khai chính xác các thao tác này trên các loại trình tự tùy chỉnh dễ dàng hơn Trong bảng s là một thể hiện của loại trình tự có thể thay đổi, t là bất kỳ đối tượng có thể lặp lại nào và x là một đối tượng tùy ý đáp ứng mọi hạn chế về loại và giá trị do s áp đặt (ví dụ: chỉ chấp nhận các số nguyên đáp ứng hạn chế về giá trị >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\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 mục i của s được thay thế bằng 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 lát s từ i đến j được thay thế bằng nội dung của 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 giống như >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\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 các phần tử của >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\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 được thay thế bằng các phần tử của 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 xóa các phần tử của >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\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 khỏi danh sá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'83 nối x vào cuối dãy (giống như >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\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 xóa tất cả các mục khỏi s (giống như >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\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 tạo một bản sao nông của s (giống như >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\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 hoặc >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\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 kéo dài s với nội dung của t (phần lớn giống như >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\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 cập nhật s với nội dung được lặp lại n lần (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 chèn x vào s tại chỉ số được cung cấp bởi i (giống như >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\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 hoặc >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\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 truy xuất mục tại i và cũng xóa mục đó khỏi 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 xóa mục đầu tiên khỏi s trong đó >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\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 bằng 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 đảo ngược các mục của s tại chỗ (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
Hàm tạo xây dựng một danh sách có các mục giống nhau và theo cùng thứ tự với các mục của iterable. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a list, a copy is made and returned, similar to >>> (65).to_bytes() b'A'20. For example, >>> (65).to_bytes() b'A'21 returns >>> (65).to_bytes() b'A'22 and >>> (65).to_bytes() b'A'23 returns >>> (65).to_bytes() b'A'24. If no argument is given, the constructor creates a new empty list, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 649 Many other operations also produce lists, including the built-in Lists implement all of the and sequence operations. Lists also provide the following additional method sort(* , key=None , reverse=False)This method sorts the list in place, using only def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 674 comparisons between items. Exceptions are not suppressed - if any comparison operations fail, the entire sort operation will fail (and the list will likely be left in a partially modified state) accepts two arguments that can only be passed by keyword () key specifies a function of one argument that is used to extract a comparison key from each list element (for example, >>> (65).to_bytes() b'A'29). The key corresponding to each item in the list is calculated once and then used for the entire sorting process. The default value of def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631 means that list items are sorted directly without calculating a separate key value The utility is available to convert a 2. x style cmp function to a key function reverse is a boolean value. If set to def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656, then the list elements are sorted as if each comparison were reversed This method modifies the sequence in place for economy of space when sorting a large sequence. To remind users that it operates by side effect, it does not return the sorted sequence (use to explicitly request a new sorted list instance) The method is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade) For sorting examples and a brief sorting tutorial, see CPython implementation detail. While a list is being sorted, the effect of attempting to mutate, or even inspect, the list is undefined. The C implementation of Python makes the list appear empty for the duration, and raises if it can detect that the list has been mutated during a sort TuplesTuples are immutable sequences, typically used to store collections of heterogeneous data (such as the 2-tuples produced by the built-in). Tuples are also used for cases where an immutable sequence of homogeneous data is needed (such as allowing storage in a or instance) class tuple([iterable])Tuples may be constructed in a number of ways
The constructor builds a tuple whose items are the same and in the same order as iterable’s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a tuple, it is returned unchanged. For example, >>> (65).to_bytes() b'A'47 returns >>> (65).to_bytes() b'A'48 and >>> (65).to_bytes() b'A'49 returns >>> (65).to_bytes() b'A'50. If no argument is given, the constructor creates a new empty tuple, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 648 Note that it is actually the comma which makes a tuple, not the parentheses. The parentheses are optional, except in the empty tuple case, or when they are needed to avoid syntactic ambiguity. For example, >>> (65).to_bytes() b'A'52 is a function call with three arguments, while >>> (65).to_bytes() b'A'53 is a function call with a 3-tuple as the sole argument Tuples implement all of the sequence operations For heterogeneous collections of data where access by name is clearer than access by index, may be a more appropriate choice than a simple tuple object RangesThe type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in loops class range(stop)class range(start , stop[ , step])The arguments to the range constructor must be integers (either built-in or any object that implements the special method). If the step argument is omitted, it defaults to def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 655. If the start argument is omitted, it defaults to def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 642. If step is zero, is raised 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 Đối với bước phủ định, nội dung của phạm vi vẫn được xác định theo công thức >>> (65).to_bytes() b'A'63, nhưng các ràng buộc là >>> (65).to_bytes() b'A'64 và >>> (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). Mới trong phiên bản 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. lớp str(đối tượng='')class str(object=b'', encoding='utf-8', errors='strict') Return a version of object. If object is not provided, returns the empty string. Otherwise, the behavior of def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 633 depends on whether encoding or errors is given, as follows If neither encoding nor errors is given, def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)09 returns , which is the “informal” or nicely printable string representation of object. For string objects, this is the string itself. If object does not have a method, then falls back to returning If at least one of encoding or errors is given, object should be a (e. g. or ). In this case, if object is a (or ) object, then def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)18 is equivalent to . Otherwise, the bytes object underlying the buffer object is obtained before calling . See and for information on buffer objects Passing a object to without the encoding or errors arguments falls under the first case of returning the informal string representation (see also the command-line option to Python). For example def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 69 For more information on the >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'22 class and its methods, see and the section below. To output formatted strings, see the and sections. In addition, see the section String MethodsStrings implement all of the sequence operations, along with the additional methods described below Strings also support two styles of string formatting, one providing a large degree of flexibility and customization (see , and ) and the other based on C def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)26 style formatting that handles a narrower range of types and is slightly harder to use correctly, but is often faster for the cases it can handle () 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. If the character is a tab ( def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)46), one or more space characters are inserted in the result until the current column is equal to the next tab position. (The tab character itself is not copied. ) If the character is a newline ( def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)47) or return ( def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)48), it is copied and the current column is reset to zero. Any other character is copied unchanged and the current column is incremented by one regardless of how the character is represented when printed >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 30str. find(sub[ , start[ , end]]) Return the lowest index in the string where substring sub is found within the slice def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)49. Optional arguments start and end are interpreted as in slice notation. Return >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 341 if sub is not found Note The method should be used only if you need to know the position of sub. To check if sub is a substring or not, use the operator >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 31str. format(*args , **kwargs) Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 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. Nonprintable characters are those characters defined in the Unicode character database as “Other” or “Separator”, excepting the ASCII space (0x20) which is considered printable. (Note that printable characters in this context are those which should not be escaped when is invoked on a string. It has no bearing on the handling of strings written to or . )str. isspace() Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if there are only whitespace characters in the string and there is at least one character, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 otherwise A character is whitespace if in the Unicode character database (see ), either its general category is >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168009 (“Separator, space”), or its bidirectional class is one of >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168010, >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168011, or >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168012str. istitle() Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 otherwisestr. isupper() Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if all cased characters in the string are uppercase and there is at least one cased character, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 otherwise >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 35str. join(iterable) Return a string which is the concatenation of the strings in iterable. A will be raised if there are any non-string values in iterable, including objects. The separator between elements is the string providing this method str. ljust(width[ , fillchar])Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'13str. lower() Return a copy of the string with all the cased characters converted to lowercase The lowercasing algorithm used is described in section 3. 13 of the Unicode Standard str. lstrip([chars])Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631, the chars argument defaults to removing whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 36 See for a method that will remove a single prefix string rather than all of a set of characters. For example >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 37static str. maketrans(x[ , y[ , z]]) This static method returns a translation table usable for If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631. Character keys will then be converted to ordinals Nếu có hai đối số, chúng phải là các chuỗi có độ dài bằng nhau và trong từ điển kết quả, mỗi ký tự trong x sẽ được ánh xạ tới ký tự ở cùng vị trí trong 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. phân vùng(sep) Tách chuỗi ở lần xuất hiện đầu tiên của sep và trả về 3-tuple chứa phần trước dấu phân cách, chính dấu phân cách và phần sau dấu phân cách. 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 Mới trong phiên bản 3. 9 str. removesuffix(suffix , /)If the string ends with the suffix string and that suffix is not empty, return >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168026. Otherwise, return a copy of the original string >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 39 Mới trong phiên bản 3. 9 str. replace(old , new[ , count])Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced str. rfind(sub[ , start[ , end]])Return the highest index in the string where substring sub is found, such that sub is contained within def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)49. Optional arguments start and end are interpreted as in slice notation. Return >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 341 on failurestr. rindex(sub[ , start[ , end]]) Like but raises when the substring sub is not found str. rjust(width[ , fillchar])Return the string right justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'13str. rpartition(sep) Split the string at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself str. rsplit(sep=None , maxsplit=- 1)Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631, any whitespace string is a separator. Except for splitting from the right, behaves like which is described in detail belowstr. rstrip([chars]) Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631, the chars argument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped def bit_count(self): return bin(self).count("1")0 See for a method that will remove a single suffix string rather than all of a set of characters. For example def bit_count(self): return bin(self).count("1")1str. split(sep=None , maxsplit=- 1) 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(prefix[ , start[ , end]]) Return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 656 if string starts with the prefix, otherwise return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that positionstr. dải([ký tự]) 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. hoán đổi() Return a copy of the string with uppercase characters converted to lowercase and vice versa. Note that it is not necessarily true that >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168067str. title() Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase For example def bit_count(self): return bin(self).count("1")9 The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'0 The function does not have this problem, as it splits words on spaces only Alternatively, a workaround for apostrophes can be constructed using regular expressions >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'1str. translate(table) Return a copy of the string in which each character has been mapped through the given translation table. The table must be an object that implements indexing via >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168069, typically a or . When indexed by a Unicode ordinal (an integer), the table object can do any of the following. return a Unicode ordinal or a string, to map the character to one or more other characters; return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631, to delete the character from the return string; or raise a exception, to map the character to itself You can use to create a translation map from character-to-character mappings in different formats See also the module for a more flexible approach to custom character mappings str. upper()Return a copy of the string with all the cased characters converted to uppercase. Note that >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168074 might be def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638 if def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)94 contains uncased characters or if the Unicode category of the resulting character(s) is not “Lu” (Letter, uppercase), but e. g. “Lt” (Letter, titlecase) The uppercasing algorithm used is described in section 3. 13 of the Unicode Standard str. zfill(width)Return a copy of the string left filled with ASCII >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168077 digits to make a string of length width. A leading sign prefix ( >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168078/ >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168079) is handled by inserting the padding after the sign character rather than before. The original string is returned if width is less than or equal to >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'13 For example >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'2 def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order) 26-style String FormattingNote The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer , the interface, or may help avoid these errors. Each of these alternatives provides their own trade-offs and benefits of simplicity, flexibility, and/or extensibility String objects have one unique built-in operation. the >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168083 operator (modulo). This is also known as the string formatting or interpolation operator. Given >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168084 (where format is a string), >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168083 conversion specifications in format are replaced with zero or more elements of values. The effect is similar to using the >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168086 in the C language If format requires a single argument, values may be a single non-tuple object. Otherwise, values must be a tuple with exactly the number of items specified by the format string, or a single mapping object (for example, a dictionary) A conversion specifier contains two or more characters and has the following components, which must occur in this order
When the right argument is a dictionary (or other mapping type), then the formats in the string must include a parenthesised mapping key into that dictionary inserted immediately after the >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168087 character. The mapping key selects the value to be formatted from the mapping. For example >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'3 In this case no >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'00 specifiers may occur in a format (since they require a sequential parameter list) The conversion flag characters are Flag 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 Chuỗi (chuyển đổi bất kỳ đối tượng Python nào bằng cách sử dụng) (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 Chuỗi (chuyển đổi bất kỳ đối tượng Python nào bằng cách sử dụng) (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 Chuỗi (chuyển đổi bất kỳ đối tượng Python nào bằng cách sử dụng) (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 Không có đối số nào được chuyển đổi, dẫn đến một 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 trong kết quả ghi chú
Since Python strings have an explicit length, def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n36 conversions do not assume that def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n37 is the end of the string Changed in version 3. 1. def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n38 conversions for numbers whose absolute value is over 1e50 are no longer replaced by def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n39 conversions. Binary Sequence Types — , ,The core built-in types for manipulating binary data are and . They are supported by which uses the to access the memory of other binary objects without needing to make a copy The module supports efficient storage of basic data types like 32-bit integers and IEEE754 double-precision floating values Bytes 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 Đã thay đổi trong phiên bản 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
Vì các đối tượng mảng phụ có thể thay đổi, nên chúng hỗ trợ các hoạt động tuần tự ngoài các hoạt động byte và mảng phụ phổ biến được mô tả trong Also see the built-in Vì 2 chữ số thập lục phân tương ứng chính xác với một byte đơn, số thập lục phân là định dạng thường được sử dụng để mô tả dữ liệu nhị phân. Theo đó, kiểu bytearray có thêm một phương thức lớp để đọc dữ liệu ở định dạng đó classmethod fromhex(string)Phương thức lớp này trả về đối tượng bytearray, giải mã đối tượng chuỗi đã cho. Chuỗi phải chứa hai chữ số thập lục phân trên mỗi byte, bỏ qua khoảng trắng ASCII >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\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 Đã thay đổi trong phiên bản 3. 7. now skips all ASCII whitespace in the string, not just spaces. Hàm chuyển đổi ngược tồn tại để chuyển đổi một đối tượng bytearray thành biểu diễn thập lục phân của nó 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. Tương tự như , giờ đây hỗ trợ các tham số sep và bytes_per_sep tùy chọn để chèn dấu phân cách giữa các byte trong đầu ra hex. Vì các đối tượng bytearray là chuỗi các số nguyên (tương tự như một danh sách), đối với một đối tượng bytearray 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 sẽ là một số nguyên, trong khi def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 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 sẽ là một đối tượng bytearray có độ dài 1. (Điều này trái ngược với các chuỗi văn bản, trong đó cả lập chỉ mục và cắt sẽ tạo ra một chuỗi có độ dài 1) Việc biểu diễn các đối tượng bytearray sử dụng định dạng byte bằng 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 n78) vì nó thường hữu ích hơn 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. Bạn luôn có thể chuyển đổi một đối tượng bytearray thành một danh sách các số nguyên bằng cách sử dụ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 n65 Byte và hoạt động BytearrayCả hai đối tượng byte và bytearray đều hỗ trợ các hoạt động trình tự. Chúng tương tác với nhau không chỉ với các toán hạng cùng loại mà với bất kỳ. Do tính linh hoạt này, chúng có thể được trộn lẫn tự do trong các hoạt động mà không gây ra lỗi. Tuy nhiên, kiểu trả về của kết quả có thể phụ thuộc vào thứ tự của các toán hạng Note Các phương thức trên các đối tượng byte và bytearray không chấp nhận các chuỗi làm đối số của chúng, giống như các phương thức trên các chuỗi không chấp nhận các byte làm đối số của chúng. Ví dụ, bạn phải viế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'9 và >>> (65).to_bytes() b'A'0 Một số hoạt động byte và bytearray giả sử sử dụng định dạng nhị phân tương thích ASCII và do đó nên tránh khi làm việc với dữ liệu nhị phân tùy ý. Những hạn chế này được đề cập dưới đây Note Sử dụng các hoạt động dựa trên ASCII này để thao tác dữ liệu nhị phân không được lưu trữ ở định dạng dựa trên ASCII có thể dẫn đến hỏng dữ liệu Có thể sử dụng các phương thức sau trên đối tượng byte và bytearray với dữ liệu nhị phân tùy ý byte. đếm(phụ[ , . start[, end]])bytearray.đếm(phụ[ , start[, end]])Trả về số lần xuất hiện không trùng lặp của subsequence sub trong phạm vi [bắt đầu, kết thúc]. Các đối số tùy chọn bắt đầu và kết thúc được diễn giải như trong ký hiệu lát cắt Dãy con cần tìm có thể là bất kỳ hoặc một số nguyên trong khoảng từ 0 đến 255 Nếu phụ trống, trả về số lát trống giữa các ký tự là độ dài của đối tượng byte cộng với một Đã thay đổi trong phiên bản 3. 3. Cũng chấp nhận một số nguyên trong khoảng từ 0 đến 255 làm dãy con. byte. removeprefix(prefix , / . )bytearray.removeprefix(prefix , /)Nếu dữ liệu nhị phân bắt đầu bằng chuỗi tiền tố, hãy trả về def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 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. Mặt khác, trả về một bản sao của dữ liệu nhị phân ban đầu >>> (65).to_bytes() b'A'1 Tiền tố có thể là bất kỳ Note Phiên bản bytearray của phương pháp này không hoạt động tại chỗ - nó luôn tạo ra một đối tượng mới, ngay cả khi không có thay đổi nào được thực hiện Mới trong phiên bản 3. 9 byte. hậu tố loại bỏ(hậu tố , / . )bytearray.hậu tố loại bỏ(hậu tố , /)Nếu dữ liệu nhị phân kết thúc bằng chuỗi hậu tố và hậu tố đó không trống, hãy trả về def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 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. Mặt khác, trả về một bản sao của dữ liệu nhị phân ban đầu >>> (65).to_bytes() b'A'2 The suffix may be any Note Phiên bản bytearray của phương pháp này không hoạt động tại chỗ - nó luôn tạo ra một đối tượng mới, ngay cả khi không có thay đổi nào được thực hiện Mới trong phiên bản 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. With optional end, stop comparing at that position The suffix(es) to search for may be any bytes. find(sub[ , start[ , end]])bytearray. find(sub[ , start[ , end]])Return the lowest index in the data where the subsequence sub is found, such that sub is contained in the slice def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)49. Optional arguments start and end are interpreted as in slice notation. Return >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 341 if sub is not found Dãy con cần tìm có thể là bất kỳ hoặc một số nguyên trong khoảng từ 0 đến 255 Note The method should be used only if you need to know the position of sub. To check if sub is a substring or not, use the operator >>> (65).to_bytes() b'A'3 Đã thay đổi trong phiên bản 3. 3. Cũng chấp nhận một số nguyên trong khoảng từ 0 đến 255 làm dãy con. bytes. index(sub[ , start[ , end]])bytearray. index(sub[ , start[ , end]])Like , but raise when the subsequence is not found Dãy con cần tìm có thể là bất kỳ hoặc một số nguyên trong khoảng từ 0 đến 255 Đã thay đổi trong phiên bản 3. 3. Cũng chấp nhận một số nguyên trong khoảng từ 0 đến 255 làm dãy con. 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(từ , đến . )static bytearray.maketrans(from , to)Phương thức tĩnh này trả về một bảng dịch có thể sử dụng để ánh xạ từng ký tự từ thành ký tự ở cùng một vị trí thành; Mới trong phiên bản 3. 1 bytes. partition(sep)bytearray. partition(sep)Tách chuỗi ở lần xuất hiện đầu tiên của sep và trả về 3-bộ chứa phần trước dấu tách, chính dấu tách hoặc bản sao mảng phụ của nó và phần sau dấu tách. 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 Dấu phân cách để tìm kiếm có thể là bất kỳ byte. thay thế(cũ , mới . [, count])bytearray.thay thế(cũ , mới[, count])Trả về một bản sao của chuỗi với tất cả các lần xuất hiện của chuỗi cũ được thay thế bằng mới. 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ế Dãy con cần tìm và sự thay thế của nó có thể là bất kỳ Note Phiên bản bytearray của phương pháp này không hoạt động tại chỗ - nó luôn tạo ra một đối tượng mới, ngay cả khi không có thay đổi nào được thực hiện byte. rfind(phụ[ , . start[, end]])bytearray.rfind(sub[ , start[, end]])Trả về chỉ số cao nhất trong chuỗi nơi tìm thấy subsequence sub, như vậy sub đó được chứa trong def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': 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. Các đối số tùy chọn bắt đầu và kết thúc được diễn giải như trong ký hiệu lát cắt. Trả lại >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 341 khi thất bại Dãy con cần tìm có thể là bất kỳ hoặc một số nguyên trong khoảng từ 0 đến 255 Đã thay đổi trong phiên bản 3. 3. Cũng chấp nhận một số nguyên trong khoảng từ 0 đến 255 làm dãy con. byte. rindex(sub[ , . start[, end]])bytearray.rindex(sub[ , start[, end]])Like nhưng tăng khi không tìm thấy sub nối tiếp Dãy con cần tìm có thể là bất kỳ hoặc một số nguyên trong khoảng từ 0 đến 255 Đã thay đổi trong phiên bản 3. 3. Cũng chấp nhận một số nguyên trong khoảng từ 0 đến 255 làm dãy con. byte. phân vùng(sep)bytearray. phân vùng(sep)Tách chuỗi ở lần xuất hiện cuối cùng của sep và trả về 3-tuple chứa phần trước dấu tách, chính dấu tách hoặc bản sao mảng phụ của nó và phần sau dấu tách. Nếu không tìm thấy dấu tách, hãy trả về 3-bộ chứa hai byte trống hoặc đối tượng mảng phụ, theo sau là bản sao của chuỗi ban đầu Dấu phân cách để tìm kiếm có thể là bất kỳ byte. startswith(tiền tố[ , . start[, end]])bytearray.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 dữ liệu nhị phân bắt đầu bằng tiền tố đã chỉ định, nếu không thì 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. tiền tố cũng có thể là một bộ tiền tố cần tìm. Với bắt đầu tùy chọn, bắt đầu kiểm tra tại vị trí đó. Với đầu cuối tùy chọn, dừng so sánh tại vị trí đó (Các) tiền tố để tìm kiếm có thể là bất kỳ byte. dịch(bảng , / . , delete=b'')bytearray.dịch(bảng , /, delete=b'')Trả về một bản sao của đối tượng byte hoặc bytearray trong đó tất cả các byte xuất hiện trong đối số tùy chọn xóa đều bị xóa và các byte còn lại đã được ánh xạ qua bảng dịch đã cho, phải là một đối tượng byte có độ dài 256 Bạn có thể sử dụng phương pháp để tạo bảng dịch Đặt đối số bảng thà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') --> 631 cho các bản dịch chỉ xóa các ký tự >>> (65).to_bytes() b'A'4 Đã thay đổi trong phiên bản 3. 6. xóa hiện được hỗ trợ làm đối số từ khóa. Các phương thức sau trên các đối tượng byte và bytearray có các hành vi mặc định giả sử sử dụng các định dạng nhị phân tương thích ASCII, nhưng vẫn có thể được sử dụng với dữ liệu nhị phân tùy ý bằng cách chuyển các đối số thích hợp. Lưu ý rằng tất cả các phương thức bytearray trong phần này không hoạt động tại chỗ mà thay vào đó tạo ra các đối tượng mới byte. trung tâm(chiều rộng[ , . fillbyte])bytearray.trung tâm(chiều rộng[ , fillbyte])Trả về một bản sao của đối tượng được căn giữa theo thứ tự chiều dài chiều rộng. Quá trình đệm được thực hiện bằng cách sử dụng fillbyte đã chỉ định (mặc định là một không gian ASCII). Đố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 Phiên bản bytearray của phương pháp này không hoạt động tại chỗ - nó luôn tạo ra một đối tượng mới, ngay cả khi không có thay đổi nào được thực hiện byte. ljust(chiều rộng[ , . fillbyte])bytearray.ljust(chiều rộng[ , fillbyte])Trả về một bản sao của đối tượng còn lại được căn đều theo trình tự chiều dài chiều rộng. Quá trình đệm được thực hiện bằng cách sử dụng fillbyte đã chỉ định (mặc định là một không gian ASCII). Đố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 Phiên bản bytearray của phương pháp này không hoạt động tại chỗ - nó luôn tạo ra một đối tượng mới, ngay cả khi không có thay đổi nào được thực hiện byte. lstrip([ký tự] . )bytearray.lstrip([ký tự])Trả về một bản sao của chuỗi đã xóa các byte đầu được chỉ định. Đối số ký tự là một chuỗi nhị phân chỉ định tập hợp các giá trị byte sẽ bị xóa - tên đề cập đến thực tế là phương thức này thường được sử dụng với các ký tự ASCII. Nếu bỏ qua 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') --> 631, đối số ký tự mặc định xóa khoảng trắng ASCII. Đối số ký tự không phải là tiền tố; >>> (65).to_bytes() b'A'5 Chuỗi nhị phân của các giá trị byte cần loại bỏ có thể là bất kỳ. Xem phương pháp sẽ xóa một chuỗi tiền tố thay vì tất cả một bộ ký tự. Ví dụ >>> (65).to_bytes() b'A'6 Note Phiên bản bytearray của phương pháp này không hoạt động tại chỗ - nó luôn tạo ra một đối tượng mới, ngay cả khi không có thay đổi nào được thực hiện byte. rjust(chiều rộng[ , . fillbyte])bytearray.rjust(chiều rộng[ , fillbyte])Trả về một bản sao của đối tượng được căn phải theo thứ tự chiều dài chiều rộng. Quá trình đệm được thực hiện bằng cách sử dụng fillbyte đã chỉ định (mặc định là một không gian ASCII). Đố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 Phiên bản bytearray của phương pháp này không hoạt động tại chỗ - nó luôn tạo ra một đối tượng mới, ngay cả khi không có thay đổi nào được thực hiện byte. rsplit(sep=Không có . , maxsplit=- 1)bytearray.rsplit(sep=Không có, maxsplit=- 1)Tách chuỗi nhị phân thành các chuỗi con cùng loại, sử dụng sep làm chuỗi phân cách. Nếu maxsplit được đưa ra, thì tối đa các phần tách maxsplit được thực hiện, những phần ngoài cùng bên phải. Nếu sep không được chỉ định 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') --> 631, thì bất kỳ dãy con nào chỉ bao gồm khoảng trắng ASCII đều là dấu phân cách. Ngoại trừ tách từ bên phải, hoạt động như được mô tả chi tiết bên dướibyte. rstrip([ký tự] . )bytearray.rstrip([ký tự]) Trả về một bản sao của chuỗi đã xóa các byte theo sau được chỉ định. Đối số ký tự là một chuỗi nhị phân chỉ định tập hợp các giá trị byte sẽ bị xóa - tên đề cập đến thực tế là phương thức này thường được sử dụng với các ký tự ASCII. Nếu bỏ qua 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') --> 631, đối số ký tự mặc định xóa khoảng trắng ASCII. Đối số ký tự không phải là một hậu tố; >>> (65).to_bytes() b'A'7 Chuỗi nhị phân của các giá trị byte cần loại bỏ có thể là bất kỳ. Xem một phương thức sẽ loại bỏ một chuỗi hậu tố thay vì tất cả một bộ ký tự. Ví dụ >>> (65).to_bytes() b'A'8 Note Phiên bản bytearray của phương pháp này không hoạt động tại chỗ - nó luôn tạo ra một đối tượng mới, ngay cả khi không có thay đổi nào được thực hiện byte. tách(sep=Không có . , maxsplit=- 1)bytearray.tách(sep=Không có, maxsplit=- 1)Tách chuỗi nhị phân thành các chuỗi con cùng loại, sử dụng sep làm chuỗi phân cách. Nếu maxsplit được đưa ra và không âm, thì tối đa việc tách maxsplit được thực hiện (do đó, danh sách sẽ có tối đ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') 1671168037 phần tử). Nếu maxsplit không được chỉ định hoặc là >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 341, thì không có giới hạn về số lần phân tách (tất cả các lần phân tách có thể được thực hiện) Nếu sep được đưa ra, các dấu phân cách liên tiếp không được nhóm lại với nhau và được coi là phân cách các chuỗi con trống (ví dụ: >>> (-2.0).is_integer() True >>> (3.2).is_integer() False27 trả về >>> (-2.0).is_integer() True >>> (3.2).is_integer() False28). Đối số sep có thể bao gồm một chuỗi nhiều byte (ví dụ: >>> (-2.0).is_integer() True >>> (3.2).is_integer() False29 trả về >>> (-2.0).is_integer() True >>> (3.2).is_integer() False30). Việc tách một chuỗi trống với một dấu tách được chỉ định trả về >>> (-2.0).is_integer() True >>> (3.2).is_integer() False31 hoặc >>> (-2.0).is_integer() True >>> (3.2).is_integer() False32 tùy thuộc vào loại đối tượng được tách. Đối số sep có thể là bất kỳ For example >>> (65).to_bytes() b'A'9 Nếu sep không được chỉ định hoặc 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, một thuật toán phân tách khác sẽ được áp dụng. các khoảng trắng ASCII liên tiếp được coi là một dấu phân cách duy nhất và kết quả sẽ không chứa chuỗi trống ở đầu hoặc cuối nếu chuỗi có khoảng trắng ở đầu hoặc cuối. Do đó, việc tách một chuỗi trống hoặc một chuỗi chỉ bao gồm khoảng trắng ASCII mà không có dấu phân cách được chỉ định sẽ 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') --> 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)0byte. dải([ký tự] . )bytearray.dải([ký tự]) Trả về một bản sao của chuỗi đã xóa các byte đầu và cuối được chỉ định. Đối số ký tự là một chuỗi nhị phân chỉ định tập hợp các giá trị byte sẽ bị xóa - tên đề cập đến thực tế là phương thức này thường được sử dụng với các ký tự ASCII. Nếu bỏ qua 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') --> 631, đối số ký tự mặc định xóa khoảng trắng ASCII. Đối số ký tự không phải là tiền tố hoặc hậu tố; def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': 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 Chuỗi nhị phân của các giá trị byte cần loại bỏ có thể là bất kỳ Note Phiên bản bytearray của phương pháp này không hoạt động tại chỗ - nó luôn tạo ra một đối tượng mới, ngay cả khi không có thay đổi nào được thực hiện 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 Phiên bản bytearray của phương pháp này không hoạt động tại chỗ - nó luôn tạo ra một đối tượng mới, ngay cả khi không có thay đổi nào được thực hiện 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 Phiên bản bytearray của phương pháp này không hoạt động tại chỗ - nó luôn tạo ra một đối tượng mới, ngay cả khi không có thay đổi nào được thực hiện 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. không gian() 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. 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 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() Return a copy of the sequence with all the uppercase ASCII characters converted to their corresponding lowercase counterpart 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 Phiên bản bytearray của phương pháp này không hoạt động tại chỗ - nó luôn tạo ra một đối tượng mới, ngay cả khi không có thay đổi nào được thực hiện bytes. splitlines(keepends=False)bytearray. splitlines(keepends=False)Return a list of the lines in the binary sequence, breaking at ASCII line boundaries. This method uses the approach to splitting lines. Line breaks are not included in the resulting list unless keepends is given and true 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') 167116801bytes. swapcase()bytearray. swapcase() Return a copy of the sequence with all the lowercase ASCII characters converted to their corresponding uppercase counterpart and vice-versa 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 Unlike , it is always the case that >>> (-2.0).is_integer() True >>> (3.2).is_integer() False71 for the binary versions. Case conversions are symmetrical in ASCII, even though that is not generally true for arbitrary Unicode code points Note Phiên bản bytearray của phương pháp này không hoạt động tại chỗ - nó luôn tạo ra một đối tượng mới, ngay cả khi không có thay đổi nào được thực hiện bytes. title()bytearray. title()Return a titlecased version of the binary sequence where words start with an uppercase ASCII character and the remaining characters are lowercase. Uncased byte values are left unmodified 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 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. All other byte values are uncased 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 A workaround for apostrophes can be constructed using regular expressions >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', 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 Phiên bản bytearray của phương pháp này không hoạt động tại chỗ - nó luôn tạo ra một đối tượng mới, ngay cả khi không có thay đổi nào được thực hiện bytes. upper()bytearray. upper()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 Phiên bản bytearray của phương pháp này không hoạt động tại chỗ - nó luôn tạo ra một đối tượng mới, ngay cả khi không có thay đổi nào được thực hiện 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 Phiên bản bytearray của phương pháp này không hoạt động tại chỗ - nó luôn tạo ra một đối tượng mới, ngay cả khi không có thay đổi nào được thực hiện Đị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). If the value being printed may be a tuple or dictionary, wrap it in a tuple Bytes objects ( >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\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) 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 bytes 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 bytes object), >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168083 conversion specifications in format are replaced with zero or more elements of values. The effect is similar to using the >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168086 in the C language If format requires a single argument, values may be a single non-tuple object. Otherwise, values must be a tuple with exactly the number of items specified by the format bytes object, 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 bytes object must include a parenthesised mapping key into that dictionary inserted immediately after the >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 1671168087 character. The mapping key selects the value to be formatted from the mapping. 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') 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 (số 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 Single byte (accepts integer or single byte objects) def bit_length(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 Bytes (any object that follows the or has def bit_length(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 is an alias 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') --> 6022 and should only be used for Python2/3 code bases (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 Bytes (converts any Python object using def bit_length(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 is an alias for def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 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 and should only be used for Python2/3 code bases (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 Không có đối số nào được chuyển đổi, dẫn đến một 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 trong kết quả ghi chú
Note Phiên bản bytearray của phương pháp này không hoạt động tại chỗ - nó luôn tạo ra một đối tượng mới, ngay cả khi không có thay đổi nào được thực hiện See also PEP 461 - Adding % formatting to bytes and bytearray New in version 3. 5 Memory Viewsobjects allow Python code to access the internal data of an object that supports the without copying class memoryview(object)Create a that references object. object must support the buffer protocol. Built-in objects that support the buffer protocol include and A has the notion of an element, which is the atomic memory unit handled by the originating object. For many simple types such as and , an element is a single byte, but other types such as may have bigger elements def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6051 is equal to the length of . If def bit_length(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, the length is 1. If def bit_length(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, the length is equal to the number of elements in the view. For higher dimensions, the length is equal to the length of the nested list representation of the view. The attribute will give you the number of bytes in a single element A supports slicing and indexing to expose its data. One-dimensional slicing will result in a subview >>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 167116809 If is one of the native format specifiers from the module, indexing with an integer or a tuple of integers is also supported and returns a single element with the correct type. One-dimensional memoryviews can be indexed with an integer or a one-integer tuple. Multi-dimensional memoryviews can be indexed with tuples of exactly ndim integers where ndim is the number of dimensions. Zero-dimensional memoryviews can be indexed with the empty tuple Here is an example with a non-byte 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 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. Resizing is not allowed def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n1 One-dimensional memoryviews of hashable (read-only) types with formats ‘B’, ‘b’ or ‘c’ are also hashable. The hash is defined as def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 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 Changed in version 3. 3. One-dimensional memoryviews can now be sliced. One-dimensional memoryviews with formats ‘B’, ‘b’ or ‘c’ are now hashable. Changed in version 3. 4. memoryview is now registered automatically with Changed in version 3. 5. memoryviews can now be indexed with tuple of integers. has several methods __eq__(exporter)A memoryview and a PEP 3118 exporter are equal if their shapes are equivalent and if all corresponding values are equal when the operands’ respective format codes are interpreted using syntax For the subset of format strings currently supported by , def bit_length(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 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') --> 6066 are equal if def bit_length(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 If either format string is not supported by the module, then the objects will always compare as unequal (even if the format strings and buffer contents are identical) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 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 Note that, as with floating point numbers, def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6069 does not imply def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6070 for memoryview objects Changed in version 3. 3. Previous versions compared the raw memory disregarding the item format and the logical array structure. tobytes(order='C')Return the data in the buffer as a bytestring. 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 For non-contiguous arrays the result is equal to the flattened list representation with all elements converted to bytes. supports all format strings, including those that are not in module syntax New in version 3. 8. order can be {‘C’, ‘F’, ‘A’}. When order is ‘C’ or ‘F’, the data of the original array is converted to C or Fortran order. For contiguous views, ‘A’ returns an exact copy of the physical memory. In particular, in-memory Fortran order is preserved. For non-contiguous views, the data is converted to C first. order=None is the same as order=’C’. hex([sep[ , bytes_per_sep]])Return a string object containing two hexadecimal digits for each byte in the buffer def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n6 New in version 3. 5 Đã thay đổi trong phiên bản 3. 8. Tương tự như , giờ đây hỗ trợ các tham số sep và bytes_per_sep tùy chọn để chèn dấu phân cách giữa các byte trong đầu ra hex. 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 Changed in version 3. 3. now supports all single character native formats in module syntax as well as multi-dimensional representations. toreadonly()Return a readonly version of the memoryview object. The original memoryview object is unchanged def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 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 release()Release the underlying buffer exposed by the memoryview object. Many objects take special actions when a view is held on them (for example, a would temporarily forbid resizing); therefore, calling release() is handy to remove these restrictions (and free any dangling resources) as soon as possible After this method has been called, any further operation on the view raises a (except itself which can be called multiple times) def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 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 cast(format[ , shape])Truyền chế độ xem bộ nhớ sang định dạng hoặc hình dạng mới. shape 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') --> 6082, which means that the result view will be one-dimensional. The return value is a new memoryview, but the buffer itself is not copied. Supported casts are 1D -> C- and C-contiguous -> 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’). The byte length of the result must be the same as the original length Cast 1D/long to 1D/unsigned bytes >>> (-2.0).is_integer() True >>> (3.2).is_integer() False1 Cast 1D/unsigned bytes to 1D/char >>> (-2.0).is_integer() True >>> (3.2).is_integer() False2 Cast 1D/bytes to 3D/ints to 1D/signed char >>> (-2.0).is_integer() True >>> (3.2).is_integer() False3 Cast 1D/unsigned long to 2D/unsigned long >>> (-2.0).is_integer() True >>> (3.2).is_integer() False4 New in version 3. 3 Changed in version 3. 5. The source format is no longer restricted when casting to a byte view. There are also several readonly attributes available objThe underlying object of the memoryview >>> (-2.0).is_integer() True >>> (3.2).is_integer() False5 New in version 3. 3 nbytesdef bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6084. This is the amount of space in bytes that the array would use in a contiguous representation. It is not necessarily equal to def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6085 >>> (-2.0).is_integer() True >>> (3.2).is_integer() False6 Multi-dimensional arrays >>> (-2.0).is_integer() True >>> (3.2).is_integer() False7 New in version 3. 3 readonlyA bool indicating whether the memory is read only formatA string containing the format (in module style) for each element in the view. A memoryview can be created from exporters with arbitrary format strings, but some methods (e. g. ) are restricted to native single element formats Changed in version 3. 3. format def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6088 is now handled according to the struct module syntax. This means that def bit_length(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. itemsize The size in bytes of each element of the memoryview >>> (-2.0).is_integer() True >>> (3.2).is_integer() False8 An integer indicating how many dimensions of a multi-dimensional array the memory represents shapeA tuple of integers the length of giving the shape of the memory as an N-dimensional array Changed in version 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. strides A tuple of integers the length of giving the size in bytes to access each element for each dimension of the array Changed in version 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. suboffsets Used internally for PIL-style arrays. Giá trị chỉ là thông tin c_contiguousA bool indicating whether the memory is C- New in version 3. 3 f_contiguousA bool indicating whether the memory is Fortran New in version 3. 3 contiguousA bool indicating whether the memory is New in version 3. 3 Set Types — ,A set object is an unordered collection of distinct objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. (For other containers see the built-in , , and classes, and the module. ) Like other collections, sets support def bit_length(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, 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') --> 6102. Being an unordered collection, sets do not record element position or order of insertion. Accordingly, sets do not support indexing, slicing, or other sequence-like behavior There are currently two built-in set types, and . The type is mutable — the contents can be changed using methods like def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6106 and >>> (65).to_bytes() b'A'01. Since it is mutable, it has no hash value and cannot be used as either a dictionary key or as an element of another set. The type is immutable and — its contents cannot be altered after it is created; it can therefore be used as a dictionary key or as an element of another set Non-empty sets (not frozensets) can be created by placing a comma-separated list of elements within braces, 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') --> 6109, in addition to the constructor The constructors for both classes work the same class set([iterable])class frozenset([iterable])Return a new set or frozenset object whose elements are taken from iterable. The elements of a set must be . To represent sets of sets, the inner sets must be objects. If iterable is not specified, a new empty set is returned Sets can be created by several means
Instances of and provide the following operations len(s)Return the number of elements in set s (cardinality of s) x in sTest x for membership in s x not in sTest x for non-membership in s isdisjoint(other)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 set has no elements in common with other. Sets are disjoint if and only if their intersection is the empty setissubset(other)set <= other Test whether every element in the set is in other set < otherTest whether the set is a proper subset of other, that 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') --> 6120issuperset(other)set >= other Test whether every element in other is in the set set > otherTest whether the set is a proper superset of other, that 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') --> 6121union(*others)set . other . . Return a new set with elements from the set and all others intersection(*others)set & other & .Return a new set with elements common to the set and all others difference(*others)set - other - .Return a new set with elements in the set that are not in the others symmetric_difference(other)set ^ otherReturn a new set with elements in either the set or other but not both bản sao()Return a shallow copy of the set Note, the non-operator versions of , , , , , and methods will accept any iterable as an argument. 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. This precludes error-prone constructions like def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6128 in favor of the more readable def bit_length(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 Both and support set to set comparisons. Two sets are equal if and only if every element of each set is contained in the other (each is a subset of the other). A set is less than another set if and only if the first set is a proper subset of the second set (is a subset, but is not equal). A set is greater than another set if and only if the first set is a proper superset of the second set (is a superset, but is not equal) 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. 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') --> 6134 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 and so does def bit_length(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 The subset and equality comparisons do not generalize to a total ordering function. For example, any two nonempty disjoint sets are not equal and are not subsets of each other, so all of the following return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 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, 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') --> 6140 Since sets only define partial ordering (subset relationships), the output of the method is undefined for lists of sets Set elements, like dictionary keys, must be Binary operations that mix instances with return the type of the first operand. 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') --> 6144 returns an instance of The following table lists operations available for that do not apply to immutable instances of update(*others)set . = other . .Update the set, adding elements from all others intersection_update(*others)set &= other & .Update the set, keeping only elements found in it and all others difference_update(*others)set -= other . .Update the set, removing elements found in others symmetric_difference_update(other)set ^= otherUpdate the set, keeping only elements found in either set, but not in both add(elem)Add element elem to the set remove(elem)Remove element elem from the set. Raises if elem is not contained in the set discard(elem)Remove element elem from the set if it is present pop()Remove and return an arbitrary element from the set. Raises if the set is empty clear()Remove all elements from the set Note, the non-operator versions of the , , , and methods will accept any iterable as an argument Note, the elem argument to the >>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 300, , and methods may be a set. To support searching for an equivalent frozenset, a temporary one is created from elem Mapping Types —A object maps values to arbitrary objects. Mappings are mutable objects. There is currently only one standard mapping type, the dictionary. (For other containers see the built-in , , and classes, and the module. ) A dictionary’s keys are almost arbitrary values. Values that are not , that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys. Values that compare equal (such as def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 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, 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') --> 656) can be used interchangeably to index the same dictionary entryclass dict(**kwargs)class dict(mapping , **kwargs)class dict(iterable , **kwargs) Return a new dictionary initialized from an optional positional argument and a possibly empty set of keyword arguments Dictionaries can be created by several means
If no positional argument is given, an empty dictionary is created. If a positional argument is given and it is a mapping object, a dictionary is created with the same key-value pairs as the mapping object. Otherwise, the positional argument must be an object. Each item in the iterable must itself be an iterable with exactly two objects. The first object of each item becomes a key in the new dictionary, and the second object the corresponding value. If a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary If keyword arguments are given, the keyword arguments and their values are added to the dictionary created from the positional argument. If a key being added is already present, the value from the keyword argument replaces the value from the positional argument To illustrate, the following examples all return a dictionary equal to def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6173 >>> (-2.0).is_integer() True >>> (3.2).is_integer() False9 Providing keyword arguments as in the first example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used These are the operations that dictionaries support (and therefore, custom mapping types should support too) list(d)Return a list of all the keys used in the dictionary d len(d)Return the number of items in the dictionary d d[key]Return the item of d with key key. Raises a if key is not in the map If a subclass of dict defines a method def bit_length(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 and key is not present, 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') --> 6176 operation calls that method with the key key as argument. 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') --> 6176 operation then returns or raises whatever is returned or raised by 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') --> 6178 call. No other operations or methods invoke def bit_length(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. If def bit_length(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 is not defined, is raised. def bit_length(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 must be a method; it cannot be an instance variable def bit_length(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 The example above shows part of the implementation of . A different def bit_length(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 method is used by d[key] = value Set def bit_length(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 to valuedel d[key] Remove def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6176 from d. Raises a if key is not in the mapkey in d 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 d has a key key, 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') --> 638key not in d 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') --> 6191iter(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') --> 6192clear() Remove all items from the dictionary bản sao()Return a shallow copy of the dictionary classmethod fromkeys(iterable[ , value])Create a new dictionary with keys from iterable and values set to value is a class method that returns a new dictionary. value 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') --> 631. All of the values refer to just a single instance, so it generally doesn’t make sense for value to be a mutable object such as an empty list. To get distinct values, use a insteadget(key[ , default]) Return the value for key if key is in the dictionary, else default. If default is not given, 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') --> 631, so that this method never raises a items() Return a new view of the dictionary’s items ( def bit_length(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). See the keys() Return a new view of the dictionary’s keys. See the pop(key[ , 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. If default is not given and key is not in the dictionary, a is raised popitem()Xóa và trả về 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 từ từ điển. Pairs are returned in LIFO order 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. If the dictionary is empty, calling raises a Changed in version 3. 7. LIFO order is now guaranteed. In prior versions, would return an arbitrary key/value pair. reversed(d)Return a reverse 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') --> 6204 Mới trong phiên bản 3. 8 setdefault(key[ , default])If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 631update([other]) Update the dictionary with the key/value pairs from other, overwriting existing keys. 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 accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs. def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6208giá trị() Return a new view of the dictionary’s values. See the An equality comparison between one def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6209 view and another will always return def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 638. This also applies when comparing def bit_length(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 to itself def bit_length(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 . other Create a new dictionary with the merged keys and values of d and other, which must both be dictionaries. The values of other take priority when d and other share keys Mới trong phiên bản 3. 9 d . = otherUpdate the dictionary d with keys and values from other, which may be either a or an of key/value pairs. The values of other take priority when d and other share keys Mới trong phiên bản 3. 9 Dictionaries compare equal if and only if they have the same def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6197 pairs (regardless of ordering). Order comparisons (‘<’, ‘<=’, ‘>=’, ‘>’) raise . Dictionaries preserve insertion order. Note that updating a key does not affect the order. Keys added after deletion are inserted at the end def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 602 Changed in version 3. 7. Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3. 6. Dictionaries and dictionary views are reversible def bit_length(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 Changed in version 3. 8. Dictionaries are now reversible. See also can be used to create a read-only view of a Dictionary view objectsThe objects returned by , and are view objects. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes Dictionary views can be iterated over to yield their respective data, and support membership tests len(dictview)Return the number of entries in the dictionary iter(dictview)Return an iterator over the keys, values or items (represented as tuples of def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6197) in the dictionary Keys and values are iterated over in insertion order. This allows the creation 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') --> 6220 pairs using . def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6222. Another way to create the same list 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') --> 6223 Iterating views while adding or deleting entries in the dictionary may raise a or fail to iterate over all entries Changed in version 3. 7. Dictionary order is guaranteed to be insertion order. x in dictviewReturn def bit_length(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 x is in the underlying dictionary’s keys, values or items (in the latter case, x should be 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 tuple)reversed(dictview) Return a reverse iterator over the keys, values or items of the dictionary. The view will be iterated in reverse order of the insertion Changed in version 3. 8. Dictionary views are now reversible. dictview. mappingReturn a that wraps the original dictionary to which the view refers Mới trong phiên bản 3. 10 Keys views are set-like since their entries are unique and hashable. If all values are hashable, so that def bit_length(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 are unique and hashable, then the items view is also set-like. (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. ) For set-like views, all of the operations defined for the abstract base class are available (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') --> 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, 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') --> 6232) An example of dictionary view usage def bit_length(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 Context Manager TypesPython’s statement supports the concept of a runtime context defined by a context manager. This is implemented using a pair of methods that allow user-defined classes to define a runtime context that is entered before the statement body is executed and exited when the statement ends contextmanager. __enter__()Enter the runtime context and return either this object or another object related to the runtime context. The value returned by this method is bound to the identifier 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') --> 6234 clause of statements using this context manager An example of a context manager that returns itself is a . File objects return themselves from __enter__() to allow to be used as the context expression in a statement An example of a context manager that returns a related object is the one returned by . These managers set the active decimal context to a copy of the original decimal context and then return the copy. This allows changes to be made to the current decimal context in the body of the statement without affecting code outside 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') --> 6081 statementcontextmanager. __exit__(exc_type , exc_val , exc_tb) Exit the runtime context and return a Boolean flag indicating if any exception that occurred should be suppressed. If an exception occurred while executing the body of the statement, the arguments contain the exception type, value and traceback information. Otherwise, all three arguments are def bit_length(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 Returning a true value from this method will cause the statement to suppress the exception and continue execution with the statement immediately following 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') --> 6081 statement. Otherwise the exception continues propagating after this method has finished executing. Exceptions that occur during execution of this method will replace any exception that occurred in the body of 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') --> 6081 statement The exception passed in should never be reraised explicitly - instead, this method should return a false value to indicate that the method completed successfully and does not want to suppress the raised exception. This allows context management code to easily detect whether or not an method has actually failed Python defines several context managers to support easy thread synchronisation, prompt closure of files or other objects, and simpler manipulation of the active decimal arithmetic context. The specific types are not treated specially beyond their implementation of the context management protocol. See the module for some examples Python’s s and the decorator provide a convenient way to implement these protocols. If a generator function is decorated with the decorator, it will return a context manager implementing the necessary and methods, rather than the iterator produced by an undecorated generator function Note that there is no specific slot for any of these methods in the type structure for Python objects in the Python/C API. Các loại tiện ích mở rộng muốn xác định các phương thức này phải cung cấp chúng như một phương thức truy cập Python thông thường. Compared to the overhead of setting up the runtime context, the overhead of a single class dictionary lookup is negligible Nhập các loại chú thích — ,The core built-in types for are and Generic Alias Typedef bit_length(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 objects are generally created by a class. They are most often used with , such as or . 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') --> 6255 is a def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6252 object created by subscripting the def bit_count(self): return bin(self).count("1")93 class with the argument . def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6252 objects are intended primarily for use with Note It is generally only possible to subscript a class if the class implements the special method 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. 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') --> 6262 can be used in type annotations to signify a in which all the elements are of type For a class which defines but is not a container, the argument(s) supplied to a subscription of the class will often indicate the return type(s) of one or more methods defined on an object. For example, can be used on both the data type and the data type
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6252 objects are instances of the class , which can also be used to create def bit_length(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 objects directlyT[X, Y, . ] Creates 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') --> 6252 representing a type def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6289 parameterized by types X, Y, and more depending on 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') --> 6289 used. For example, a function expecting a containing elements def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 605 Another example for objects, using a , which is a generic type expecting two type parameters representing the key type and the value type. 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 The builtin functions and do not accept def bit_length(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 types for their second argument def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 607 The Python runtime does not enforce . This extends to generic types and their type parameters. When creating a container object from a def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6252, the elements in the container are not checked against their type. For example, the following code is discouraged, but will run without errors def bit_length(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 Furthermore, parameterized generics erase type parameters during object creation def bit_length(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 Calling or on a generic shows the parameterized type def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 610 The method of generic containers will raise an exception to disallow mistakes like def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 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 However, such expressions are valid when are used. 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 Standard Generic ClassesThe following standard library classes support parameterized generics. This list is non-exhaustive Special Attributes of |