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.

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.

Phương phápSự mô tả
Viết hoa []Chuyển đổi ký tự đầu tiên thành vỏ trên
CASEPERD []Chuyển đổi chuỗi thành chữ thường
trung tâm[]Trả về một chuỗi tập trung
đếm[]Trả về số lần một giá trị được chỉ định xảy ra trong một chuỗi
mã hóa []Trả về một phiên bản được mã hóa của chuỗi
endswith []Trả về true nếu chuỗi kết thúc với giá trị được chỉ định
expandtabs []Đặt kích thước tab của chuỗi
tìm thấy[]Tìm kiếm chuỗi cho một giá trị được chỉ định và trả về vị trí của nơi nó được tìm thấy
định dạng[]Các định dạng các giá trị được chỉ định trong một chuỗi
format_map []Các định dạng các giá trị được chỉ định trong một chuỗi
format_map []Tìm kiếm chuỗi cho một giá trị được chỉ định và trả về vị trí của nơi nó được tìm thấy
định dạng[]Các định dạng các giá trị được chỉ định trong một chuỗi
format_map []mục lục[]
isalnum []Trả về true nếu tất cả các ký tự trong chuỗi là chữ và số
Isalpha []Trả về true nếu tất cả các ký tự trong chuỗi nằm trong bảng chữ cái
isascii []Trả về true nếu tất cả các ký tự trong chuỗi là các ký tự ASCII
isdecimal []Trả về true nếu tất cả các ký tự trong chuỗi là số thập phân
isdigit []Trả về true nếu tất cả các ký tự trong chuỗi là các chữ số
isidentifier []Trả về true nếu chuỗi là một định danh
thấp hơn[]Trả về true nếu tất cả các ký tự trong chuỗi là chữ thường
isnumeric []Trả về true nếu tất cả các ký tự trong chuỗi là số
isprintable []Trả về true nếu tất cả các ký tự trong chuỗi có thể in được
không gian ISSP []Trả về true nếu tất cả các ký tự trong chuỗi là khoảng trắng
istitle []Trả về đúng nếu chuỗi tuân theo các quy tắc của một tiêu đề
Isupper []Trả về true nếu tất cả các ký tự trong chuỗi là trường hợp trên
tham gia[]Chuyển đổi các phần tử của một thứ có thể lặp thành một chuỗi
ljust []Trả về một phiên bản chính đáng của chuỗi
thấp hơn[]Chuyển đổi một chuỗi thành chữ thường
Lstrip []Trả về phiên bản trang trí bên trái của chuỗi
Maketrans []Trả về một bảng dịch được sử dụng trong các bản dịch
vách ngăn[]Trả về một tuple trong đó chuỗi được chia thành ba phần
thay thế[]Trả về một tuple trong đó chuỗi được chia thành ba phần
thay thế[]Trả về một chuỗi trong đó một giá trị được chỉ định được thay thế bằng một giá trị được chỉ định
rfind []Trả về phiên bản trang trí bên trái của chuỗi
Maketrans []Trả về một bảng dịch được sử dụng trong các bản dịch
vách ngăn[]Trả về một tuple trong đó chuỗi được chia thành ba phần
thay thế[]Trả về một bảng dịch được sử dụng trong các bản dịch
vách ngăn[]Trả về một tuple trong đó chuỗi được chia thành ba phần
thay thế[]Trả về một chuỗi trong đó một giá trị được chỉ định được thay thế bằng một giá trị được chỉ định
rfind []Tìm kiếm chuỗi cho một giá trị được chỉ định và trả về vị trí cuối cùng của nơi nó được tìm thấy
Rindex []RJUST []
Trả về một phiên bản chính đáng của chuỗirpartition []
rsplit []Chia chuỗi vào dấu phân cách được chỉ định và trả về danh sách
rstrip []Trả về một phiên bản trang trí bên phải của chuỗi
tách ra[]splitlines []

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ố lor

Cá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 first
0 đượ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 first
3. 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 first
6. 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 first
9.

________ 17 ________ 31¶

Chuỗi

format_spec     ::=  [[fill]align][sign][#][0][width][grouping_option][.precision][type]
fill            ::=  
align           ::=  "" | "=" | "^"
sign            ::=  "+" | "-" | " "
width           ::=  digit+
grouping_option ::=  "_" | ","
precision       ::=  digit+
type            ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
2.

________ 17 ________ 34¶

Chuỗi

format_spec     ::=  [[fill]align][sign][#][0][width][grouping_option][.precision][type]
fill            ::=  
align           ::=  "" | "=" | "^"
sign            ::=  "+" | "-" | " "
width           ::=  digit+
grouping_option ::=  "_" | ","
precision       ::=  digit+
type            ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
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     ::=  [[fill]align][sign][#][0][width][grouping_option][.precision][type]
fill            ::=  
align           ::=  "" | "=" | "^"
sign            ::=  "+" | "-" | " "
width           ::=  digit+
grouping_option ::=  "_" | ","
precision       ::=  digit+
type            ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
8:
format_spec     ::=  [[fill]align][sign][#][0][width][grouping_option][.precision][type]
fill            ::=  
align           ::=  "" | "=" | "^"
sign            ::=  "+" | "-" | " "
width           ::=  digit+
grouping_option ::=  "_" | ","
precision       ::=  digit+
type            ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
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ỉnh

Lớ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áp

Phươ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['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 ::=  "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name        ::=  arg_name ["." attribute_name | "[" element_index "]"]*
arg_name          ::=  [identifier | digit+]
attribute_name    ::=  identifier
element_index     ::=  digit+ | index_string
index_string      ::=   +
conversion        ::=  "r" | "s" | "a"
format_spec       ::=  

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['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['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['right aligned']
'                 right aligned'
>>> '{:^30}'.format['centered']
'           centered           '
>>> '{:*^30}'.format['centered']  # use '*' as a fill char
'***********centered***********'
3 hoặc
>>> '{: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['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['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['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, do đó
"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 tương đương vớ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'.
01.The positional argument specifiers can be omitted for
>>> "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.The positional argument specifiers can be omitted for
>>> '{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     ::=  [[fill]align][sign][#][0][width][grouping_option][.precision][type]
fill            ::=  
align           ::=  "" | "=" | "^"
sign            ::=  "+" | "-" | " "
width           ::=  digit+
grouping_option ::=  "_" | ","
precision       ::=  digit+
type            ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

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:

Quyền mua

Nghĩ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'.
17

Buộc trường phải được liên kết trái trong không gian có sẵn [đây là mặc định cho hầu hết các đối tượ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'.
18

Buộc trường phải được liên kết đúng trong không gian có sẵn [đây là mặc định cho các 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'.
19

Buộc các phần đệm được đặt sau dấu hiệu [nếu có] nhưng trước các chữ số. Điều này được sử dụng để in các trường trong mẫu ‘+000000120. Tùy chọn căn chỉnh này chỉ có giá trị cho các loại số. Nó trở thành mặc định cho các số khi ‘0, ngay trước chiều rộng trườ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'.
20

Buộc các lĩnh vực phải được tập trung trong không gian có sẵn.

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:

Quyền mua

Nghĩ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'.
21

Buộc trường phải được liên kết trái trong không gian có sẵn [đây là mặc định cho hầu hết các đối tượ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'.
22

Buộc trường phải được liên kết đúng trong không gian có sẵn [đây là mặc định cho các số].

Buộc các phần đệm được đặt sau dấu hiệu [nếu có] nhưng trước các chữ số. Điều này được sử dụng để in các trường trong mẫu ‘+000000120. Tùy chọn căn chỉnh này chỉ có giá trị cho các loại số. Nó trở thành mặc định cho các số khi ‘0, ngay trước chiều rộng trường.

Buộc các lĩnh vực phải được tập trung trong không gian có sẵn.

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 không còn ảnh hưởng đến căn chỉnh mặc định cho các chuỗi.Preceding the width field by
"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à:

Loại hình

Nghĩ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'.
48

Định dạng chuỗi. Đây là loại mặc định cho chuỗi và có thể bị bỏ qua.

Không có

Giống như

"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'.
48.

Các loại trình bày số nguyên có sẵn là:

Loại hình

Nghĩ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'.
35

Định dạng chuỗi. Đây là loại mặc định cho chuỗi và có thể bị bỏ qua.

"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'.
51

Không 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'.
34

Giống như

"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'.
48.

"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'.
36

Các loại trình bày số nguyên có sẵn 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'.
37

Định dạng nhị phân. Đầu ra số trong cơ sở 2.

"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'.
38

Tính cách. Chuyển đổi số nguyên thành ký tự unicode tương ứng trước khi in.

"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'.
31

Số nguyên thập phân. Đầu ra số trong cơ sở 10.

Không có

Giống như

"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'.
48.

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.

Loại hình

Nghĩ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'.
67

Định dạng chuỗi. Đây là loại mặc định cho chuỗi và có thể bị bỏ qua.

"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'.
75

Không 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'.
44

Giống như

"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'.
48.

"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

Các loại trình bày số nguyên có sẵn 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'.
28

Định dạng nhị phân. Đầu ra số trong cơ sở 2.

Tính cách. Chuyển đổi số nguyên thành ký tự unicode tương ứng trước khi in.

Số nguyên thập phân. Đầu ra số trong cơ sở 10.

Vô cực tích cực và tiêu cực, 0 dương và âm, và NAN, được định dạng 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'.
88,
"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
11,
"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'.
93,
"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
13 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'.
86, bất kể độ chính xá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

Định dạng chung. Giống như

"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 ngoại trừ chuyển sang
"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'.
75 nếu số lượng quá lớn. Các đại diện của Infinity và Nan cũng được sử dụ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'.
31

Con số. Điều này giống như

"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, ngoại trừ việc nó sử dụng cài đặt địa phương hiện tại để chèn các ký tự phân tách số thích hợ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 first
20

Tỷ lệ phần trăm. Nhân số lượng với 100 và hiển thị ở định dạng cố định [

"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], theo sau là dấu phần trăm.

Không có

Đối vớ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'.
65, điều này giống như
"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, ngoại trừ khi ký hiệu điểm cố định được sử dụng để định dạng kết quả, nó luôn bao gồm ít nhất một chữ số qua dấu thập phân. Độ chính xác được sử dụng là lớn như cần thiết để thể hiện giá trị đã cho một cách trung thực.

Đối vớ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'.
66, điều này giống như
"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 tùy thuộc vào giá trị 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 first
27 cho bối cảnh thập phân hiện tại.

Hiệu ứng tổng thể là phù hợp với đầu ra 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'.
06 khi bị thay đổi bởi các bộ điều chỉnh định dạng khác.

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 first
33 đượ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 first
30. 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
35 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 first
36.

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 first
37 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 first
38:

>>> "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['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 first
39,
"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
40 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 first
41 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 first
42 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 first
43 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ẫu

Cá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:

  • "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
    
    45 là một lối thoát; Nó được thay thế bằng một
    "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
    
    44.

  • "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
    
    47 đặt tên cho một trình giữ chỗ thay thế phù hợp với khóa ánh xạ 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 first
    
    48. Theo mặc đị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 first
    
    48 bị giới hạn trong bất kỳ chuỗi chữ và số khác không nhạy cảm với trường hợp [bao gồm cả dấu gạch dưới] bắt đầu bằng chữ cái dấu gạch dưới hoặc ASCII. Nhân vật không nhận dạng đầu tiên sau ký tự
    "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
    
    44 chấm dứt đặc tả của người giữ chỗ này.

  • "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
    
    51 tương đương 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 first
    
    47. Nó được yêu cầu khi các ký tự định danh hợp lệ tuân theo trình giữ chỗ nhưng không phải là một phần của trình giữ chỗ, chẳng hạn 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 first
    
    53.

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 first
44 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 first
55 đượ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 first
57 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 first
57 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 first
63, 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 first
63, 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 first
44 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 first
44 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 first
55.

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 first
69 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 first
57 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 first
57 để 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:

  • DELIMITER - Đây là chuỗi theo nghĩa đen mô tả một trình giữ chỗ giới thiệu Delimiter. Giá trị mặc định là

    "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
    
    44. Lưu ý rằng đây không phải là một biểu thức thông thường, vì việc triển khai sẽ gọ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 first
    
    74 trên chuỗi này khi cần. Lưu ý thêm rằng bạn không thể thay đổi dấu phân cách sau khi tạo lớp [nghĩa là một dấu phân cách khác phải được đặt trong không gian tên lớp con lớp con].

  • IDPOTYN-Đây là biểu thức chính quy mô tả mẫu cho người giữ chỗ không thuận tay. Giá trị mặc định là biểu thức thông 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 first
    
    75. Nếu điều này được đưa ra và BraceIdPotype 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, mô hình này cũng sẽ áp dụng cho các trình giữ chỗ giằng.

    Ghi chú

    Vì các cờ mặc định là

    "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
    
    77, mẫu
    "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
    
    78 có thể khớp với một số ký tự không phải ASCII. Đó là lý do tại sao chúng tôi sử dụng 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 first
    
    79 địa phương ở đây.

    Đã thay đổi trong phiên bản 3.7: BraceIdPattern có thể được sử dụng để xác định các mẫu riêng biệt được sử dụng bên trong và bên ngoài niềng răng.braceidpattern can be used to define separate patterns used inside and outside the braces.

  • BraceIdPotype - Điều này giống như idpattern nhưng mô tả mô hình cho các trình giữ chỗ giằng. Mặc định 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 có nghĩa là rơi trở lại idpattern [nghĩa là cùng một mẫu được sử dụng cả niềng răng bên trong và bên ngoài]. Nếu được đưa ra, điều này cho phép bạn xác định các mẫu khác nhau cho các chỗ giữ chỗ giằng và không thay đổi.

    Mới trong phiên bản 3.7.

  • Cờ - Các cờ biểu thức chính quy sẽ được áp dụng khi biên dịch biểu thức chính quy được sử dụng để nhận biết các thay thế. Giá trị mặc định là

    "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
    
    77. Lưu ý rằ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 first
    
    82 sẽ luôn được thêm vào các lá cờ, vì vậy các idpattern tùy chỉnh phải tuân theo các quy ước cho các biểu thức chính quy verbose.

    Mới trong phiên bản 3.2.

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ệ:

  • Thoát khỏi - Nhóm này phù hợp với chuỗi thoát, 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
    
    45, trong mẫu mặc định.

  • Được đặt tên - Nhóm này phù hợp với tên giữ chỗ không có mặt; Nó không nên bao gồm các dấu phân cách trong nhóm chụp.

  • BRACED - Nhóm này phù hợp với tên giữ chỗ kín nẹp; Nó không nên bao gồm các dấu phân cách hoặc niềng răng trong nhóm bắt giữ.

  • Không hợp lệ - Nhóm này phù hợp với bất kỳ mẫu phân cách nào khác [thường là một dấu phân cách duy nhất] và nó sẽ xuất hiện cuối cùng trong biểu thức chính quy.

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 first
86, 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 first
87 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 first
88. 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ừ.

Bài Viết Liên Quan

Chủ Đề