Hướng dẫn string function in python 3 - hàm chuỗi trong python 3
Python có một bộ các phương thức tích hợp mà bạn có thể sử dụng trên các chuỗi. Show Lưu ý: Tất cả các phương thức chuỗi trả về các giá trị mới. Họ không thay đổi chuỗi ban đầu. All string methods returns new values. They do not change the original string.
Lưu ý: Tất cả các phương thức chuỗi trả về các giá trị mới. Họ không thay đổi chuỗi ban đầu. All string methods returns new values. They do not change the original string. Chia chuỗi ở mức độ ngắt dòng và trả về danh sách Mã nguồn: lib/string.py Lib/string.py Chuỗi hằng số lorCác hằng số được xác định trong mô -đun này là: ________ 17 ________ 18¶Sự kết hợp của hằng số "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.9 và "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first0 được mô tả dưới đây. Giá trị này không phụ thuộc vào địa phương. ________ 17 ________ 22¶ Các chữ cái chữ thường "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first3. Giá trị này không phụ thuộc vào địa phương và sẽ không thay đổi. ________ 17 ________ 25¶ Các chữ cái viết hoa "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first6. Giá trị này không phụ thuộc vào địa phương và sẽ không thay đổi. ________ 17 ________ 28¶ Chuỗi "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first9. ________ 17 ________ 31¶ Chuỗi format_spec ::= [[2. ________ 17 ________ 34¶ Chuỗi format_spec ::= [[5. ________ 17 ________ 37¶ Chuỗi các ký tự ASCII được coi là ký tự chấm câu trong ngôn ngữ format_spec ::= [[8: format_spec ::= [[9. ________ 17 ________ 41¶ Chuỗi các ký tự ASCII được coi là có thể in. Đây là sự kết hợp của >>> '{0}, {1}, {2}'.format('a', 'b', 'c') 'a, b, c' >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only 'a, b, c' >>> '{2}, {1}, {0}'.format('a', 'b', 'c') 'c, b, a' >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence 'c, b, a' >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated 'abracadabra'2, >>> '{0}, {1}, {2}'.format('a', 'b', 'c') 'a, b, c' >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only 'a, b, c' >>> '{2}, {1}, {0}'.format('a', 'b', 'c') 'c, b, a' >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence 'c, b, a' >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated 'abracadabra'3, >>> '{0}, {1}, {2}'.format('a', 'b', 'c') 'a, b, c' >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only 'a, b, c' >>> '{2}, {1}, {0}'.format('a', 'b', 'c') 'c, b, a' >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence 'c, b, a' >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated 'abracadabra'4 và >>> '{0}, {1}, {2}'.format('a', 'b', 'c') 'a, b, c' >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only 'a, b, c' >>> '{2}, {1}, {0}'.format('a', 'b', 'c') 'c, b, a' >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence 'c, b, a' >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated 'abracadabra'5. ________ 17 ________ 47¶ Một chuỗi chứa tất cả các ký tự ASCII được coi là khoảng trắng. Điều này bao gồm không gian ký tự, tab, linefeed, return, formFeed và tab dọc. Định dạng chuỗi tùy chỉnhLớp chuỗi tích hợp cung cấp khả năng thực hiện các thay thế biến đổi phức tạp và định dạng giá trị thông qua phương thức >>> '{0}, {1}, {2}'.format('a', 'b', 'c') 'a, b, c' >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only 'a, b, c' >>> '{2}, {1}, {0}'.format('a', 'b', 'c') 'c, b, a' >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence 'c, b, a' >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated 'abracadabra'8 được mô tả trong PEP 3101. Lớp >>> '{0}, {1}, {2}'.format('a', 'b', 'c') 'a, b, c' >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only 'a, b, c' >>> '{2}, {1}, {0}'.format('a', 'b', 'c') 'c, b, a' >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence 'c, b, a' >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated 'abracadabra'9 trong mô-đun >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W') 'Coordinates: 37.24N, -115.81W' >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'} >>> 'Coordinates: {latitude}, {longitude}'.format(**coord) 'Coordinates: 37.24N, -115.81W'0 cho phép bạn tạo và tùy chỉnh các hành vi định dạng chuỗi của riêng bạn Phương pháp >>> '{0}, {1}, {2}'.format('a', 'b', 'c') 'a, b, c' >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only 'a, b, c' >>> '{2}, {1}, {0}'.format('a', 'b', 'c') 'c, b, a' >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence 'c, b, a' >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated 'abracadabra'8 tích hợp.PEP 3101. The >>> '{0}, {1}, {2}'.format('a', 'b', 'c') 'a, b, c' >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only 'a, b, c' >>> '{2}, {1}, {0}'.format('a', 'b', 'c') 'c, b, a' >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence 'c, b, a' >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated 'abracadabra'9 class in the >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W') 'Coordinates: 37.24N, -115.81W' >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'} >>> 'Coordinates: {latitude}, {longitude}'.format(**coord) 'Coordinates: 37.24N, -115.81W'0 module allows you to create and customize your own string formatting behaviors using the same implementation as the built-in >>> '{0}, {1}, {2}'.format('a', 'b', 'c') 'a, b, c' >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only 'a, b, c' >>> '{2}, {1}, {0}'.format('a', 'b', 'c') 'c, b, a' >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence 'c, b, a' >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated 'abracadabra'8 method. Lớp ________ 17 ________ 53¶ Lớp >>> '{0}, {1}, {2}'.format('a', 'b', 'c') 'a, b, c' >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only 'a, b, c' >>> '{2}, {1}, {0}'.format('a', 'b', 'c') 'c, b, a' >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence 'c, b, a' >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated 'abracadabra'9 có các phương thức công khai sau: ________ 55 (Format_String, /, *args, ** kwargs) ¶(format_string, /, *args, **kwargs)¶ Phương pháp API chính. Nó lấy một chuỗi định dạng và một tập hợp các đối số từ khóa và vị trí tùy ý. Nó chỉ là một trình bao bọc mà gọi >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W') 'Coordinates: 37.24N, -115.81W' >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'} >>> 'Coordinates: {latitude}, {longitude}'.format(**coord) 'Coordinates: 37.24N, -115.81W'6. Đã thay đổi trong phiên bản 3.7: Đối số chuỗi định dạng hiện chỉ có vị trí.A format string argument is now positional-only. ________ 57 (format_string, args, kwargs) ¶(format_string, args, kwargs)¶Chức năng này thực hiện công việc thực tế của định dạng. Nó được phơi bày như một chức năng riêng biệt cho các trường hợp bạn muốn truyền trong một từ điển được xác định trước về các đối số, thay vì giải nén và đóng gói từ điển làm đối số riêng lẻ bằng cách sử dụng cú pháp >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W') 'Coordinates: 37.24N, -115.81W' >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'} >>> 'Coordinates: {latitude}, {longitude}'.format(**coord) 'Coordinates: 37.24N, -115.81W'8 và >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W') 'Coordinates: 37.24N, -115.81W' >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'} >>> 'Coordinates: {latitude}, {longitude}'.format(**coord) 'Coordinates: 37.24N, -115.81W'9. >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W') 'Coordinates: 37.24N, -115.81W' >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'} >>> 'Coordinates: {latitude}, {longitude}'.format(**coord) 'Coordinates: 37.24N, -115.81W'6 thực hiện công việc phá vỡ chuỗi định dạng thành dữ liệu ký tự và các trường thay thế. Nó gọi các phương pháp khác nhau được mô tả dưới đây. Ngoài ra, >>> '{0}, {1}, {2}'.format('a', 'b', 'c') 'a, b, c' >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only 'a, b, c' >>> '{2}, {1}, {0}'.format('a', 'b', 'c') 'c, b, a' >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence 'c, b, a' >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated 'abracadabra'9 xác định một số phương thức được dự định sẽ được thay thế bằng các lớp con: ________ 62 (Format_String) ¶(format_string)¶ Vòng lặp qua định dạng_string và trả về một bộ dữ liệu (literal_text, field_name, format_spec, chuyển đổi). Điều này được sử dụng bởi >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W') 'Coordinates: 37.24N, -115.81W' >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'} >>> 'Coordinates: {latitude}, {longitude}'.format(**coord) 'Coordinates: 37.24N, -115.81W'6 để chia chuỗi thành văn bản theo nghĩa đen hoặc các trường thay thế. Các giá trị trong tuple về mặt khái niệm đại diện cho một nhịp của văn bản theo nghĩa đen theo sau là một trường thay thế duy nhất. Nếu không có văn bản theo nghĩa đen (có thể xảy ra nếu hai trường thay thế xảy ra liên tiếp), thì literal_text sẽ là một chuỗi có độ dài bằng không. Nếu không có trường thay thế, thì các giá trị của field_name, format_spec và chuyển đổi sẽ là >>> c = 3-5j >>> ('The complex number {0} is formed from the real part {0.real} ' ... 'and the imaginary part {0.imag}.').format(c) 'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.' >>> class Point: ... def __init__(self, x, y): ... self.x, self.y = x, y ... def __str__(self): ... return 'Point({self.x}, {self.y})'.format(self=self) ... >>> str(Point(4, 2)) 'Point(4, 2)'4. ________ 65 (field_name, args, kwargs) ¶(field_name, args, kwargs)¶ Cho field_name được trả về bởi >>> c = 3-5j >>> ('The complex number {0} is formed from the real part {0.real} ' ... 'and the imaginary part {0.imag}.').format(c) 'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.' >>> class Point: ... def __init__(self, x, y): ... self.x, self.y = x, y ... def __str__(self): ... return 'Point({self.x}, {self.y})'.format(self=self) ... >>> str(Point(4, 2)) 'Point(4, 2)'6 (xem ở trên), chuyển đổi nó thành một đối tượng được định dạng. Trả về một tuple (obj, used_key). Phiên bản mặc định có các chuỗi của biểu mẫu được xác định trong PEP 3101, chẳng hạn như là 0 [tên] Args và kwargs được truyền vào >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W') 'Coordinates: 37.24N, -115.81W' >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'} >>> 'Coordinates: {latitude}, {longitude}'.format(**coord) 'Coordinates: 37.24N, -115.81W'6. Giá trị trả về đã sử dụng_key có cùng ý nghĩa với tham số chính với >>> c = 3-5j >>> ('The complex number {0} is formed from the real part {0.real} ' ... 'and the imaginary part {0.imag}.').format(c) 'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.' >>> class Point: ... def __init__(self, x, y): ... self.x, self.y = x, y ... def __str__(self): ... return 'Point({self.x}, {self.y})'.format(self=self) ... >>> str(Point(4, 2)) 'Point(4, 2)'8.PEP 3101, such as “0[name]” or “label.title”. args and kwargs are as passed in to >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W') 'Coordinates: 37.24N, -115.81W' >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'} >>> 'Coordinates: {latitude}, {longitude}'.format(**coord) 'Coordinates: 37.24N, -115.81W'6. The return value used_key has the same meaning as the key parameter to >>> c = 3-5j >>> ('The complex number {0} is formed from the real part {0.real} ' ... 'and the imaginary part {0.imag}.').format(c) 'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.' >>> class Point: ... def __init__(self, x, y): ... self.x, self.y = x, y ... def __str__(self): ... return 'Point({self.x}, {self.y})'.format(self=self) ... >>> str(Point(4, 2)) 'Point(4, 2)'8. ________ 69 (khóa, args, kwargs) ¶(key, args, kwargs)¶ Lấy một giá trị trường đã cho. Đối số chính sẽ là một số nguyên hoặc một chuỗi. Nếu nó là một số nguyên, nó đại diện cho chỉ số của đối số vị trí trong Args; Nếu đó là một chuỗi, thì nó đại diện cho một đối số được đặt tên trong kwargs. Tham số ARGS được đặt thành danh sách các đối số vị trí thành >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W') 'Coordinates: 37.24N, -115.81W' >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'} >>> 'Coordinates: {latitude}, {longitude}'.format(**coord) 'Coordinates: 37.24N, -115.81W'6 và tham số KWARGS được đặt thành từ điển của các đối số từ khóa. Đối với tên trường ghép, các chức năng này chỉ được gọi cho thành phần đầu tiên của tên trường; Các thành phần tiếp theo được xử lý thông qua các hoạt động thuộc tính và lập chỉ mục thông thường. Vì vậy, ví dụ, biểu thức trường ‘0.Name, sẽ khiến >>> c = 3-5j >>> ('The complex number {0} is formed from the real part {0.real} ' ... 'and the imaginary part {0.imag}.').format(c) 'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.' >>> class Point: ... def __init__(self, x, y): ... self.x, self.y = x, y ... def __str__(self): ... return 'Point({self.x}, {self.y})'.format(self=self) ... >>> str(Point(4, 2)) 'Point(4, 2)'8 được gọi bằng đối số chính là 0. Thuộc tính >>> coord = (3, 5) >>> 'X: {0[0]}; Y: {0[1]}'.format(coord) 'X: 3; Y: 5'2 sẽ được tra cứu sau khi trả về >>> c = 3-5j >>> ('The complex number {0} is formed from the real part {0.real} ' ... 'and the imaginary part {0.imag}.').format(c) 'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.' >>> class Point: ... def __init__(self, x, y): ... self.x, self.y = x, y ... def __str__(self): ... return 'Point({self.x}, {self.y})'.format(self=self) ... >>> str(Point(4, 2)) 'Point(4, 2)'8 bằng cách gọi hàm >>> coord = (3, 5) >>> 'X: {0[0]}; Y: {0[1]}'.format(coord) 'X: 3; Y: 5'4 tích hợp. Nếu chỉ mục hoặc từ khóa đề cập đến một mục không tồn tại, thì nên nâng cao >>> coord = (3, 5) >>> 'X: {0[0]}; Y: {0[1]}'.format(coord) 'X: 3; Y: 5'5 hoặc >>> coord = (3, 5) >>> 'X: {0[0]}; Y: {0[1]}'.format(coord) 'X: 3; Y: 5'6. ________ 77 (used_args, args, kwargs) ¶(used_args, args, kwargs)¶ Thực hiện kiểm tra các đối số không sử dụng nếu muốn. Các đối số cho hàm này là tập hợp tất cả các khóa đối số thực sự được đề cập trong chuỗi định dạng (số nguyên cho các đối số vị trí và các chuỗi cho các đối số được đặt tên) và tham chiếu đến ARGS và KWARGS được truyền cho VFormat. Tập hợp các arg không sử dụng có thể được tính từ các tham số này. >>> coord = (3, 5) >>> 'X: {0[0]}; Y: {0[1]}'.format(coord) 'X: 3; Y: 5'8 được giả định để tăng một ngoại lệ nếu kiểm tra không thành công. ________ 79 (giá trị, format_spec) ¶(value, format_spec)¶ >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2') "repr() shows quotes: 'test1'; str() doesn't: test2"0 chỉ đơn giản gọi là toàn cầu >>> '{0}, {1}, {2}'.format('a', 'b', 'c') 'a, b, c' >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only 'a, b, c' >>> '{2}, {1}, {0}'.format('a', 'b', 'c') 'c, b, a' >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence 'c, b, a' >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated 'abracadabra'8 tích hợp. Phương pháp được cung cấp để các lớp con có thể ghi đè nó. ________ 82 (giá trị, chuyển đổi) ¶(value, conversion)¶ Chuyển đổi giá trị (được trả về bởi >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2') "repr() shows quotes: 'test1'; str() doesn't: test2"3) được đưa ra một loại chuyển đổi (như trong bộ tuple được trả về bằng phương pháp >>> c = 3-5j >>> ('The complex number {0} is formed from the real part {0.real} ' ... 'and the imaginary part {0.imag}.').format(c) 'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.' >>> class Point: ... def __init__(self, x, y): ... self.x, self.y = x, y ... def __str__(self): ... return 'Point({self.x}, {self.y})'.format(self=self) ... >>> str(Point(4, 2)) 'Point(4, 2)'6). Phiên bản mặc định hiểu các loại chuyển đổi (STR), ‘R, (repr) và‘ A (ASCII). Định dạng Chuỗi Cú phápPhương pháp >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2') "repr() shows quotes: 'test1'; str() doesn't: test2"5 và lớp >>> '{0}, {1}, {2}'.format('a', 'b', 'c') 'a, b, c' >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only 'a, b, c' >>> '{2}, {1}, {0}'.format('a', 'b', 'c') 'c, b, a' >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence 'c, b, a' >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated 'abracadabra'9 có chung cú pháp cho các chuỗi định dạng (mặc dù trong trường hợp >>> '{0}, {1}, {2}'.format('a', 'b', 'c') 'a, b, c' >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only 'a, b, c' >>> '{2}, {1}, {0}'.format('a', 'b', 'c') 'c, b, a' >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence 'c, b, a' >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated 'abracadabra'9, các lớp con có thể xác định cú pháp chuỗi định dạng của riêng chúng). Cú pháp có liên quan đến các chữ viết được định dạng, nhưng nó kém tinh vi hơn và đặc biệt, không hỗ trợ các biểu thức tùy ý.formatted string literals, but it is less sophisticated and, in particular, does not support arbitrary expressions. Các chuỗi định dạng có chứa các trường thay thế trên mạng, được bao quanh bởi niềng răng xoăn >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2') "repr() shows quotes: 'test1'; str() doesn't: test2"8. Bất cứ điều gì không chứa trong niềng răng đều được coi là văn bản theo nghĩa đen, được sao chép không thay đổi với đầu ra. Nếu bạn cần bao gồm một ký tự nẹp trong văn bản theo nghĩa đen, nó có thể được thoát ra bằng cách nhân đôi: >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2') "repr() shows quotes: 'test1'; str() doesn't: test2"9 và >>> '{:<30}'.format('left aligned') 'left aligned ' >>> '{:>30}'.format('right aligned') ' right aligned' >>> '{:^30}'.format('centered') ' centered ' >>> '{:*^30}'.format('centered') # use '*' as a fill char '***********centered***********'0. Ngữ pháp cho một trường thay thế như sau: replacement_field ::= "{" [ Trong các thuật ngữ ít chính thức hơn, trường thay thế có thể bắt đầu bằng một field_name chỉ định đối tượng có giá trị được định dạng và chèn vào đầu ra thay vì trường thay thế. Field_name được tùy chọn theo sau bởi một trường chuyển đổi, được đi trước bởi một dấu chấm than >>> '{:<30}'.format('left aligned') 'left aligned ' >>> '{:>30}'.format('right aligned') ' right aligned' >>> '{:^30}'.format('centered') ' centered ' >>> '{:*^30}'.format('centered') # use '*' as a fill char '***********centered***********'1 và một định dạng_spec, được đi trước bởi một đại tràng >>> '{:<30}'.format('left aligned') 'left aligned ' >>> '{:>30}'.format('right aligned') ' right aligned' >>> '{:^30}'.format('centered') ' centered ' >>> '{:*^30}'.format('centered') # use '*' as a fill char '***********centered***********'2. Chúng chỉ định một định dạng không mặc định cho giá trị thay thế. Xem thêm phần Đặc tả định dạng Mini-Language.Format Specification Mini-Language section. Field_name bắt đầu bằng một arg_name là số hoặc từ khóa. Nếu nó có một số, nó đề cập đến một đối số vị trí và nếu nó là một từ khóa, nó sẽ đề cập đến một đối số từ khóa được đặt tên. Nếu arg_names số trong chuỗi định dạng là 0, 1, 2, theo trình tự, tất cả chúng đều có thể bị bỏ qua (không chỉ một số) và các số 0, 1, 2, sẽ được tự động chèn theo thứ tự đó. Vì arg_name không được trích dẫn, nên không thể chỉ định các khóa từ điển tùy ý (ví dụ: chuỗi >>> '{:<30}'.format('left aligned') 'left aligned ' >>> '{:>30}'.format('right aligned') ' right aligned' >>> '{:^30}'.format('centered') ' centered ' >>> '{:*^30}'.format('centered') # use '*' as a fill char '***********centered***********'3 hoặc >>> '{:<30}'.format('left aligned') 'left aligned ' >>> '{:>30}'.format('right aligned') ' right aligned' >>> '{:^30}'.format('centered') ' centered ' >>> '{:*^30}'.format('centered') # use '*' as a fill char '***********centered***********'4) trong chuỗi định dạng. ARG_NAME có thể được theo sau bởi bất kỳ số lượng biểu thức chỉ mục hoặc thuộc tính nào. Một biểu thức của Mẫu >>> '{:<30}'.format('left aligned') 'left aligned ' >>> '{:>30}'.format('right aligned') ' right aligned' >>> '{:^30}'.format('centered') ' centered ' >>> '{:*^30}'.format('centered') # use '*' as a fill char '***********centered***********'5 chọn thuộc tính được đặt tên bằng cách sử dụng >>> coord = (3, 5) >>> 'X: {0[0]}; Y: {0[1]}'.format(coord) 'X: 3; Y: 5'4, trong khi biểu thức của Mẫu >>> '{:<30}'.format('left aligned') 'left aligned ' >>> '{:>30}'.format('right aligned') ' right aligned' >>> '{:^30}'.format('centered') ' centered ' >>> '{:*^30}'.format('centered') # use '*' as a fill char '***********centered***********'7 thực hiện tra cứu chỉ mục bằng cách sử dụng >>> '{:<30}'.format('left aligned') 'left aligned ' >>> '{:>30}'.format('right aligned') ' right aligned' >>> '{:^30}'.format('centered') ' centered ' >>> '{:*^30}'.format('centered') # use '*' as a fill char '***********centered***********'8. Đã thay đổi trong phiên bản 3.1: Các nhà xác định đối số vị trí có thể được bỏ qua cho >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2') "repr() shows quotes: 'test1'; str() doesn't: test2"5, so "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.00 is equivalent to "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.01. Đã thay đổi trong phiên bản 3.4: Các nhà xác định đối số vị trí có thể được bỏ qua cho >>> '{0}, {1}, {2}'.format('a', 'b', 'c') 'a, b, c' >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only 'a, b, c' >>> '{2}, {1}, {0}'.format('a', 'b', 'c') 'c, b, a' >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence 'c, b, a' >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated 'abracadabra'9. Một số ví dụ chuỗi định dạng đơn giản: "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'. Trường chuyển đổi gây ra sự ép buộc loại trước khi định dạng. Thông thường, công việc định dạng một giá trị được thực hiện bằng phương thức "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.03 của chính giá trị. Tuy nhiên, trong một số trường hợp, mong muốn buộc một loại được định dạng thành một chuỗi, ghi đè lên định nghĩa của chính nó về định dạng. Bằng cách chuyển đổi giá trị thành một chuỗi trước khi gọi "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.03, logic định dạng thông thường được bỏ qua. Ba cờ chuyển đổi hiện đang được hỗ trợ: "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.05 gọi "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.06 trên giá trị, "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.07 gọi "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.08 và "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.09 gọi "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.10. Vài ví dụ: "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first Trường định dạng_spec chứa một đặc điểm kỹ thuật về cách trình bày giá trị, bao gồm các chi tiết như chiều rộng trường, căn chỉnh, đệm, độ chính xác thập phân, v.v. Mỗi loại giá trị có thể xác định định dạng ngôn ngữ nhỏ của riêng mình hoặc giải thích định dạng_spec. Hầu hết các loại tích hợp hỗ trợ một ngôn ngữ mini định dạng phổ biến, được mô tả trong phần tiếp theo. Trường định dạng_spec cũng có thể bao gồm các trường thay thế lồng nhau trong đó. Các trường thay thế lồng nhau này có thể chứa một tên trường, cờ chuyển đổi và đặc tả định dạng, nhưng không được phép làm tổ sâu hơn. Các trường thay thế trong định dạng_spec được thay thế trước khi chuỗi định dạng_spec được giải thích. Điều này cho phép định dạng của một giá trị được chỉ định động. Xem phần Ví dụ định dạng cho một số ví dụ.Format examples section for some examples. Đặc điểm kỹ thuật về định dạng Mini-Language¶Thông số kỹ thuật định dạng của Nhật Bản được sử dụng trong các trường thay thế có trong một chuỗi định dạng để xác định cách trình bày các giá trị riêng lẻ (xem Syntax String Syntax và các chuỗi chuỗi được định dạng). Chúng cũng có thể được chuyển trực tiếp đến chức năng >>> '{0}, {1}, {2}'.format('a', 'b', 'c') 'a, b, c' >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only 'a, b, c' >>> '{2}, {1}, {0}'.format('a', 'b', 'c') 'c, b, a' >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence 'c, b, a' >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated 'abracadabra'8 tích hợp. Mỗi loại có thể tạo thành có thể xác định cách giải thích đặc tả định dạng.Format String Syntax and Formatted string literals). They can also be passed directly to the built-in >>> '{0}, {1}, {2}'.format('a', 'b', 'c') 'a, b, c' >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only 'a, b, c' >>> '{2}, {1}, {0}'.format('a', 'b', 'c') 'c, b, a' >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence 'c, b, a' >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated 'abracadabra'8 function. Each formattable type may define how the format specification is to be interpreted. Hầu hết các loại tích hợp thực hiện các tùy chọn sau đây cho các thông số kỹ thuật định dạng, mặc dù một số tùy chọn định dạng chỉ được hỗ trợ bởi các loại số. Một quy ước chung là một đặc tả định dạng trống tạo ra kết quả tương tự như khi bạn đã gọi "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.06 về giá trị. Một đặc tả định dạng không trống thường sửa đổi kết quả. Hình thức chung của trình xác định định dạng tiêu chuẩn là: format_spec ::= [[ Nếu một giá trị căn chỉnh hợp lệ được chỉ định, nó có thể được đi trước bởi một ký tự điền có thể là bất kỳ ký tự và mặc định nào đối với một không gian nếu bị bỏ qua. Không thể sử dụng niềng răng xoăn theo nghĩa đen (____ ____11333 hoặc ____ ____114) làm ký tự điền theo nghĩa đen được định dạng hoặc khi sử dụng phương pháp >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2') "repr() shows quotes: 'test1'; str() doesn't: test2"5. Tuy nhiên, có thể chèn một nẹp xoăn với một trường thay thế lồng nhau. Giới hạn này không ảnh hưởng đến chức năng >>> '{0}, {1}, {2}'.format('a', 'b', 'c') 'a, b, c' >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only 'a, b, c' >>> '{2}, {1}, {0}'.format('a', 'b', 'c') 'c, b, a' >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence 'c, b, a' >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated 'abracadabra'8.formatted string literal or when using the >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2') "repr() shows quotes: 'test1'; str() doesn't: test2"5 method. However, it is possible to insert a curly brace with a nested replacement field. This limitation doesn’t affect the >>> '{0}, {1}, {2}'.format('a', 'b', 'c') 'a, b, c' >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only 'a, b, c' >>> '{2}, {1}, {0}'.format('a', 'b', 'c') 'c, b, a' >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence 'c, b, a' >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated 'abracadabra'8 function. Ý nghĩa của các tùy chọn căn chỉnh khác nhau như sau:
Lưu ý rằng trừ khi chiều rộng trường tối thiểu được xác định, chiều rộng trường sẽ luôn có cùng kích thước với dữ liệu để điền vào nó, do đó tùy chọn căn chỉnh không có ý nghĩa trong trường hợp này. Tùy chọn dấu hiệu chỉ hợp lệ cho các loại số và có thể là một trong những điều sau đây:
Lưu ý rằng trừ khi chiều rộng trường tối thiểu được xác định, chiều rộng trường sẽ luôn có cùng kích thước với dữ liệu để điền vào nó, do đó tùy chọn căn chỉnh không có ý nghĩa trong trường hợp này. Tùy chọn dấu hiệu chỉ hợp lệ cho các loại số và có thể là một trong những điều sau đây: chỉ ra rằng một dấu hiệu nên được sử dụng cho cả số dương cũng như số âm.Added the "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.30 option (see also PEP 378). chỉ ra rằng một dấu hiệu chỉ nên được sử dụng cho các số âm (đây là hành vi mặc định). không gianAdded the "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.33 option (see also PEP 515). chỉ ra rằng một không gian hàng đầu nên được sử dụng trên các số dương và dấu trừ trên các số âm. Khi không có sự liên kết rõ ràng được đưa ra, trước trường chiều rộng bằng ký tự bằng 0 ( "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.40) cho phép nhận biết số không nhận được cho các loại số. Điều này tương đương với ký tự điền của "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.40 với loại căn chỉnh là "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.19. Đã thay đổi trong phiên bản 3.10: Trước trường chiều rộng bằng "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.40 no longer affects the default alignment for strings. Độ chính xác là một số nguyên thập phân cho thấy có bao nhiêu chữ số nên được hiển thị sau điểm thập phân cho các loại trình bày "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.44 và "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.45, hoặc trước và sau điểm thập phân cho các loại trình bày "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.28 hoặc "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.29. Đối với các loại trình bày chuỗi, trường chỉ ra kích thước trường tối đa - nói cách khác, có bao nhiêu ký tự sẽ được sử dụng từ nội dung trường. Độ chính xác không được phép cho các loại trình bày số nguyên. Cuối cùng, loại xác định cách trình bày dữ liệu. Các loại trình bày chuỗi có sẵn là:
Các loại trình bày số nguyên có sẵn là:
Các loại trình bày số nguyên có sẵn là: Định dạng nhị phân. Đầu ra số trong cơ sở 2.
Ví dụ định dạng ¶Phần này chứa các ví dụ về cú pháp >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2') "repr() shows quotes: 'test1'; str() doesn't: test2"5 và so sánh với định dạng ________ 230 cũ. Trong hầu hết các trường hợp, cú pháp tương tự như định dạng ____ 230 cũ, với việc bổ sung >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2') "repr() shows quotes: 'test1'; str() doesn't: test2"8 và với "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first33 được sử dụng thay vì "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first30. Ví dụ, "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first35 có thể được dịch thành "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first36. Cú pháp định dạng mới cũng hỗ trợ các tùy chọn mới và khác nhau, được hiển thị trong các ví dụ sau. Truy cập các đối số theo vị trí: >>> '{0}, {1}, {2}'.format('a', 'b', 'c') 'a, b, c' >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only 'a, b, c' >>> '{2}, {1}, {0}'.format('a', 'b', 'c') 'c, b, a' >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence 'c, b, a' >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated 'abracadabra' Truy cập các đối số theo tên: >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W') 'Coordinates: 37.24N, -115.81W' >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'} >>> 'Coordinates: {latitude}, {longitude}'.format(**coord) 'Coordinates: 37.24N, -115.81W' Truy cập các thuộc tính của đối số: >>> c = 3-5j >>> ('The complex number {0} is formed from the real part {0.real} ' ... 'and the imaginary part {0.imag}.').format(c) 'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.' >>> class Point: ... def __init__(self, x, y): ... self.x, self.y = x, y ... def __str__(self): ... return 'Point({self.x}, {self.y})'.format(self=self) ... >>> str(Point(4, 2)) 'Point(4, 2)' Truy cập các mục đối số của các mục: >>> coord = (3, 5) >>> 'X: {0[0]}; Y: {0[1]}'.format(coord) 'X: 3; Y: 5' Thay thế "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first37 và "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first38: >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2') "repr() shows quotes: 'test1'; str() doesn't: test2" Căn chỉnh văn bản và chỉ định chiều rộng: >>> '{:<30}'.format('left aligned') 'left aligned ' >>> '{:>30}'.format('right aligned') ' right aligned' >>> '{:^30}'.format('centered') ' centered ' >>> '{:*^30}'.format('centered') # use '*' as a fill char '***********centered***********' Thay thế "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first39, "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first40 và "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first41 và chỉ định một dấu hiệu: "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.0 Thay thế "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first42 và "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first43 và chuyển đổi giá trị thành các cơ sở khác nhau: "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.1 Sử dụng dấu phẩy làm dấu phân cách hàng ngàn: "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.2 Thể hiện tỷ lệ phần trăm: "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.3 Sử dụng định dạng cụ thể loại:
"First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.4 Đối số làm tổ và các ví dụ phức tạp hơn: "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.5 Chuỗi mẫuCác chuỗi mẫu cung cấp các thay thế chuỗi đơn giản hơn như được mô tả trong PEP 292. Một trường hợp sử dụng chính cho chuỗi mẫu là để quốc tế hóa (I18N) vì trong bối cảnh đó, cú pháp và chức năng đơn giản hơn giúp dịch dễ dàng hơn các cơ sở định dạng chuỗi tích hợp khác trong Python . Như một ví dụ về thư viện được xây dựng trên chuỗi mẫu cho i18n, hãy xem gói flufl.i18n.PEP 292. A primary use case for template strings is for internationalization (i18n) since in that context, the simpler syntax and functionality makes it easier to translate than other built-in string formatting facilities in Python. As an example of a library built on template strings for i18n, see the flufl.i18n package. Chuỗi mẫu hỗ trợ thay thế dựa trên 244, sử dụng các quy tắc sau:
Bất kỳ sự xuất hiện nào khác của "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first44 trong chuỗi sẽ dẫn đến "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first55 được nâng lên. Mô -đun >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W') 'Coordinates: 37.24N, -115.81W' >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'} >>> 'Coordinates: {latitude}, {longitude}'.format(**coord) 'Coordinates: 37.24N, -115.81W'0 cung cấp một lớp "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first57 thực hiện các quy tắc này. Các phương pháp của "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first57 là: Lớp ________ 17 ________ 260 (Mẫu)(template)¶ Trình xây dựng lấy một đối số duy nhất là chuỗi mẫu. ________ 261 (ánh xạ = {}, /, ** kwds) ¶(mapping={}, /, **kwds)¶Thực hiện thay thế mẫu, trả về một chuỗi mới. Ánh xạ là bất kỳ đối tượng giống như từ điển nào với các khóa phù hợp với trình giữ chỗ trong mẫu. Ngoài ra, bạn có thể cung cấp các đối số từ khóa, trong đó các từ khóa là người giữ chỗ. Khi cả bản đồ và KWD được đưa ra và có những bản sao, các giữ chỗ từ KWD được ưu tiên. ________ 262 (ánh xạ = {}, /, ** kwds) ¶(mapping={}, /, **kwds)¶Giống như "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first63, ngoại trừ nếu người giữ chỗ bị thiếu từ ánh xạ và KWD, thay vì tăng ngoại lệ >>> coord = (3, 5) >>> 'X: {0[0]}; Y: {0[1]}'.format(coord) 'X: 3; Y: 5'6, trình giữ chỗ ban đầu sẽ xuất hiện trong chuỗi kết quả nguyên vẹn. Ngoài ra, không giống như với "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first63, bất kỳ sự xuất hiện nào khác của "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first44 sẽ chỉ đơn giản là trả lại "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first44 thay vì tăng "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first55. Mặc dù các trường hợp ngoại lệ khác vẫn có thể xảy ra, phương pháp này được gọi là an toàn vì nó luôn cố gắng trả về một chuỗi có thể sử dụng thay vì tăng ngoại lệ. Theo một nghĩa khác, "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first69 có thể là bất cứ điều gì khác ngoài an toàn, vì nó sẽ âm thầm bỏ qua các mẫu có hình dạng có chứa các phân định lơ lửng, niềng răng chưa từng có hoặc các trình giữ chỗ không phải là định danh python hợp lệ. Các phiên bản "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first57 cũng cung cấp một thuộc tính dữ liệu công khai: ________ 271¶ Đây là đối tượng được truyền đến đối số mẫu của Constructor. Nói chung, bạn không nên thay đổi nó, nhưng quyền truy cập chỉ đọc không được thực thi. Dưới đây là một ví dụ về cách sử dụng một mẫu: "First, thou shalt count to {0}" # References first positional argument "Bring me a {}" # Implicitly references the first positional argument "From {} to {}" # Same as "From {0} to {1}" "My quest is {name}" # References keyword argument 'name' "Weight in tons {0.weight}" # 'weight' attribute of first positional arg "Units destroyed: {players[0]}" # First element of keyword argument 'players'.6 Sử dụng nâng cao: Bạn có thể lấy các lớp con của "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first57 để tùy chỉnh cú pháp giữ chỗ, ký tự phân cách hoặc toàn bộ biểu thức chính quy được sử dụng để phân tích các chuỗi mẫu. Để làm điều này, bạn có thể ghi đè các thuộc tính lớp này:
Ngoài ra, bạn có thể cung cấp toàn bộ mẫu biểu thức chính quy bằng cách ghi đè mẫu thuộc tính lớp. Nếu bạn làm điều này, giá trị phải là một đối tượng biểu thức chính quy với bốn nhóm chụp được đặt tên. Các nhóm bắt giữ tương ứng với các quy tắc được đưa ra ở trên, cùng với quy tắc giữ chỗ không hợp lệ:
Chức năng của người trợ giúp________ 17 ________ 285 (s, sep = none) ¶(s, sep=None)¶Chia đối số thành các từ bằng cách sử dụng "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first86, viết hoa mỗi từ bằng cách sử dụng "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first87 và tham gia các từ được viết hoa bằng cách sử dụng "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first88. Nếu đối số thứ hai tùy chọn SEP không có hoặc >>> c = 3-5j >>> ('The complex number {0} is formed from the real part {0.real} ' ... 'and the imaginary part {0.imag}.').format(c) 'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.' >>> class Point: ... def __init__(self, x, y): ... self.x, self.y = x, y ... def __str__(self): ... return 'Point({self.x}, {self.y})'.format(self=self) ... >>> str(Point(4, 2)) 'Point(4, 2)'4, thì các ký tự khoảng trắng sẽ được thay thế bằng một không gian duy nhất và khoảng trắng dẫn đầu và dấu vết được loại bỏ, nếu không, SEP được sử dụng để chia và tham gia các từ. |