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
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ật
Bấ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 một phương thức
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 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 một phương thức
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 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
hằng số được xác định là sai.
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
31 anddef bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
38số không của bất kỳ loại số nào.
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
42,def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
43,def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
44,def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
45,def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
46trình tự và bộ sưu tập trố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'] --> 6
47,def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
48,def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
49,def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
50,def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
51,def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
52
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
if x is false, then x, else y
[2]
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 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ú
Đây là toán tử ngắn mạch, vì vậy nó chỉ đánh giá đối số thứ hai nếu đối số thứ nhất sai
Đây là toán tử ngắn mạch, vì vậy nó chỉ đánh giá đối số thứ hai nếu đối số thứ nhấ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'] --> 6
61 có mức ưu tiên thấp hơn so với các toán tử không phải Boolean, vì vậydef bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
68 được hiểu làdef bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
69 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'] --> 6
70 là một lỗi cú pháp
so sánh
Có 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]. Comparisons can be chained arbitrarily; for example,
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 671 is equivalent to
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 672, except that y is evaluated only once [but in both cases z is not evaluated at all when
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 673 is found to be false]
This table summarizes the comparison operations
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
equal
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 679
not equal
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 680
object identity
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 681
danh tính đối tượng phủ nhận
Objects of different types, except different numeric types, never compare equal. 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;
Non-identical instances of a class normally compare as non-equal unless the class defines the method
Instances of a class cannot be ordered with respect to other instances of the same class, or other types of object, unless the class defines enough of the methods , , , and [in general, and are sufficient, if you want the conventional meanings of the comparison operators]
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ố — , ,
There are three distinct numeric types. integers, floating point numbers, and complex numbers. 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. Floating point numbers are usually implemented using double in C; information about the precision and internal representation of floating point numbers for the machine on which your program is running is available in . Complex numbers have a real and imaginary part, which are each a floating point number. Để 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 không trang trí [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 = 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ú
Còn gọi là phép chia số nguyên. Giá trị kết quả là một số nguyên, mặc dù loại kết quả không nhất thiết phải là int. Kết quả luôn được làm tròn về phía âm vô cực.
>>> n = 19 >>> bin[n] '0b10011' >>> n.bit_count[] 3 >>> [-n].bit_count[] 3
38 là _______0_______42, _______51_______40 là _______51_______41, _______51_______42 là _______51_______41, và _______51_______44 là _________42Không dành cho số phức. Thay vào đó, hãy chuyển đổi thành float bằng cách sử dụng nếu thích hợp
Chuyển đổi từ dấu phẩy động sang số nguyên có thể làm tròn hoặc cắt ngắn như trong C;
float cũng chấp nhận các chuỗi “nan” và “inf” với tiền tố tùy chọn “+” hoặc “-” cho Không phải là Số [NaN] và vô cực dương hoặc âm
Python định nghĩa
>>> n = 19 >>> bin[n] '0b10011' >>> n.bit_count[] 3 >>> [-n].bit_count[] 3
49 và>>> n = 19 >>> bin[n] '0b10011' >>> n.bit_count[] 3 >>> [-n].bit_count[] 3
50 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'] --> 6
55, như thường thấy đối với các ngôn ngữ lập trìnhThe numeric literals accepted include the digits
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
42 to>>> n = 19 >>> bin[n] '0b10011' >>> n.bit_count[] 3 >>> [-n].bit_count[] 3
53 or any Unicode equivalent [code points with the>>> n = 19 >>> bin[n] '0b10011' >>> n.bit_count[] 3 >>> [-n].bit_count[] 3
54 property]Xem https. //www. unicode. tổ chức/Công khai/14. 0. 0/ucd/extracted/DerivedNumericType. txt để biết danh sách đầy đủ các điểm mã với thuộc tính
>>> n = 19 >>> bin[n] '0b10011' >>> n.bit_count[] 3 >>> [-n].bit_count[] 3
54
All types [ and ] also include the following operations
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
Đố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ên
Hoạ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 or of x and 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ú
Số lần thay đổi âm là bất hợp pháp và gây ra một sự gia tăng
A left shift by n bits is equivalent to multiplication by
>>> n = 19 >>> bin[n] '0b10011' >>> n.bit_count[] 3 >>> [-n].bit_count[] 3
78Dịch chuyển sang phải n bit tương đương với phép chia sàn cho
>>> n = 19 >>> bin[n] '0b10011' >>> n.bit_count[] 3 >>> [-n].bit_count[] 3
78Thực hiện các tính toán này với ít nhất một bit mở rộng dấu phụ trong biểu diễn phần bù của hai hữu hạn [độ rộng bit làm việc là
>>> n = 19 >>> bin[n] '0b10011' >>> n.bit_count[] 3 >>> [-n].bit_count[] 3
80 trở lên] là đủ để có được kết quả tương tự như thể có vô số bit dấu
Các phương thức bổ sung trên các kiểu số nguyên
Kiể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
New in version 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. This is also known as the population count. Thí 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_bytes[length=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. classmethod int. from_bytes[bytes , byteorder='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
The signed argument indicates whether two’s complement is used to represent the integer
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 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
Two methods support conversion to and from hexadecimal strings. 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. This can be useful when debugging, and in numerical work
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. For finite floating-point numbers, this representation will always include a leading
def bit_count[self]: return bin[self].count["1"]12 and a trailing
def bit_count[self]: return bin[self].count["1"]13 and exponentphươ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 một trong hai tên là
>>> n = 19 >>> bin[n] '0b10011' >>> n.bit_count[] 3 >>> [-n].bit_count[] 369 hoặc
>>> 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à chuỗi các 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 tùy chọn ở đầu. 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
Hashing of numeric types
Đố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
Nếu
def bit_count[self]: return bin[self].count["1"]
50 là một số hữu tỉ không âm vàdef bit_count[self]: return bin[self].count["1"]
51 không chia hết chodef bit_count[self]: return bin[self].count["1"]
43, hãy định nghĩadef bit_count[self]: return bin[self].count["1"]
53 làdef bit_count[self]: return bin[self].count["1"]
54, trong đódef bit_count[self]: return bin[self].count["1"]
55 cho số nghịch đảo củadef bit_count[self]: return bin[self].count["1"]
51 theo modulodef bit_count[self]: return bin[self].count["1"]
43Nếu
def bit_count[self]: return bin[self].count["1"]
50 là một số hữu tỉ không âm vàdef bit_count[self]: return bin[self].count["1"]
51 chia hết chodef bit_count[self]: return bin[self].count["1"]
43 [nhưngdef bit_count[self]: return bin[self].count["1"]
61 thì không] thìdef bit_count[self]: return bin[self].count["1"]
51 không có modulo nghịch đảodef bit_count[self]: return bin[self].count["1"]
43 và quy tắc trên không áp dụng;Nếu
def bit_count[self]: return bin[self].count["1"]
50 là một số hữu tỷ âm, hãy xác địnhdef bit_count[self]: return bin[self].count["1"]
53 làdef bit_count[self]: return bin[self].count["1"]
68. Nếu hàm băm kết quả là>>> n = 19 >>> bin[n] '0b10011' >>> n.bit_count[] 3 >>> [-n].bit_count[] 3
41, hãy thay thế nó bằngdef bit_count[self]: return bin[self].count["1"]
70Các giá trị cụ thể
def bit_count[self]: return bin[self].count["1"]
65 vàdef bit_count[self]: return bin[self].count["1"]
72 được sử dụng làm giá trị băm cho vô cực dương hoặc vô cực âm [tương ứng]Đối với một số
def bit_count[self]: return bin[self].count["1"]
74, các giá trị băm của phần thực và phần ảo được kết hợp bằng cách tính toándef bit_count[self]: return bin[self].count["1"]
75, rút gọn modulodef bit_count[self]: return bin[self].count["1"]
76 để nó nằm trong ____113_______77. Một lần nữa, nếu kết quả là>>> n = 19 >>> bin[n] '0b10011' >>> n.bit_count[] 3 >>> [-n].bit_count[] 3
41, nó sẽ được thay thế bằngdef bit_count[self]: return bin[self].count["1"]
70
Để 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ặp
Python 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 vòng 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 lại 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à. This method corresponds to the slot of the type structure for Python objects in the Python/C API
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ệ. This method corresponds to the slot of the type structure for Python objects in the Python/C API
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ện
Python 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 ___113_______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ến
Cá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ú
Trong khi các hoạt động
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
98 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'] --> 6
99 chỉ được sử dụng cho thử nghiệm ngăn chặn đơn giản trong trường hợp chung, một số trình tự chuyên biệt [chẳng hạn như , và ] cũng sử dụng chúng cho thử nghiệm trình tự tiếp theodef bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
4Các giá trị của n nhỏ 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'] --> 6
42 được coi 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'] --> 6
42 [tạo ra một chuỗi trống cùng loại với s]. Lưu ý rằng các mục trong chuỗi s không được sao chép; . Điều này thường ám ảnh các lập trình viên Python mớ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
5Điều đã xảy ra là
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'
27 là danh sách một phần tử chứa danh sách trống, vì vậy cả ba 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'
28 đều là tham chiếu đến danh sách trống duy nhất này. Sửa đổi bất kỳ thành phần nào 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'
29 sẽ sửa đổi danh sách đơn này. You can create a list of different lists this waydef bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
6Further explanation is available in the FAQ entry
Nếu i hoặc j âm, chỉ số liên quan đến phần cuối của chuỗi s.
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'
30 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'
31 được thay thế. Nhưng lưu ý rằ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'
32 vẫn 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'] --> 6
42Lát của s từ i đến j được định nghĩa là chuỗi các phần tử có chỉ số k sao cho
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'
34. Nếu i hoặc j lớn hơ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'
13, hãy sử dụ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. Nếu tôi bị bỏ qua hoặcdef bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
31, hãy sử dụngdef bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
42. Nếu j bị bỏ qua hoặcdef bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
31, hãy sử dụ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. Nếu i lớn hơn hoặc bằng j, lát cắt trốngPhần s từ i đến j với bước k được định nghĩa là chuỗi các mục có chỉ 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'
41 sao cho>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'
42. Nói cách khác, các chỉ số là>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'
43,>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'
44,>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'
45,>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'
46, v.v., dừng khi đạt đến j [nhưng không bao giờ bao gồm j]. Khi k dương, i và j giảm xuống _______114_______13 nếu chúng lớn hơn. Khi k âm, i và j giảm xuống _______114_______48 nếu chúng lớn hơn. Nếu i hoặc j bị bỏ qua hoặcdef bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
31, chúng trở thành giá trị “kết thúc” [kết thúc này phụ thuộc vào dấu của k]. Lưu ý, k không thể bằng 0. Nếu 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'] --> 6
31, nó được xử 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'] --> 6
55Nối các chuỗi bất biến luôn dẫn đến một đối tượng mới. Điều này có nghĩa là việc xây dựng một chuỗi bằng cách nối lặp lại sẽ có chi phí thời gian chạy bậc hai trong tổng chiều dài chuỗi. Để có chi phí thời gian chạy tuyến tính, bạn phải chuyển sang một trong các lựa chọn thay thế bên dưới
nếu nối các đối tượng, bạn có thể tạo một danh sách và sử dụng ở cuối hoặc nếu không thì ghi vào một thể hiện và truy xuất giá trị của nó khi hoàn tất
nếu nối các đối tượng, bạn có thể sử dụng tương tự hoặc hoặc bạn có thể thực hiện nối tại chỗ với một đối tượng. các đối tượng có thể thay đổi và có cơ chế phân bổ tổng thể hiệu quả
nếu nối các đối tượng, thay vào đó hãy mở rộng a
đối với các loại khác, hãy điều tra tài liệu lớp có liên quan
Một số loại trình tự [chẳng hạn như ] chỉ hỗ trợ các trình tự vật phẩm tuân theo các mẫu cụ thể và do đó không hỗ trợ nối hoặc lặp lại trình 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'
63 tăng khi không tìm thấy x trong s. Không phải tất cả các triển khai đều hỗ trợ chuyển các đối số bổ sung i và j. Các đối số này cho phép tìm kiếm hiệu quả các phần phụ của chuỗi. Truyền các đối số bổ sung gần tương đương với việc sử dụ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'
65, chỉ là không sao chép bất kỳ dữ liệu nào và với chỉ mục được trả về có liên quan đến phần đầu của chuỗi chứ không phải phần đầu của lát cắt
Các loại trình tự bất biến
Thao 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 thực hiện được 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 đổi
Cá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
item i of s is replaced by x
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'76
slice of s from i to j is replaced by the contents of the iterable t
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'77
same as
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'78
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'79
the elements of
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'12 are replaced by those of t
[1]
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'81
removes the elements of
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'12 from the list
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'83
appends x to the end of the sequence [same as
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'84]
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'85
removes all items from s [same as
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'86]
[5]
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'87
creates a shallow copy of s [same as
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'88]
[5]
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'89 or
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'90
extends s with the contents of t [for the most part the same as
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'91]
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'92
updates s with its contents repeated n times
[6]
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'93
inserts x into s at the index given by i [same as
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'94]
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'95 or
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'96
retrieves the item at i and also removes it from s
[2]
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'97
remove the first item from s where
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'10 is equal to x
[3]
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'99
reverses the items of s in place
[4]
ghi chú
t must have the same length as the slice it is replacing
The optional argument i defaults to
>>> n = 19 >>> bin[n] '0b10011' >>> n.bit_count[] 3 >>> [-n].bit_count[] 3
41, so that by default the last item is removed and returned>>> [65].to_bytes[] b'A'
01 raises when x is not found in sThe
>>> [65].to_bytes[] b'A'
03 method modifies the sequence in place for economy of space when reversing a large sequence. To remind users that it operates by side effect, it does not return the reversed sequence>>> [65].to_bytes[] b'A'
04 and>>> [65].to_bytes[] b'A'
05 are included for consistency with the interfaces of mutable containers that don’t support slicing operations [such as and ].>>> [65].to_bytes[] b'A'
05 is not part of the ABC, but most concrete mutable sequence classes provide itNew in version 3. 3.
>>> [65].to_bytes[] b'A'
04 and>>> [65].to_bytes[] b'A'
05 methods.The value n is an integer, or an object implementing . Zero and negative values of n clear the sequence. Items in the sequence are not copied; they are referenced multiple times, as explained for
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'
08 under
Lists
Lists are mutable sequences, typically used to store collections of homogeneous items [where the precise degree of similarity will vary by application]
class list[[iterable]]Lists may be constructed in several ways
Using a pair of square brackets to denote the empty list.
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
49Using square brackets, separating items with commas.
>>> [65].to_bytes[] b'A'
15,>>> [65].to_bytes[] b'A'
16Using a list comprehension.
>>> [65].to_bytes[] b'A'
17Using the type constructor.
>>> [65].to_bytes[] b'A'
18 or>>> [65].to_bytes[] b'A'
19
The constructor builds a list whose items are the same and in the same order as iterable’s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a list, a copy is made and returned, similar to
>>> [65].to_bytes[] b'A'20. For example,
>>> [65].to_bytes[] b'A'21 returns
>>> [65].to_bytes[] b'A'22 and
>>> [65].to_bytes[] b'A'23 returns
>>> [65].to_bytes[] b'A'24. If no argument is given, the constructor creates a new empty list,
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 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
Tuples
Tuples are immutable sequences, typically used to store collections of heterogeneous data [such as the 2-tuples produced by the built-in]. Tuples are also used for cases where an immutable sequence of homogeneous data is needed [such as allowing storage in a or instance]
class tuple[[iterable]]Tuples may be constructed in a number of ways
Using a pair of parentheses to denote the empty tuple.
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
48Using a trailing comma for a singleton tuple.
>>> [65].to_bytes[] b'A'
40 or>>> [65].to_bytes[] b'A'
41Separating items with commas.
>>> [65].to_bytes[] b'A'
42 or>>> [65].to_bytes[] b'A'
43Using the built-in.
>>> [65].to_bytes[] b'A'
44 or>>> [65].to_bytes[] b'A'
46
The constructor builds a tuple whose items are the same and in the same order as iterable’s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a tuple, it is returned unchanged. For example,
>>> [65].to_bytes[] b'A'47 returns
>>> [65].to_bytes[] b'A'48 and
>>> [65].to_bytes[] b'A'49 returns
>>> [65].to_bytes[] b'A'50. If no argument is given, the constructor creates a new empty tuple,
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 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
Ranges
The type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in loops
class range[stop]class range[start , stop[ , step]]The arguments to the range constructor must be integers [either built-in or any object that implements the special method]. If the step argument is omitted, it defaults to
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 655. If the start argument is omitted, it defaults to
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 642. If step is zero, is raised
For a positive step, the contents of a range
>>> [65].to_bytes[] b'A'62 are determined by the formula
>>> [65].to_bytes[] b'A'63 where
>>> [65].to_bytes[] b'A'64 and
>>> [65].to_bytes[] b'A'65
For a negative step, the contents of the range are still determined by the formula
>>> [65].to_bytes[] b'A'63, but the constraints are
>>> [65].to_bytes[] b'A'64 and
>>> [65].to_bytes[] b'A'68
A range object will be empty if
>>> [65].to_bytes[] b'A'69 does not meet the value constraint. Ranges do support negative indices, but these are interpreted as indexing from the end of the sequence determined by the positive indices
Ranges containing absolute values larger than are permitted but some features [such as ] may raise
Range examples
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 67
Ranges implement all of the sequence operations except concatenation and repetition [due to the fact that range objects can only represent sequences that follow a strict pattern and repetition and concatenation will usually violate that pattern]
startThe value of the start parameter [or
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 642 if the parameter was not supplied]stop
The value of the stop parameter
stepThe value of the step parameter [or
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 655 if the parameter was not supplied]
The advantage of the type over a regular or is that a object will always take the same [small] amount of memory, no matter the size of the range it represents [as it only stores the
>>> [65].to_bytes[] b'A'79,
>>> [65].to_bytes[] b'A'80 and
>>> [65].to_bytes[] b'A'81 values, calculating individual items and subranges as needed]
Range objects implement the ABC, and provide features such as containment tests, element index lookup, slicing and support for negative indices [see ]
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 68
Testing range objects for equality with
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 678 and
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 679 compares them as sequences. That is, two range objects are considered equal if they represent the same sequence of values. [Note that two range objects that compare equal might have different , and attributes, for example
>>> [65].to_bytes[] b'A'88 or
>>> [65].to_bytes[] b'A'89. ]
Changed in version 3. 2. Implement the Sequence ABC. Support slicing and negative indices. Test objects for membership in constant time instead of iterating through all items.
Changed in version 3. 3. Define ‘==’ and ‘. =’ to compare range objects based on the sequence of values they define [instead of comparing based on object identity].
New in version 3. 3. The , and attributes.
See also
The linspace recipe shows how to implement a lazy version of range suitable for floating point applications
Text Sequence Type —
Textual data in Python is handled with objects, or strings. Strings are immutable of Unicode code points. String literals are written in a variety of ways
Single quotes.
>>> [65].to_bytes[] b'A'
96Dấu ngoặc kép.
>>> [65].to_bytes[] b'A'
97Ba trích dẫn.
>>> [65].to_bytes[] b'A'
98,>>> [65].to_bytes[] b'A'
99
Các chuỗi được trích dẫn ba lần có thể kéo dài trên nhiều dòng - tất cả khoảng trắng được liên kết sẽ được bao gồm trong chuỗi ký tự
Các chuỗi ký tự là một phần của một biểu thức và chỉ có khoảng trắng giữa chúng sẽ được chuyển đổi hoàn toàn thành một chuỗi ký tự đơn. Tức là,
def to_bytes[n, length=1, byteorder='big', signed=False]: if byteorder == 'little': order = range[length] elif byteorder == 'big': 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
Xem để biết thêm về các dạng chuỗi ký tự khác nhau, bao gồm các chuỗi thoát được hỗ trợ và tiền tố
>>> [65].to_bytes[] b'A'62 [“raw”] vô hiệu hóa hầu hết quá trình xử lý chuỗi thoát
Strings may also be created from other objects using the constructor
Vì không có loại "ký tự" riêng biệt, nên việc lập chỉ mục một chuỗi sẽ tạo ra các chuỗi có độ dài 1. That is, for a non-empty string s,
def to_bytes[n, length=1, byteorder='big', signed=False]: if byteorder == 'little': order = range[length] elif byteorder == 'big': order = reversed[range[length]] else: raise ValueError["byteorder must be either 'little' or 'big'"] return bytes[[n >> i*8] & 0xff for i in order]03
There is also no mutable string type, but or can be used to efficiently construct strings from multiple fragments
Changed in version 3. 3. For backwards compatibility with the Python 2 series, the
def to_bytes[n, length=1, byteorder='big', signed=False]: if byteorder == 'little': order = range[length] elif byteorder == 'big': order = reversed[range[length]] else: raise ValueError["byteorder must be either 'little' or 'big'"] return bytes[[n >> i*8] & 0xff for i in order]06 prefix is once again permitted on string literals. It has no effect on the meaning of string literals and cannot be combined with the
>>> [65].to_bytes[] b'A'62 prefix. class str[object='']class str[object=b'' , encoding='utf-8' , errors='strict']
Return a version of object. If object is not provided, returns the empty string. Otherwise, the behavior of
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 633 depends on whether encoding or errors is given, as follows
If neither encoding nor errors is given,
def to_bytes[n, length=1, byteorder='big', signed=False]: if byteorder == 'little': order = range[length] elif byteorder == 'big': order = reversed[range[length]] else: raise ValueError["byteorder must be either 'little' or 'big'"] return bytes[[n >> i*8] & 0xff for i in order]09 returns , which is the “informal” or nicely printable string representation of object. For string objects, this is the string itself. If object does not have a method, then falls back to returning
If at least one of encoding or errors is given, object should be a [e. g. or ]. In this case, if object is a [or ] object, then
def to_bytes[n, length=1, byteorder='big', signed=False]: if byteorder == 'little': order = range[length] elif byteorder == 'big': order = reversed[range[length]] else: raise ValueError["byteorder must be either 'little' or 'big'"] return bytes[[n >> i*8] & 0xff for i in order]18 is equivalent to . Otherwise, the bytes object underlying the buffer object is obtained before calling . See and for information on buffer objects
Passing a object to without the encoding or errors arguments falls under the first case of returning the informal string representation [see also the command-line option to Python]. For example
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 69
For more information on the
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'22 class and its methods, see and the section below. To output formatted strings, see the and sections. In addition, see the section
String Methods
Strings implement all of the sequence operations, along with the additional methods described below
Strings also support two styles of string formatting, one providing a large degree of flexibility and customization [see , and ] and the other based on C
def to_bytes[n, length=1, byteorder='big', signed=False]: if byteorder == 'little': order = range[length] elif byteorder == 'big': order = reversed[range[length]] else: raise ValueError["byteorder must be either 'little' or 'big'"] return bytes[[n >> i*8] & 0xff for i in order]26 style formatting that handles a narrower range of types and is slightly harder to use correctly, but is often faster for the cases it can handle []
The section of the standard library covers a number of other modules that provide various text related utilities [including regular expression support in the module]
str. capitalize[]Return a copy of the string with its first character capitalized and the rest lowercased
Changed in version 3. 8. The first character is now put into titlecase rather than uppercase. This means that characters like digraphs will only have their first letter capitalized, instead of the full character.
str. casefold[]Return a casefolded copy of the string. Casefolded strings may be used for caseless matching
Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter
def to_bytes[n, length=1, byteorder='big', signed=False]: if byteorder == 'little': order = range[length] elif byteorder == 'big': order = reversed[range[length]] else: raise ValueError["byteorder must be either 'little' or 'big'"] return bytes[[n >> i*8] & 0xff for i in order]28 is equivalent to
def to_bytes[n, length=1, byteorder='big', signed=False]: if byteorder == 'little': order = range[length] elif byteorder == 'big': order = reversed[range[length]] else: raise ValueError["byteorder must be either 'little' or 'big'"] return bytes[[n >> i*8] & 0xff for i in order]29. Since it is already lowercase, would do nothing to
def to_bytes[n, length=1, byteorder='big', signed=False]: if byteorder == 'little': order = range[length] elif byteorder == 'big': order = reversed[range[length]] else: raise ValueError["byteorder must be either 'little' or 'big'"] return bytes[[n >> i*8] & 0xff for i in order]28; converts it to
def to_bytes[n, length=1, byteorder='big', signed=False]: if byteorder == 'little': order = range[length] elif byteorder == 'big': order = reversed[range[length]] else: raise ValueError["byteorder must be either 'little' or 'big'"] return bytes[[n >> i*8] & 0xff for i in order]29
The casefolding algorithm is described in section 3. 13 of the Unicode Standard
New in version 3. 3
str. center[width[ , fillchar]]Return centered in a string of length width. Padding is done using the specified fillchar [default is an ASCII space]. The original string is returned if width is less than or equal to
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'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. Chữ số bao gồm các ký tự thập phân và chữ số cần xử lý đặc biệt, chẳng hạn như chữ số chỉ số trên tương thích. 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
Gọi để kiểm tra xem chuỗ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]94 có phải là mã định danh dành riêng hay không, chẳng hạn như và
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[]
Trả về
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 656 nếu tất cả các ký tự trong chuỗi là ký tự số và có ít nhất một ký tự, 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. Các ký tự số bao gồm các ký tự chữ số và tất cả các ký tự có thuộc tính giá trị số Unicode, e. g. U+2155, VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numericstr. isprintable[]
Return
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 656 if all characters in the string are printable or the string is empty,
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 638 otherwise. Nonprintable characters are those characters defined in the Unicode character database as “Other” or “Separator”, excepting the ASCII space [0x20] which is considered printable. [Note that printable characters in this context are those which should not be escaped when is invoked on a string. It has no bearing on the handling of strings written to or . ]str. isspace[]
Return
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 656 if there are only whitespace characters in the string and there is at least one character,
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 638 otherwise
A character is whitespace if in the Unicode character database [see ], either its general category is
>>> int.from_bytes[b'\x00\x10', byteorder='big'] 16 >>> int.from_bytes[b'\x00\x10', byteorder='little'] 4096 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=True] -1024 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=False] 64512 >>> int.from_bytes[[255, 0, 0], byteorder='big'] 1671168009 [“Separator, space”], or its bidirectional class is one of
>>> int.from_bytes[b'\x00\x10', byteorder='big'] 16 >>> int.from_bytes[b'\x00\x10', byteorder='little'] 4096 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=True] -1024 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=False] 64512 >>> int.from_bytes[[255, 0, 0], byteorder='big'] 1671168010,
>>> int.from_bytes[b'\x00\x10', byteorder='big'] 16 >>> int.from_bytes[b'\x00\x10', byteorder='little'] 4096 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=True] -1024 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=False] 64512 >>> int.from_bytes[[255, 0, 0], byteorder='big'] 1671168011, or
>>> int.from_bytes[b'\x00\x10', byteorder='big'] 16 >>> int.from_bytes[b'\x00\x10', byteorder='little'] 4096 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=True] -1024 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=False] 64512 >>> int.from_bytes[[255, 0, 0], byteorder='big'] 1671168012str. istitle[]
Return
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 656 if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 638 otherwisestr. isupper[]
Return
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 656 if all cased characters in the string are uppercase and there is at least one cased character,
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 638 otherwise
>>> n = 19 >>> bin[n] '0b10011' >>> n.bit_count[] 3 >>> [-n].bit_count[] 35str. join[iterable]
Return a string which is the concatenation of the strings in iterable. A will be raised if there are any non-string values in iterable, including objects. The separator between elements is the string providing this method
str. ljust[width[ , fillchar]]Return the string left justified in a string of length width. Padding is done using the specified fillchar [default is an ASCII space]. The original string is returned if width is less than or equal to
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'13str. lower[]
Return a copy of the string with all the cased characters converted to lowercase
The lowercasing algorithm used is described in section 3. 13 of the Unicode Standard
str. lstrip[[chars]]Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 631, the chars argument defaults to removing whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped
>>> n = 19 >>> bin[n] '0b10011' >>> n.bit_count[] 3 >>> [-n].bit_count[] 36
See for a method that will remove a single prefix string rather than all of a set of characters. For example
>>> n = 19 >>> bin[n] '0b10011' >>> n.bit_count[] 3 >>> [-n].bit_count[] 37static str. maketrans[x[ , y[ , z]]]
This static method returns a translation table usable for
If there is only one argument, it must be a dictionary mapping Unicode ordinals [integers] or characters [strings of length 1] to Unicode ordinals, strings [of arbitrary lengths] or
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 631. Character keys will then be converted to ordinals
If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 631 in the resultstr. partition[sep]
Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings
str. removeprefix[prefix , /]If the string starts with the prefix string, return
>>> int.from_bytes[b'\x00\x10', byteorder='big'] 16 >>> int.from_bytes[b'\x00\x10', byteorder='little'] 4096 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=True] -1024 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=False] 64512 >>> int.from_bytes[[255, 0, 0], byteorder='big'] 1671168025. Otherwise, return a copy of the original string
>>> n = 19 >>> bin[n] '0b10011' >>> n.bit_count[] 3 >>> [-n].bit_count[] 38
New in version 3. 9
str. removesuffix[suffix , /]If the string ends with the suffix string and that suffix is not empty, return
>>> int.from_bytes[b'\x00\x10', byteorder='big'] 16 >>> int.from_bytes[b'\x00\x10', byteorder='little'] 4096 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=True] -1024 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=False] 64512 >>> int.from_bytes[[255, 0, 0], byteorder='big'] 1671168026. Otherwise, return a copy of the original string
>>> n = 19 >>> bin[n] '0b10011' >>> n.bit_count[] 3 >>> [-n].bit_count[] 39
New in version 3. 9
str. replace[old , new[ , count]]Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced
str. rfind[sub[ , start[ , end]]]Return the highest index in the string where substring sub is found, such that sub is contained within
def to_bytes[n, length=1, byteorder='big', signed=False]: if byteorder == 'little': order = range[length] elif byteorder == 'big': order = reversed[range[length]] else: raise ValueError["byteorder must be either 'little' or 'big'"] return bytes[[n >> i*8] & 0xff for i in order]49. Optional arguments start and end are interpreted as in slice notation. Return
>>> n = 19 >>> bin[n] '0b10011' >>> n.bit_count[] 3 >>> [-n].bit_count[] 341 on failurestr. rindex[sub[ , start[ , end]]]
Like but raises when the substring sub is not found
str. rjust[width[ , fillchar]]Return the string right justified in a string of length width. Padding is done using the specified fillchar [default is an ASCII space]. The original string is returned if width is less than or equal to
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'13str. rpartition[sep]
Split the string at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself
str. rsplit[sep=None , maxsplit=- 1]Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 631, any whitespace string is a separator. Except for splitting from the right, behaves like which is described in detail belowstr. rstrip[[chars]]
Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 631, the chars argument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped
def bit_count[self]: return bin[self].count["1"]0
See for a method that will remove a single suffix string rather than all of a set of characters. For example
def bit_count[self]: return bin[self].count["1"]1str. split[sep=None , maxsplit=- 1]
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. strip[[chars]]
Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 631, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped
def bit_count[self]: return bin[self].count["1"]7
The outermost leading and trailing chars argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in chars. A similar action takes place on the trailing end. For example
def bit_count[self]: return bin[self].count["1"]8str. swapcase[]
Return a copy of the string with uppercase characters converted to lowercase and vice versa. Note that it is not necessarily true that
>>> int.from_bytes[b'\x00\x10', byteorder='big'] 16 >>> int.from_bytes[b'\x00\x10', byteorder='little'] 4096 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=True] -1024 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=False] 64512 >>> int.from_bytes[[255, 0, 0], byteorder='big'] 1671168067str. title[]
Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase
For example
def bit_count[self]: return bin[self].count["1"]9
The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'0
The function does not have this problem, as it splits words on spaces only
Alternatively, a workaround for apostrophes can be constructed using regular expressions
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'1str. translate[table]
Return a copy of the string in which each character has been mapped through the given translation table. The table must be an object that implements indexing via
>>> int.from_bytes[b'\x00\x10', byteorder='big'] 16 >>> int.from_bytes[b'\x00\x10', byteorder='little'] 4096 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=True] -1024 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=False] 64512 >>> int.from_bytes[[255, 0, 0], byteorder='big'] 1671168069, typically a or . When indexed by a Unicode ordinal [an integer], the table object can do any of the following. return a Unicode ordinal or a string, to map the character to one or more other characters; return
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 631, to delete the character from the return string; or raise a exception, to map the character to itself
Bạn có thể sử dụng để tạo bản đồ dịch từ ánh xạ ký tự sang ký tự ở các định dạng khác nhau
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 Formatting
Note
The formatting operations described here exhibit a variety of quirks that lead to a number of common errors [such as failing to display tuples and dictionaries correctly]. Using the newer , the interface, or may help avoid these errors. Each of these alternatives provides their own trade-offs and benefits of simplicity, flexibility, and/or extensibility
String objects have one unique built-in operation. the
>>> int.from_bytes[b'\x00\x10', byteorder='big'] 16 >>> int.from_bytes[b'\x00\x10', byteorder='little'] 4096 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=True] -1024 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=False] 64512 >>> int.from_bytes[[255, 0, 0], byteorder='big'] 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
The
>>> int.from_bytes[b'\x00\x10', byteorder='big'] 16 >>> int.from_bytes[b'\x00\x10', byteorder='little'] 4096 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=True] -1024 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=False] 64512 >>> int.from_bytes[[255, 0, 0], byteorder='big'] 16711680
87 character, which marks the start of the specifierMapping key [optional], consisting of a parenthesised sequence of characters [for example,
>>> int.from_bytes[b'\x00\x10', byteorder='big'] 16 >>> int.from_bytes[b'\x00\x10', byteorder='little'] 4096 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=True] -1024 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=False] 64512 >>> int.from_bytes[[255, 0, 0], byteorder='big'] 16711680
88]Conversion flags [optional], which affect the result of some conversion types
Minimum field width [optional]. If specified as an
>>> int.from_bytes[b'\x00\x10', byteorder='big'] 16 >>> int.from_bytes[b'\x00\x10', byteorder='little'] 4096 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=True] -1024 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=False] 64512 >>> int.from_bytes[[255, 0, 0], byteorder='big'] 16711680
89 [asterisk], the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precisionPrecision [optional], given as a
>>> int.from_bytes[b'\x00\x10', byteorder='big'] 16 >>> int.from_bytes[b'\x00\x10', byteorder='little'] 4096 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=True] -1024 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=False] 64512 >>> int.from_bytes[[255, 0, 0], byteorder='big'] 16711680
90 [dot] followed by the precision. If specified as>>> int.from_bytes[b'\x00\x10', byteorder='big'] 16 >>> int.from_bytes[b'\x00\x10', byteorder='little'] 4096 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=True] -1024 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=False] 64512 >>> int.from_bytes[[255, 0, 0], byteorder='big'] 16711680
89 [an asterisk], the actual precision is read from the next element of the tuple in values, and the value to convert comes after the precisionLength modifier [optional]
Conversion type
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 >> n.bit_count[] 3 >>> [-n].bit_count[] 341 on failure
The subsequence to search for may be any or an integer in the range 0 to 255
Changed in version 3. 3. Also accept an integer in the range 0 to 255 as the subsequence.
bytes. rindex[sub[ , start[ , end]]]bytearray. rindex[sub[ , start[ , end]]]Like but raises when the subsequence sub is not found
The subsequence to search for may be any or an integer in the range 0 to 255
Changed in version 3. 3. Also accept an integer in the range 0 to 255 as the subsequence.
bytes. rpartition[sep]bytearray. rpartition[sep]Split the sequence at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself or its bytearray copy, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty bytes or bytearray objects, followed by a copy of the original sequence
The separator to search for may be any
bytes. startswith[tiền tố[ , . start[, end]]]bytearray.startswith[prefix[ , start[ , end]]]Return
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 656 if the binary data starts with the specified prefix, otherwise return
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 638. prefix can also be a tuple of prefixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position
The prefix[es] to search for may be any
bytes. dịch[bảng , / . , delete=b'']bytearray.translate[table , / , delete=b'']Return a copy of the bytes or bytearray object where all bytes occurring in the optional argument delete are removed, and the remaining bytes have been mapped through the given translation table, which must be a bytes object of length 256
You can use the method to create a translation table
Set the table argument to
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 631 for translations that only delete characters
>>> [65].to_bytes[] b'A'4
Changed in version 3. 6. delete is now supported as a keyword argument.
The following methods on bytes and bytearray objects have default behaviours that assume the use of ASCII compatible binary formats, but can still be used with arbitrary binary data by passing appropriate arguments. Note that all of the bytearray methods in this section do not operate in place, and instead produce new objects
bytes. center[width[ , fillbyte]]bytearray. center[width[ , fillbyte]]Return a copy of the object centered in a sequence of length width. Padding is done using the specified fillbyte [default is an ASCII space]. For objects, the original sequence is returned if width is less than or equal to
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'13
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
bytes. ljust[width[ , fillbyte]]bytearray. ljust[width[ , fillbyte]]Return a copy of the object left justified in a sequence of length width. Padding is done using the specified fillbyte [default is an ASCII space]. For objects, the original sequence is returned if width is less than or equal to
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'13
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
bytes. lstrip[[chars]]bytearray. lstrip[[chars]]Return a copy of the sequence with specified leading bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 631, the chars argument defaults to removing ASCII whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped
>>> [65].to_bytes[] b'A'5
The binary sequence of byte values to remove may be any . See for a method that will remove a single prefix string rather than all of a set of characters. For example
>>> [65].to_bytes[] b'A'6
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
bytes. rjust[width[ , fillbyte]]bytearray. rjust[width[ , fillbyte]]Return a copy of the object right justified in a sequence of length width. Padding is done using the specified fillbyte [default is an ASCII space]. For objects, the original sequence is returned if width is less than or equal to
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'13
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
bytes. rsplit[sep=None , maxsplit=- 1]bytearray. rsplit[sep=None , maxsplit=- 1]Split the binary sequence into subsequences of the same type, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 631, any subsequence consisting solely of ASCII whitespace is a separator. Except for splitting from the right, behaves like which is described in detail belowbytes. rstrip[[chars]]bytearray. rstrip[[chars]]
Return a copy of the sequence with specified trailing bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 631, the chars argument defaults to removing ASCII whitespace. Đối số ký tự không phải là một hậu tố;
>>> [65].to_bytes[] b'A'7
The binary sequence of byte values to remove may be any . See for a method that will remove a single suffix string rather than all of a set of characters. For example
>>> [65].to_bytes[] b'A'8
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
bytes. tách[sep=Không có . , maxsplit=- 1]bytearray.tách[sep=Không có, maxsplit=- 1]Split the binary sequence into subsequences of the same type, using sep as the delimiter string. If maxsplit is given and non-negative, at most maxsplit splits are done [thus, the list will have at most
>>> int.from_bytes[b'\x00\x10', byteorder='big'] 16 >>> int.from_bytes[b'\x00\x10', byteorder='little'] 4096 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=True] -1024 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=False] 64512 >>> int.from_bytes[[255, 0, 0], byteorder='big'] 1671168037 elements]. If maxsplit is not specified or is
>>> n = 19 >>> bin[n] '0b10011' >>> n.bit_count[] 3 >>> [-n].bit_count[] 341, then there is no limit on the number of splits [all possible splits are made]
If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty subsequences [for example,
>>> [-2.0].is_integer[] True >>> [3.2].is_integer[] False27 returns
>>> [-2.0].is_integer[] True >>> [3.2].is_integer[] False28]. The sep argument may consist of a multibyte sequence [for example,
>>> [-2.0].is_integer[] True >>> [3.2].is_integer[] False29 returns
>>> [-2.0].is_integer[] True >>> [3.2].is_integer[] False30]. Splitting an empty sequence with a specified separator returns
>>> [-2.0].is_integer[] True >>> [3.2].is_integer[] False31 or
>>> [-2.0].is_integer[] True >>> [3.2].is_integer[] False32 depending on the type of object being split. The sep argument may be any
For example
>>> [65].to_bytes[] b'A'9
If sep is not specified or is
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 631, a different splitting algorithm is applied. runs of consecutive ASCII whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the sequence has leading or trailing whitespace. Consequently, splitting an empty sequence or a sequence consisting solely of ASCII whitespace without a specified separator returns
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 649
For example
def to_bytes[n, length=1, byteorder='big', signed=False]: if byteorder == 'little': order = range[length] elif byteorder == 'big': order = reversed[range[length]] else: raise ValueError["byteorder must be either 'little' or 'big'"] return bytes[[n >> i*8] & 0xff for i in order]0bytes. strip[[chars]]bytearray. strip[[chars]]
Return a copy of the sequence with specified leading and trailing bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 631, the chars argument defaults to removing ASCII whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped
def to_bytes[n, length=1, byteorder='big', signed=False]: if byteorder == 'little': order = range[length] elif byteorder == 'big': order = reversed[range[length]] else: raise ValueError["byteorder must be either 'little' or 'big'"] return bytes[[n >> i*8] & 0xff for i in order]1
The binary sequence of byte values to remove may be any
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
The following methods on bytes and bytearray objects assume the use of ASCII compatible binary formats and should not be applied to arbitrary binary data. Note that all of the bytearray methods in this section do not operate in place, and instead produce new objects
bytes. capitalize[]bytearray. capitalize[]Return a copy of the sequence with each byte interpreted as an ASCII character, and the first byte capitalized and the rest lowercased. Non-ASCII byte values are passed through unchanged
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
bytes. expandtabs[tabsize=8]bytearray. expandtabs[tabsize=8]Return a copy of the sequence where all ASCII tab characters are replaced by one or more ASCII spaces, depending on the current column and the given tab size. Tab positions occur every tabsize bytes [default is 8, giving tab positions at columns 0, 8, 16 and so on]. To expand the sequence, the current column is set to zero and the sequence is examined byte by byte. If the byte is an ASCII tab character [
>>> [-2.0].is_integer[] True >>> [3.2].is_integer[] False36], one or more space characters are inserted in the result until the current column is equal to the next tab position. [The tab character itself is not copied. ] If the current byte is an ASCII newline [
>>> [-2.0].is_integer[] True >>> [3.2].is_integer[] False37] or carriage return [
>>> [-2.0].is_integer[] True >>> [3.2].is_integer[] False38], it is copied and the current column is reset to zero. Any other byte value is copied unchanged and the current column is incremented by one regardless of how the byte value is represented when printed
def to_bytes[n, length=1, byteorder='big', signed=False]: if byteorder == 'little': order = range[length] elif byteorder == 'big': order = reversed[range[length]] else: raise ValueError["byteorder must be either 'little' or 'big'"] return bytes[[n >> i*8] & 0xff for i in order]2
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
bytes. isalnum[]bytearray. isalnum[]Trả về
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 656 nếu tất cả các byte trong chuỗi là ký tự ASCII theo thứ tự bảng chữ cái hoặc chữ số thập phân ASCII và chuỗi không trống, 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. Alphabetic ASCII characters are those byte values in the sequence
>>> [-2.0].is_integer[] True >>> [3.2].is_integer[] False41. ASCII decimal digits are those byte values in the sequence
>>> [-2.0].is_integer[] True >>> [3.2].is_integer[] False42
For example
def to_bytes[n, length=1, byteorder='big', signed=False]: if byteorder == 'little': order = range[length] elif byteorder == 'big': order = reversed[range[length]] else: raise ValueError["byteorder must be either 'little' or 'big'"] return bytes[[n >> i*8] & 0xff for i in order]3bytes. isalpha[]bytearray. isalpha[]
Return
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 656 if all bytes in the sequence are alphabetic ASCII characters and the sequence is not empty,
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 638 otherwise. Alphabetic ASCII characters are those byte values in the sequence
>>> [-2.0].is_integer[] True >>> [3.2].is_integer[] False41
For example
def to_bytes[n, length=1, byteorder='big', signed=False]: if byteorder == 'little': order = range[length] elif byteorder == 'big': order = reversed[range[length]] else: raise ValueError["byteorder must be either 'little' or 'big'"] return bytes[[n >> i*8] & 0xff for i in order]4bytes. isascii[]bytearray. isascii[]
Return
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 656 if the sequence is empty or all bytes in the sequence are ASCII,
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 638 otherwise. ASCII bytes are in the range 0-0x7F
New in version 3. 7
bytes. isdigit[]bytearray. isdigit[]Return
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 656 if all bytes in the sequence are ASCII decimal digits and the sequence is not empty,
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 638 otherwise. ASCII decimal digits are those byte values in the sequence
>>> [-2.0].is_integer[] True >>> [3.2].is_integer[] False42
For example
def to_bytes[n, length=1, byteorder='big', signed=False]: if byteorder == 'little': order = range[length] elif byteorder == 'big': order = reversed[range[length]] else: raise ValueError["byteorder must be either 'little' or 'big'"] return bytes[[n >> i*8] & 0xff for i in order]5bytes. islower[]bytearray. islower[]
Return
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 656 if there is at least one lowercase ASCII character in the sequence and no uppercase ASCII characters,
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 638 otherwise
For example
def to_bytes[n, length=1, byteorder='big', signed=False]: if byteorder == 'little': order = range[length] elif byteorder == 'big': order = reversed[range[length]] else: raise ValueError["byteorder must be either 'little' or 'big'"] return bytes[[n >> i*8] & 0xff for i in order]6
Lowercase ASCII characters are those byte values in the sequence
>>> [-2.0].is_integer[] True >>> [3.2].is_integer[] False53. Uppercase ASCII characters are those byte values in the sequence
>>> [-2.0].is_integer[] True >>> [3.2].is_integer[] False54bytes. isspace[]bytearray. isspace[]
Return
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 656 if all bytes in the sequence are ASCII whitespace and the sequence is not empty,
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 638 otherwise. ASCII whitespace characters are those byte values in the sequence
>>> [-2.0].is_integer[] True >>> [3.2].is_integer[] False57 [space, tab, newline, carriage return, vertical tab, form feed]bytes. istitle[]bytearray. 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
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
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
Không giống như , luôn luôn xảy ra trường hợp
>>> [-2.0].is_integer[] True >>> [3.2].is_integer[] False71 đối với các phiên bản nhị phân. Chuyển đổi trường hợp là đối xứng trong ASCII, mặc dù điều đó thường không đúng đối với các điểm mã Unicode tùy ý
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
bytes. tiêu đề[]bytearray. tiêu đề[]Trả về phiên bản có tiêu đề của chuỗi nhị phân trong đó các từ bắt đầu bằng ký tự ASCII viết hoa và các ký tự còn lại là chữ thường. Các giá trị byte chưa được khai thác không được sửa đổi
For example
>>> int.from_bytes[b'\x00\x10', byteorder='big'] 16 >>> int.from_bytes[b'\x00\x10', byteorder='little'] 4096 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=True] -1024 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=False] 64512 >>> int.from_bytes[[255, 0, 0], byteorder='big'] 167116803
Các ký tự ASCII chữ thường là các giá trị byte trong chuỗi
>>> [-2.0].is_integer[] True >>> [3.2].is_integer[] False53. Các ký tự ASCII chữ hoa là những giá trị byte trong chuỗi
>>> [-2.0].is_integer[] True >>> [3.2].is_integer[] False54. Tất cả các giá trị byte khác đều không có vỏ
The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result
>>> int.from_bytes[b'\x00\x10', byteorder='big'] 16 >>> int.from_bytes[b'\x00\x10', byteorder='little'] 4096 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=True] -1024 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=False] 64512 >>> int.from_bytes[[255, 0, 0], byteorder='big'] 167116804
Có thể xây dựng giải pháp thay thế cho dấu nháy đơn bằng cách sử dụng biểu thức chính quy
>>> int.from_bytes[b'\x00\x10', byteorder='big'] 16 >>> int.from_bytes[b'\x00\x10', byteorder='little'] 4096 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=True] -1024 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=False] 64512 >>> int.from_bytes[[255, 0, 0], byteorder='big'] 167116805
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
byte. trên[]bytearray. trên[]Trả về một bản sao của chuỗi với tất cả các ký tự ASCII chữ thường được chuyển đổi thành chữ hoa tương ứng của chúng
For example
>>> int.from_bytes[b'\x00\x10', byteorder='big'] 16 >>> int.from_bytes[b'\x00\x10', byteorder='little'] 4096 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=True] -1024 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=False] 64512 >>> int.from_bytes[[255, 0, 0], byteorder='big'] 167116806
Lowercase ASCII characters are those byte values in the sequence
>>> [-2.0].is_integer[] True >>> [3.2].is_integer[] False53. Uppercase ASCII characters are those byte values in the sequence
>>> [-2.0].is_integer[] True >>> [3.2].is_integer[] False54
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
bytes. zfill[width]bytearray. zfill[width]Return a copy of the sequence left filled with ASCII
>>> [-2.0].is_integer[] True >>> [3.2].is_integer[] False76 digits to make a sequence of length width. A leading sign prefix [
>>> [-2.0].is_integer[] True >>> [3.2].is_integer[] False77/
>>> [-2.0].is_integer[] True >>> [3.2].is_integer[] False78] is handled by inserting the padding after the sign character rather than before. For objects, the original sequence is returned if width is less than or equal to
>>> [-2.0].is_integer[] True >>> [3.2].is_integer[] False80
For example
>>> int.from_bytes[b'\x00\x10', byteorder='big'] 16 >>> int.from_bytes[b'\x00\x10', byteorder='little'] 4096 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=True] -1024 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=False] 64512 >>> int.from_bytes[[255, 0, 0], byteorder='big'] 167116807
Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made
def to_bytes[n, length=1, byteorder='big', signed=False]:
if byteorder == 'little':
order = range[length]
elif byteorder == 'big':
order = reversed[range[length]]
else:
raise ValueError["byteorder must be either 'little' or 'big'"]
return bytes[[n >> i*8] & 0xff for i in order]
26-style Bytes Formatting
Note
The formatting operations described here exhibit a variety of quirks that lead to a number of common errors [such as failing to display tuples and dictionaries correctly]. 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]. Điều này còn được gọi là định dạng byte hoặc toán tử nội suy. 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
The
>>> int.from_bytes[b'\x00\x10', byteorder='big'] 16 >>> int.from_bytes[b'\x00\x10', byteorder='little'] 4096 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=True] -1024 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=False] 64512 >>> int.from_bytes[[255, 0, 0], byteorder='big'] 16711680
87 character, which marks the start of the specifierMapping key [optional], consisting of a parenthesised sequence of characters [for example,
>>> int.from_bytes[b'\x00\x10', byteorder='big'] 16 >>> int.from_bytes[b'\x00\x10', byteorder='little'] 4096 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=True] -1024 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=False] 64512 >>> int.from_bytes[[255, 0, 0], byteorder='big'] 16711680
88]Conversion flags [optional], which affect the result of some conversion types
Minimum field width [optional]. If specified as an
>>> int.from_bytes[b'\x00\x10', byteorder='big'] 16 >>> int.from_bytes[b'\x00\x10', byteorder='little'] 4096 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=True] -1024 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=False] 64512 >>> int.from_bytes[[255, 0, 0], byteorder='big'] 16711680
89 [asterisk], the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precisionPrecision [optional], given as a
>>> int.from_bytes[b'\x00\x10', byteorder='big'] 16 >>> int.from_bytes[b'\x00\x10', byteorder='little'] 4096 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=True] -1024 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=False] 64512 >>> int.from_bytes[[255, 0, 0], byteorder='big'] 16711680
90 [dot] followed by the precision. If specified as>>> int.from_bytes[b'\x00\x10', byteorder='big'] 16 >>> int.from_bytes[b'\x00\x10', byteorder='little'] 4096 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=True] -1024 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=False] 64512 >>> int.from_bytes[[255, 0, 0], byteorder='big'] 16711680
89 [an asterisk], the actual precision is read from the next element of the tuple in values, and the value to convert comes after the precisionLength modifier [optional]
Conversion type
When the right argument is a dictionary [or other mapping type], then the formats in the bytes object must include a parenthesised mapping key into that dictionary inserted immediately after the
>>> int.from_bytes[b'\x00\x10', byteorder='big'] 16 >>> int.from_bytes[b'\x00\x10', byteorder='little'] 4096 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=True] -1024 >>> int.from_bytes[b'\xfc\x00', byteorder='big', signed=False] 64512 >>> int.from_bytes[[255, 0, 0], byteorder='big'] 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 '-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[] False8ndim
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. The value is informational only
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. Loại là bất biến và — không thể thay đổi nội dung của nó sau khi nó được tạo;
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
Sử dụng danh sách các phần tử được phân tách bằng dấu phẩy trong dấu ngoặc nhọn.
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
109Sử dụng một bộ hiểu.
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
113Sử dụng hàm tạo kiểu.
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
51,def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
115,def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
116
Các trường hợp và cung cấp các hoạt động sau
[các] ống kínhTrả về số phần tử trong tập hợp s [số lượng của 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 6 120issuperset[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
copy[]Return a shallow copy of the set
Note, the non-operator versions of , , , , , and methods will accept any iterable as an argument. In contrast, their operator based counterparts require their arguments to be sets. 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]
Instances of are compared to instances of based on their members. Ví dụ:
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6134 trả về
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 656 và
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6136 cũng vậy
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
Use a comma-separated list of
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
165 pairs within braces.def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
166 ordef bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
167Use a dict comprehension.
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
50,def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
169Use the type constructor.
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
170,def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
171,def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
172
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. Mặt khác, đối số vị trí phải là một đối tượng. 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
Việc cung cấp các đối số từ khóa như trong ví dụ đầu tiên chỉ hoạt động đối với các khóa là mã định danh Python hợp lệ. 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]Trả về số mục trong từ điển d
d[key]Return the item of d with key key. Tăng phím nếu không có trong bản đồ
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. Hoạt động
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6176 sau đó trả lại hoặc tăng bất cứ thứ gì được trả lại hoặc tăng bởi lệnh gọi
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6178. 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. Nếu
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6175 không được xác định, được nâng lên.
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6175 phải là một phương pháp;
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 600
Ví dụ trên cho thấy một phần của việc thực hiện. Một phương pháp
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6184 khác được sử dụng bởid[key] = giá trị
Đặt
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6176 thành giá trịdel d[key]
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
copy[]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]]If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a is raised
popitem[]Remove and return a
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6197 pair from the dictionary. Các cặp được trả lại theo thứ tự LIFO
is useful to destructively iterate over a dictionary, as often used in set algorithms. 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'] --> 6208values[]
Trả lại chế độ xem mới về các giá trị của từ điển. See the
So sánh bình đẳng giữa một chế độ xem
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6209 và chế độ xem khác sẽ luôn trả về
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 638. 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 . khác
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
New in version 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
New in version 3. 9
Dictionaries compare equal if and only if they have the same
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6197 pairs [regardless of ordering]. Order comparisons [‘’] raise .
Dictionaries preserve insertion order. 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 objects
The 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. lập bản đồTrả lại a bao bọc từ điển gốc mà chế độ xem đề cập đến
Mới trong phiên bản 3. 10
Chế độ xem khóa giống như được đặt vì các mục nhập của chúng là duy nhất và có thể băm. Nếu tất cả các giá trị đều có thể băm, để các cặp
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6197 là duy nhất và có thể băm, thì chế độ xem các mục cũng giống như được đặt. [Values views are not treated as set-like since the entries are generally not unique. ] 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 Types
Python’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. Xem mô-đun để biết một số ví dụ
Python's và trình trang trí cung cấp một cách thuận tiện để triển khai các giao thức này. Nếu một hàm tạo được trang trí bằng trình tạo trang trí, thì nó sẽ trả về trình quản lý ngữ cảnh thực hiện các phương thức và cần thiết, thay vì trình vòng lặp được tạo bởi hàm tạo không được trang trí
Lưu ý rằng không có vị trí cụ thể nào cho bất kỳ phương thức nào trong số này trong cấu trúc kiểu cho các đối tượng Python trong API Python/C. 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. So với chi phí thiết lập bối cảnh thời gian chạy, chi phí hoạt động của một tra cứu từ điển một lớp là không đáng kể
Nhập các loại chú thích — ,
Các loại tích hợp sẵn cốt lõi cho are và
Loại bí danh chung
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6252 đối tượng thường được tạo bởi một lớp. Chúng thường được sử dụng với , chẳng hạn như hoặc. Ví dụ:
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6255 là một đối tượng
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6252 được tạo bằng cách đăng ký lớp
def bit_count[self]: return bin[self].count["1"]93 với đối số.
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6252 đối tượng được dự định chủ yếu để sử dụng với
Note
Nói chung, chỉ có thể đăng ký một lớp nếu lớp đó thực hiện phương thức đặc biệt
Một đối tượng
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6252 hoạt động như một proxy cho một , triển khai các generic được tham số hóa
Đối với một lớp chứa, [các] đối số được cung cấp cho một lớp có thể chỉ ra [các] loại phần tử mà một đối tượng chứa. Ví dụ:
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6262 có thể được sử dụng trong chú thích loại để biểu thị một trong đó tất cả các phần tử đều thuộc loại
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
Nếu
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
269, thì>>> n = 19 >>> bin[n] '0b10011' >>> n.bit_count[] 3 >>> [-n].bit_count[] 3
82 sẽ là một đối tượng mà các giá trị trả về củadef bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
271 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'] --> 6
272 đều thuộc loại. Chúng ta có thể biểu diễn loại đối tượng này trong các chú thích kiểu vớidef bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
252def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
275Nếu
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
276, [lưu ýdef from_bytes[bytes, byteorder='big', signed=False]: if byteorder == 'little': little_ordered = list[bytes] elif byteorder == 'big': little_ordered = list[reversed[bytes]] else: raise ValueError["byteorder must be either 'little' or 'big'"] n = sum[b 6
281 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'] --> 6
282 đều thuộc loại. Trong chú thích loại, chúng tôi sẽ đại diện cho nhiều đối tượng này bằngdef bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
284
Các đối tượng
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6252 là các thể hiện của lớp, cũng có thể được sử dụng để tạo trực tiếp các đối tượng
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6252T[X, Y, . ]
Tạo một
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6252 đại diện cho một loại
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6289 được tham số hóa bởi các loại X, Y, v.v. tùy thuộc vào
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6289 được sử dụng. Ví dụ: một hàm mong đợi một phần tử chứa
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 605
Một ví dụ khác cho các đối tượng, sử dụng a , là loại chung mong đợi hai tham số loại đại diện cho loại khóa và loại giá trị. Trong ví dụ này, hàm mong đợi một
>>> [1024].to_bytes[2, byteorder='big'] b'\x04\x00' >>> [1024].to_bytes[10, byteorder='big'] b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> [-1024].to_bytes[10, byteorder='big', signed=True] b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes[[x.bit_length[] + 7] // 8, byteorder='little'] b'\xe8\x03'68 với các khóa thuộc loại và các giá trị thuộc loại
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 606
Các hàm dựng sẵn và không chấp nhận các loại
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6252 cho đối số thứ hai của chúng
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 607
Thời gian chạy Python không thực thi. Điều này mở rộng đến các loại chung và các tham số loại của chúng. Khi tạo đối tượng vùng chứa từ
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6252, các phần tử trong vùng chứa không được kiểm tra đối với loại của chúng. Ví dụ: đoạn mã sau không được khuyến khích nhưng sẽ chạy không có lỗi
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 608
Hơn nữa, các tham số loại được tham số hóa xóa các tham số loại trong quá trình tạo đối tượng
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 609
Gọi hoặc trên chung hiển thị loại được tham số hóa
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 610
Phương pháp của các thùng chứa chung sẽ đưa ra một ngoại lệ để không cho phép các lỗi như
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6304
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 611
Tuy nhiên, các biểu thức như vậy có giá trị khi được sử dụng. Chỉ mục phải có nhiều phần tử bằng với số mục biến loại trong đố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
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 612
Các lớp chung tiêu chuẩn
The following standard library classes support parameterized generics. danh sách này là không đầy đủ
Thuộc tính đặc biệt của def bit_length[self]:
s = bin[self] # binary representation: bin[-37] --> '-0b100101'
s = s.lstrip['-0b'] # remove leading zeros and minus sign
return len[s] # len['100101'] --> 6
252 đối tượng
Tất cả các generic được tham số hóa đều triển khai các thuộc tính chỉ đọc đặc biệt
tên chung. __origin__Thuộc tính này trỏ đến lớp chung không tham số hóa
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 613tên chung. __args__
Thuộc tính này là [có thể có độ dài 1] của các loại chung được truyền cho bản gốc của lớp chung
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 614tên chung. __tham số__
Thuộc tính này là một bộ được tính toán chậm [có thể trống] gồm các biến loại duy nhất được tìm thấy trong
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6306
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 615
Note
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 với các tham số có thể khô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'] --> 6365 sau khi thay thế vì mục đích chủ yếu là để kiểm tra kiểu tĩnhtên chung. __unpacked__
Một giá trị boolean đúng nếu bí danh đã được giải nén bằng cách sử dụng toán 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'00 [xem phần ]
Mới trong phiên bản 3. 11
See also
PEP 484 - Gợi ý loạiGiới thiệu khung của Python cho các chú thích loại
PEP 585 - Nhập gợi ý Generics trong bộ sưu tập tiêu chuẩnGiới thiệu khả năng tham số hóa các lớp thư viện tiêu chuẩn, miễn là chúng triển khai phương thức lớp đặc biệt
, vàDocumentation on how to implement generic classes that can be parameterized at runtime and understood by static type-checkers
New in version 3. 9
Loại liên minh
Một đối tượng hợp lưu giữ giá trị của 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'] --> 6371 [theo bit hoặc] trên nhiều. These types are intended primarily for . Biểu thức kiểu kết hợp cho phép cú pháp gợi ý kiểu sạch hơn so vớiX . Y . .
Xác định một đối tượng kết hợp chứa các loại X, Y, v.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'] --> 6373 có nghĩa là X hoặc Y. Nó 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'] --> 6374. Ví dụ: hàm sau mong đợi một đối số kiểu 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'] --> 616union_object == khác
Các đối tượng kết hợp có thể được kiểm tra sự bình đẳng với các đối tượng kết hợp khác. Thông tin chi tiết
Liên minh công đoàn bị san 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'] --> 6
17Các loại dư thừa được loại bỏ
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
18Khi so sánh các công đoàn, thứ tự bị bỏ qua
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
19Nó tương thích 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
20Các loại tùy chọn có thể được viết dưới dạng hợp nhất 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
31def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
21
Các cuộc gọi đến và cũng được hỗ trợ với một đối tượng hợp nhấ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'] --> 622
Tuy nhiên, không thể sử dụng các đối tượng hợp có chứa
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 623
Loại tiếp xúc với người dùng cho đối tượng hợp nhất có thể được truy cập và sử dụng để kiểm tra. Một đối tượng không thể được khởi tạo từ loại
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 624
Note
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'] --> 6383 cho các đối tượng kiểu đã được thêm vào để hỗ trợ cú pháp
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6373. Nếu một siêu dữ liệu triển khai
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6383, Liên minh có thể ghi đè lên 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'] --> 625
See also
PEP 604 – PEP đề xuất cú pháp
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6373 và kiểu Union
Mới trong phiên bản 3. 10
Các loại tích hợp khác
Trình thông dịch hỗ trợ một số loại đối tượng khác. Hầu hết trong số này chỉ hỗ trợ một hoặc hai thao tác
mô-đun
The only special operation on a module is attribute access.
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6387, where m is a module and name accesses a name defined in m’s symbol table. Thuộc tính mô-đun có thể được gán cho. [Lưu ý rằng câu lệnh, nói đúng ra, không phải là một thao tác trên một đối tượng mô-đun;
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6389 không yêu cầu một đối tượng mô-đun có tên foo tồn tại, thay vào đó, nó yêu cầu một định nghĩa [bên ngoài] cho một mô-đun có tên foo ở đâu đó. ]
Một thuộc tính đặc biệt của mỗi mô-đun là. Đây là từ điển chứa bảng ký hiệu của module. Sửa đổi từ điển này sẽ thực sự thay đổi bảng ký hiệu của mô-đun, nhưng không thể gán trực tiếp cho thuộc tính [bạn có thể viế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'] --> 6392, định 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'] --> 6393 là ________0____55, nhưng bạn không thể viế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'] --> 6395]. Sửa đổi trực tiếp không được khuyến khích
Các mô-đun được tích hợp trong trình thông dịch được viết như thế này.
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6397. Nếu được tải từ một tệp, chúng được viết là
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6398
Các lớp và trường hợp lớp
Xem và cho những
Chức năng
Các đối tượng hàm được tạo bởi các định nghĩa hàm. Thao tác duy nhất trên một đối tượng hàm là gọi nó.
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6399
Thực sự có hai hương vị của các đối tượng chức năng. chức năng tích hợp và chức năng do người dùng định nghĩa. Cả hai đều hỗ trợ cùng một thao tác [để gọi hàm], nhưng cách thực hiện khác nhau, do đó các loại đối tượng khác nhau
Xem để biết thêm thông tin
phương pháp
Methods are functions that are called using the attribute notation. Có hai hương vị. các phương thức tích hợp sẵn [chẳng hạn như
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6400 trong danh sách] và các phương thức thể hiện của lớp. Các phương thức tích hợp được mô tả với các loại hỗ trợ chúng
Nếu bạn truy cập một phương thức [một hàm được xác định trong không gian tên lớp] thông qua một thể hiện, bạn sẽ nhận được một đối tượng đặc biệt. một đối tượng phương thức ràng buộc [còn gọi là phương thức thể hiện]. Khi được gọi, nó sẽ thêm đối số
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6401 vào danh sách đối số. Các phương thức ràng buộc có hai thuộc tính chỉ đọc đặc biệ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'] --> 6402 là đối tượng mà phương thức hoạt động 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'] --> 6403 là hàm thực thi phương thức. Gọi
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6404 hoàn toàn tương đương với gọi
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6405
Giống như các đối tượng hàm, các đối tượng phương thức ràng buộc hỗ trợ nhận các thuộc tính tùy ý. Tuy nhiên, vì các thuộc tính của phương thức thực sự được lưu trữ trên đối tượng chức năng bên dướ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'] --> 6406], nên việc đặt các thuộc tính của phương thức trên các phương thức bị ràng buộc là không được phép. Cố gắng đặt một thuộc tính trên một phương thức dẫn đến việc tăng. In order to set a method attribute, you need to explicitly set it on the underlying function object
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 626
Xem để biết thêm thông tin
Code Objects
Code objects are used by the implementation to represent “pseudo-compiled” executable Python code such as a function body. They differ from function objects because they don’t contain a reference to their global execution environment. Code objects are returned by the built-in function and can be extracted from function objects through their
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6409 attribute. See also the module
Accessing
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6409 raises an
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6412 with arguments
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6413 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'] --> 6414
A code object can be executed or evaluated by passing it [instead of a source string] to the or built-in functions
Xem để biết thêm thông tin
Type Objects
Loại đối tượng đại diện cho các loại đối tượng khác nhau. Loại đối tượng được truy cập bởi chức năng tích hợp. Không có thao tác đặc biệt nào trên các loại. Mô-đun tiêu chuẩn xác định tên cho tất cả các loại tích hợp tiêu chuẩn
Các loại được viết như thế này. ______________419
Đối tượng Null
Đối tượng này được trả về bởi các hàm không trả về giá trị một cách rõ ràng. Nó không hỗ trợ các hoạt động đặc biệt. Có chính xác một đối tượng null, tên là
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 631 [tên dựng sẵ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'] --> 6421 produces the same singleton
Nó được viết là
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 631
Đối tượng Dấu chấm lửng
Đối tượng này thường được sử dụng bằng cách cắt lát [xem ]. Nó không hỗ trợ các hoạt động đặc biệt. Có chính xác một đối tượng dấu chấm lửng, được đặt tên [tên tích hợ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'] --> 6424 sản xuất singleton
Nó được viết là
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6423 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'] --> 6427
Đối tượng không được triển khai
Đối tượng này được trả về từ phép so sánh và phép toán nhị phân khi chúng được yêu cầu thao tác trên các loại mà chúng không hỗ trợ. Xem để biết thêm thông tin. Có chính xác 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'] --> 6428.
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6429 tạo ra cá thể đơn lẻ
Nó được viết là
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6428
Giá trị Boolean
Giá trị Boolean là hai đối tượng hằng 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'] --> 638 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. Chúng được sử dụng để biểu thị giá trị thật [mặc dù các giá trị khác cũng có thể được coi là sai hoặc đúng]. Trong ngữ cảnh số [ví dụ: khi được sử dụng làm đối số cho toán tử số học], chúng hoạt động giống như các số nguyên 0 và 1 tương ứng. Hàm tích hợp có thể được sử dụng để chuyển đổi bất kỳ giá trị nào thành Boolean, nếu giá trị đó có thể được hiểu là giá trị thực [xem phần ở trên]
Chúng được viết lần lượt là
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 638 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
Đối tượng bên trong
See for this information. It describes stack frame objects, traceback objects, and slice objects
Thuộc tính đặc biệt
Việc triển khai thêm một vài thuộc tính chỉ đọc đặc biệt cho một số loại đối tượng, nơi chúng có liên quan. Một số trong số này không được báo cáo bởi chức năng tích hợp
đối tượng. __dict__Từ điển hoặc đối tượng ánh xạ khác được sử dụng để lưu trữ các thuộc tính [có thể ghi] của đối tượng
ví dụ. __class__Lớp mà một thể hiện của lớp thuộc về
lớp. __base__Bộ các lớp cơ sở của một đối tượng lớp
định nghĩa. __name__Tên của lớp, hàm, phương thức, bộ mô tả hoặc thể hiện của trình tạo
định nghĩa. __tên_số__Thể hiện của lớp, hàm, phương thức, bộ mô tả hoặc trình tạo
New in version 3. 3
lớp. __mro__Thuộc tính này là một bộ các lớp được xem xét khi tìm kiếm các lớp cơ sở trong quá trình phân giải phương thức
lớp. mro[]Phương thức này có thể được ghi đè bởi một siêu dữ liệu để tùy chỉnh thứ tự phân giải phương thức cho các phiên bản của nó. Nó được gọi khi khởi tạo lớp và kết quả của nó được lưu trữ trong
lớp. __phân lớp__[]Mỗi lớp giữ một danh sách các tham chiếu yếu đến các lớp con trực tiếp của nó. Phương thức này trả về một danh sách tất cả các tham chiếu vẫn còn tồn tại. Danh sách theo thứ tự định nghĩa. Thí dụ
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 627
Giới hạn độ dài chuyển đổi chuỗi số nguyên
CPython có giới hạn toàn cầu để chuyển đổi giữa và để giảm thiểu các cuộc tấn công từ chối dịch vụ. Giới hạn này chỉ áp dụng cho cơ số thập phân hoặc cơ số không phải lũy thừa hai. Chuyển đổi thập lục phân, bát phân và nhị phân là không giới hạn. Giới hạn có thể được cấu hình
Loại trong Python là một số có độ dài tùy ý được lưu trữ ở dạng nhị phân [thường được gọi là “bignum”]. There exists no algorithm that can convert a string to a binary integer or a binary integer to a string in linear time, unless the base is a power of 2. Ngay cả các thuật toán được biết đến nhiều nhất cho cơ số 10 cũng có độ phức tạp bậc hai. Chuyển đổi một giá trị lớn chẳng hạn như
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6441 có thể mất hơn một giây trên CPU nhanh
Giới hạn kích thước chuyển đổi cung cấp một cách thiết thực để tránh CVE-2020-10735
Giới hạn được áp dụng cho số ký tự chữ số trong chuỗi đầu vào hoặc đầu ra khi sử dụng thuật toán chuyển đổi phi tuyến tính. Dấu gạch dưới và dấu không được tính vào giới hạn
Khi một hoạt động sẽ vượt quá giới hạn, a được nâng lên
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 628
Giới hạn mặc định là 4300 chữ số như được cung cấp trong. Giới hạn thấp nhất có thể được cấu hình là 640 chữ số như được cung cấp trong
xác minh
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 629
Mới trong phiên bản 3. 11
API bị ảnh hưởng
Giới hạn chỉ áp dụng cho các chuyển đổi có khả năng chậm giữa và 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'] --> 6
448 với cơ số mặc định là 10def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
449 cho tất cả các cơ số không phải là lũy thừa của 2def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
450def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
451any other string conversion to base 10, for example
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
452,def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
453, ordef bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
454
Các giới hạn không áp dụng cho các hàm có thuật toán tuyến tí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'] --> 6
449 với cơ số 2, 4, 8, 16 hoặc 32Và
, ,
cho các số hex, bát phân và nhị phân
đến
đến
Định cấu hình giới hạn
Trước khi Python khởi động, bạn có thể sử dụng biến môi trường hoặc cờ dòng lệnh của trình thông dịch để định cấu hình giới hạn
, e. g.
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
466 để đặt giới hạn thành 640 hoặcdef bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
467 để tắt giới hạn, e. g.
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
469def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
470 chứa giá trị của hoặc. Nếu cả env var và tùy chọndef bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
473 đều được đặt, thì tùy chọndef bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6
473 sẽ được ưu tiên. Giá trị -1 cho biết rằng cả hai đều không được đặt, do đó, giá trị ____0_______443 đã được sử dụng trong quá trình khởi tạo
Từ mã, bạn có thể kiểm tra giới hạn hiện tại và đặt giới hạn mới bằng các API này
và là một getter và setter cho giới hạn trên toàn trình thông dịch. Phiên dịch viên phụ có giới hạn riêng của họ
Thông tin về mặc định và tối thiểu có thể được tìm thấy trong
is the compiled-in default limit
là giá trị thấp nhất được chấp nhận cho giới hạn [khác 0 sẽ vô hiệu hóa giới hạn đó]
Mới trong phiên bản 3. 11
thận trọng
Đặt giới hạn thấp có thể dẫn đến sự cố. Mặc dù hiếm gặp, mã tồn tại chứa các hằng số nguyên ở dạng thập phân trong nguồn của chúng vượt quá ngưỡng tối thiểu. Hậu quả của việc đặt giới hạn là mã nguồn Python chứa các số nguyên thập phân dài hơn giới hạn sẽ gặp lỗi trong quá trình phân tích cú pháp, thường là tại thời điểm khởi động hoặc thời điểm nhập hoặc thậm chí tại thời điểm cài đặt - bất kỳ lúc nào bản cập nhậ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'] --> 6482 chưa tồn tại cho . Một giải pháp thay thế cho nguồn chứa các hằng số lớn như vậy là chuyển đổi chúng sang dạng thập lục phân
def bit_count[self]: return bin[self].count["1"]12 vì nó không có giới hạn
Kiểm tra ứng dụng của bạn kỹ lưỡng nếu bạn sử dụng giới hạn thấp. Đảm bảo các thử nghiệm của bạn chạy với giới hạn được đặt sớm thông qua môi trường hoặc cờ để nó áp dụng trong quá trình khởi động và thậm chí trong bất kỳ bước cài đặt nào có thể gọi Python để biên dịch trước các nguồ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'] --> 6484 thành tệ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'] --> 6482
Cấu hình đề xuất
Giá trị mặc định
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 6443 dự kiến sẽ hợp lý cho hầu hết các ứng dụng. Nếu ứng dụng của bạn yêu cầu một giới hạn khác, hãy đặt giới hạn đó từ điểm vào chính của bạn bằng cách sử dụng mã bất khả tri của phiên bản Python vì các API này đã được thêm vào trong các bản phát hành bản vá bảo mật trong các phiên bản trước 3. 11
Example
def bit_length[self]: s = bin[self] # binary representation: bin[-37] --> '-0b100101' s = s.lstrip['-0b'] # remove leading zeros and minus sign return len[s] # len['100101'] --> 630
Nếu bạn cần tắt hoàn toàn, hãy đặt 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'] --> 642
chú thích
Thông tin bổ sung về các phương pháp đặc biệt này có thể được tìm thấy trong Python Reference Manual []
Kết quả là, danh sá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'] --> 6488 được coi là bằ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'] --> 6489, và tương tự đối với các bộ dữ liệu
Chúng phải có vì trình phân tích cú pháp không thể cho biết loại toán hạng
4[,,,]Các ký tự viết hoa là những ký tự có thuộc tính danh mục chung là một trong số “Lu” [Chữ cái, chữ hoa], “Ll” [Chữ cái, chữ thường] hoặc “Lt” [Chữ cái, chữ hoa tiêu đề]
5[,]Do đó, để chỉ định dạng một bộ dữ liệu, bạn nên cung cấp một bộ dữ liệu đơn có phần tử duy nhất là bộ dữ liệu được định dạng