• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1.. _syntax:
2
3********************
4Format String Syntax
5********************
6
7Formatting functions such as :ref:`fmt::format() <format>` and
8:ref:`fmt::print() <print>` use the same format string syntax described in this
9section.
10
11Format strings contain "replacement fields" surrounded by curly braces ``{}``.
12Anything that is not contained in braces is considered literal text, which is
13copied unchanged to the output.  If you need to include a brace character in the
14literal text, it can be escaped by doubling: ``{{`` and ``}}``.
15
16The grammar for a replacement field is as follows:
17
18.. productionlist:: sf
19   replacement_field: "{" [`arg_id`] [":" `format_spec`] "}"
20   arg_id: `integer` | `identifier`
21   integer: `digit`+
22   digit: "0"..."9"
23   identifier: `id_start` `id_continue`*
24   id_start: "a"..."z" | "A"..."Z" | "_"
25   id_continue: `id_start` | `digit`
26
27In less formal terms, the replacement field can start with an *arg_id*
28that specifies the argument whose value is to be formatted and inserted into
29the output instead of the replacement field.
30The *arg_id* is optionally followed by a *format_spec*, which is preceded
31by a colon ``':'``.  These specify a non-default format for the replacement value.
32
33See also the :ref:`formatspec` section.
34
35If the numerical arg_ids in a format string are 0, 1, 2, ... in sequence,
36they can all be omitted (not just some) and the numbers 0, 1, 2, ... will be
37automatically inserted in that order.
38
39Named arguments can be referred to by their names or indices.
40
41Some simple format string examples::
42
43   "First, thou shalt count to {0}" // References the first argument
44   "Bring me a {}"                  // Implicitly references the first argument
45   "From {} to {}"                  // Same as "From {0} to {1}"
46
47The *format_spec* field contains a specification of how the value should be
48presented, including such details as field width, alignment, padding, decimal
49precision and so on.  Each value type can define its own "formatting
50mini-language" or interpretation of the *format_spec*.
51
52Most built-in types support a common formatting mini-language, which is
53described in the next section.
54
55A *format_spec* field can also include nested replacement fields in certain
56positions within it. These nested replacement fields can contain only an
57argument id; format specifications are not allowed. This allows the formatting
58of a value to be dynamically specified.
59
60See the :ref:`formatexamples` section for some examples.
61
62.. _formatspec:
63
64Format Specification Mini-Language
65==================================
66
67"Format specifications" are used within replacement fields contained within a
68format string to define how individual values are presented (see
69:ref:`syntax`).  Each formattable type may define how the format
70specification is to be interpreted.
71
72Most built-in types implement the following options for format specifications,
73although some of the formatting options are only supported by the numeric types.
74
75The general form of a *standard format specifier* is:
76
77.. productionlist:: sf
78   format_spec: [[`fill`]`align`][`sign`]["#"]["0"][`width`]["." `precision`][`type`]
79   fill: <a character other than '{', '}' or '\0'>
80   align: "<" | ">" | "=" | "^"
81   sign: "+" | "-" | " "
82   width: `integer` | "{" `arg_id` "}"
83   precision: `integer` | "{" `arg_id` "}"
84   type: `int_type` | "a" | "A" | "c" | "e" | "E" | "f" | "F" | "g" | "G" | "p" | "s"
85   int_type: "b" | "B" | "d" | "n" | "o" | "x" | "X"
86
87The *fill* character can be any character other than '{', '}' or '\\0'. The
88presence of a fill character is signaled by the character following it, which
89must be one of the alignment options.  If the second character of *format_spec*
90is not a valid alignment option, then it is assumed that both the fill character
91and the alignment option are absent.
92
93The meaning of the various alignment options is as follows:
94
95+---------+----------------------------------------------------------+
96| Option  | Meaning                                                  |
97+=========+==========================================================+
98| ``'<'`` | Forces the field to be left-aligned within the available |
99|         | space (this is the default for most objects).            |
100+---------+----------------------------------------------------------+
101| ``'>'`` | Forces the field to be right-aligned within the          |
102|         | available space (this is the default for numbers).       |
103+---------+----------------------------------------------------------+
104| ``'^'`` | Forces the field to be centered within the available     |
105|         | space.                                                   |
106+---------+----------------------------------------------------------+
107
108Note that unless a minimum field width is defined, the field width will always
109be the same size as the data to fill it, so that the alignment option has no
110meaning in this case.
111
112The *sign* option is only valid for number types, and can be one of the
113following:
114
115+---------+----------------------------------------------------------+
116| Option  | Meaning                                                  |
117+=========+==========================================================+
118| ``'+'`` | indicates that a sign should be used for both            |
119|         | positive as well as negative numbers.                    |
120+---------+----------------------------------------------------------+
121| ``'-'`` | indicates that a sign should be used only for negative   |
122|         | numbers (this is the default behavior).                  |
123+---------+----------------------------------------------------------+
124| space   | indicates that a leading space should be used on         |
125|         | positive numbers, and a minus sign on negative numbers.  |
126+---------+----------------------------------------------------------+
127
128The ``'#'`` option causes the "alternate form" to be used for the
129conversion.  The alternate form is defined differently for different
130types.  This option is only valid for integer and floating-point types.
131For integers, when binary, octal, or hexadecimal output is used, this
132option adds the prefix respective ``"0b"`` (``"0B"``), ``"0"``, or
133``"0x"`` (``"0X"``) to the output value.  Whether the prefix is
134lower-case or upper-case is determined by the case of the type
135specifier, for example, the prefix ``"0x"`` is used for the type ``'x'``
136and ``"0X"`` is used for ``'X'``.  For floating-point numbers the
137alternate form causes the result of the conversion to always contain a
138decimal-point character, even if no digits follow it. Normally, a
139decimal-point character appears in the result of these conversions
140only if a digit follows it. In addition, for ``'g'`` and ``'G'``
141conversions, trailing zeros are not removed from the result.
142
143.. ifconfig:: False
144
145   The ``','`` option signals the use of a comma for a thousands separator.
146   For a locale aware separator, use the ``'n'`` integer presentation type
147   instead.
148
149*width* is a decimal integer defining the minimum field width.  If not
150specified, then the field width will be determined by the content.
151
152Preceding the *width* field by a zero (``'0'``) character enables sign-aware
153zero-padding for numeric types. It forces the padding to be placed after the
154sign or base (if any) but before the digits. This is used for printing fields in
155the form '+000000120'. This option is only valid for numeric types and it has no
156effect on formatting of infinity and NaN.
157
158The *precision* is a decimal number indicating how many digits should be
159displayed after the decimal point for a floating-point value formatted with
160``'f'`` and ``'F'``, or before and after the decimal point for a floating-point
161value formatted with ``'g'`` or ``'G'``.  For non-number types the field
162indicates the maximum field size - in other words, how many characters will be
163used from the field content. The *precision* is not allowed for integer,
164character, Boolean, and pointer values.
165
166Finally, the *type* determines how the data should be presented.
167
168The available string presentation types are:
169
170+---------+----------------------------------------------------------+
171| Type    | Meaning                                                  |
172+=========+==========================================================+
173| ``'s'`` | String format. This is the default type for strings and  |
174|         | may be omitted.                                          |
175+---------+----------------------------------------------------------+
176| none    | The same as ``'s'``.                                     |
177+---------+----------------------------------------------------------+
178
179The available character presentation types are:
180
181+---------+----------------------------------------------------------+
182| Type    | Meaning                                                  |
183+=========+==========================================================+
184| ``'c'`` | Character format. This is the default type for           |
185|         | characters and may be omitted.                           |
186+---------+----------------------------------------------------------+
187| none    | The same as ``'c'``.                                     |
188+---------+----------------------------------------------------------+
189
190The available integer presentation types are:
191
192+---------+----------------------------------------------------------+
193| Type    | Meaning                                                  |
194+=========+==========================================================+
195| ``'b'`` | Binary format. Outputs the number in base 2. Using the   |
196|         | ``'#'`` option with this type adds the prefix ``"0b"``   |
197|         | to the output value.                                     |
198+---------+----------------------------------------------------------+
199| ``'B'`` | Binary format. Outputs the number in base 2. Using the   |
200|         | ``'#'`` option with this type adds the prefix ``"0B"``   |
201|         | to the output value.                                     |
202+---------+----------------------------------------------------------+
203| ``'d'`` | Decimal integer. Outputs the number in base 10.          |
204+---------+----------------------------------------------------------+
205| ``'o'`` | Octal format. Outputs the number in base 8.              |
206+---------+----------------------------------------------------------+
207| ``'x'`` | Hex format. Outputs the number in base 16, using         |
208|         | lower-case letters for the digits above 9. Using the     |
209|         | ``'#'`` option with this type adds the prefix ``"0x"``   |
210|         | to the output value.                                     |
211+---------+----------------------------------------------------------+
212| ``'X'`` | Hex format. Outputs the number in base 16, using         |
213|         | upper-case letters for the digits above 9. Using the     |
214|         | ``'#'`` option with this type adds the prefix ``"0X"``   |
215|         | to the output value.                                     |
216+---------+----------------------------------------------------------+
217| ``'n'`` | Number. This is the same as ``'d'``, except that it uses |
218|         | the current locale setting to insert the appropriate     |
219|         | number separator characters.                             |
220+---------+----------------------------------------------------------+
221| none    | The same as ``'d'``.                                     |
222+---------+----------------------------------------------------------+
223
224Integer presentation types can also be used with character and Boolean values.
225Boolean values are formatted using textual representation, either ``true`` or
226``false``, if the presentation type is not specified.
227
228The available presentation types for floating-point values are:
229
230+---------+----------------------------------------------------------+
231| Type    | Meaning                                                  |
232+=========+==========================================================+
233| ``'a'`` | Hexadecimal floating point format. Prints the number in  |
234|         | base 16 with prefix ``"0x"`` and lower-case letters for  |
235|         | digits above 9. Uses ``'p'`` to indicate the exponent.   |
236+---------+----------------------------------------------------------+
237| ``'A'`` | Same as ``'a'`` except it uses upper-case letters for    |
238|         | the prefix, digits above 9 and to indicate the exponent. |
239+---------+----------------------------------------------------------+
240| ``'e'`` | Exponent notation. Prints the number in scientific       |
241|         | notation using the letter 'e' to indicate the exponent.  |
242+---------+----------------------------------------------------------+
243| ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an     |
244|         | upper-case ``'E'`` as the separator character.           |
245+---------+----------------------------------------------------------+
246| ``'f'`` | Fixed point. Displays the number as a fixed-point        |
247|         | number.                                                  |
248+---------+----------------------------------------------------------+
249| ``'F'`` | Fixed point. Same as ``'f'``, but converts ``nan`` to    |
250|         | ``NAN`` and ``inf`` to ``INF``.                          |
251+---------+----------------------------------------------------------+
252| ``'g'`` | General format.  For a given precision ``p >= 1``,       |
253|         | this rounds the number to ``p`` significant digits and   |
254|         | then formats the result in either fixed-point format     |
255|         | or in scientific notation, depending on its magnitude.   |
256|         |                                                          |
257|         | A precision of ``0`` is treated as equivalent to a       |
258|         | precision of ``1``.                                      |
259+---------+----------------------------------------------------------+
260| ``'G'`` | General format. Same as ``'g'`` except switches to       |
261|         | ``'E'`` if the number gets too large. The                |
262|         | representations of infinity and NaN are uppercased, too. |
263+---------+----------------------------------------------------------+
264| ``'n'`` | Number. This is the same as ``'g'``, except that it uses |
265|         | the current locale setting to insert the appropriate     |
266|         | number separator characters.                             |
267+---------+----------------------------------------------------------+
268| ``'%'`` | Fixed point as a percentage. This is similar to ``'f'``, |
269|         | but the argument is multiplied by 100 and a percent sign |
270|         | ``%`` is appended.                                       |
271+---------+----------------------------------------------------------+
272| none    | Similar to ``'g'``, except that fixed-point notation,    |
273|         | when used, has at least one digit past the decimal       |
274|         | point. The default precision is as high as needed to     |
275|         | represent the particular value.                          |
276+---------+----------------------------------------------------------+
277
278.. ifconfig:: False
279
280   +---------+----------------------------------------------------------+
281   |         | The precise rules are as follows: suppose that the       |
282   |         | result formatted with presentation type ``'e'`` and      |
283   |         | precision ``p-1`` would have exponent ``exp``.  Then     |
284   |         | if ``-4 <= exp < p``, the number is formatted            |
285   |         | with presentation type ``'f'`` and precision             |
286   |         | ``p-1-exp``.  Otherwise, the number is formatted         |
287   |         | with presentation type ``'e'`` and precision ``p-1``.    |
288   |         | In both cases insignificant trailing zeros are removed   |
289   |         | from the significand, and the decimal point is also      |
290   |         | removed if there are no remaining digits following it.   |
291   |         |                                                          |
292   |         | Positive and negative infinity, positive and negative    |
293   |         | zero, and nans, are formatted as ``inf``, ``-inf``,      |
294   |         | ``0``, ``-0`` and ``nan`` respectively, regardless of    |
295   |         | the precision.                                           |
296   |         |                                                          |
297   +---------+----------------------------------------------------------+
298
299The available presentation types for pointers are:
300
301+---------+----------------------------------------------------------+
302| Type    | Meaning                                                  |
303+=========+==========================================================+
304| ``'p'`` | Pointer format. This is the default type for             |
305|         | pointers and may be omitted.                             |
306+---------+----------------------------------------------------------+
307| none    | The same as ``'p'``.                                     |
308+---------+----------------------------------------------------------+
309
310.. _formatexamples:
311
312Format Examples
313===============
314
315This section contains examples of the format syntax and comparison with
316the printf formatting.
317
318In most of the cases the syntax is similar to the printf formatting, with the
319addition of the ``{}`` and with ``:`` used instead of ``%``.
320For example, ``"%03.2f"`` can be translated to ``"{:03.2f}"``.
321
322The new format syntax also supports new and different options, shown in the
323following examples.
324
325Accessing arguments by position::
326
327   format("{0}, {1}, {2}", 'a', 'b', 'c');
328   // Result: "a, b, c"
329   format("{}, {}, {}", 'a', 'b', 'c');
330   // Result: "a, b, c"
331   format("{2}, {1}, {0}", 'a', 'b', 'c');
332   // Result: "c, b, a"
333   format("{0}{1}{0}", "abra", "cad");  // arguments' indices can be repeated
334   // Result: "abracadabra"
335
336Aligning the text and specifying a width::
337
338   format("{:<30}", "left aligned");
339   // Result: "left aligned                  "
340   format("{:>30}", "right aligned");
341   // Result: "                 right aligned"
342   format("{:^30}", "centered");
343   // Result: "           centered           "
344   format("{:*^30}", "centered");  // use '*' as a fill char
345   // Result: "***********centered***********"
346
347Dynamic width::
348
349   format("{:<{}}", "left aligned", 30);
350   // Result: "left aligned                  "
351
352Dynamic precision::
353
354   format("{:.{}f}", 3.14, 1);
355   // Result: "3.1"
356
357Replacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign::
358
359   format("{:+f}; {:+f}", 3.14, -3.14);  // show it always
360   // Result: "+3.140000; -3.140000"
361   format("{: f}; {: f}", 3.14, -3.14);  // show a space for positive numbers
362   // Result: " 3.140000; -3.140000"
363   format("{:-f}; {:-f}", 3.14, -3.14);  // show only the minus -- same as '{:f}; {:f}'
364   // Result: "3.140000; -3.140000"
365
366As a percentage::
367
368   format("{0:f} or {0:%}", .635);
369   // Result: "0.635000 or 63.500000%"
370   format("{:*^{}.{}%}", 1., 15, 2); // With fill, dynamic width and dynamic precision.
371   // Result: "****100.00%****"
372
373Replacing ``%x`` and ``%o`` and converting the value to different bases::
374
375   format("int: {0:d};  hex: {0:x};  oct: {0:o}; bin: {0:b}", 42);
376   // Result: "int: 42;  hex: 2a;  oct: 52; bin: 101010"
377   // with 0x or 0 or 0b as prefix:
378   format("int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}", 42);
379   // Result: "int: 42;  hex: 0x2a;  oct: 052;  bin: 0b101010"
380
381Padded hex byte with prefix and always prints both hex characters::
382
383   format("{:#04x}", 0);
384   // Result: "0x00"
385
386.. ifconfig:: False
387
388   Using the comma as a thousands separator::
389
390      format("{:,}", 1234567890);
391      '1,234,567,890'
392
393   Using type-specific formatting::
394
395      >>> import datetime
396      >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
397      Format("{:%Y-%m-%d %H:%M:%S}") << d)
398      '2010-07-04 12:15:58'
399
400   Nesting arguments and more complex examples::
401
402      >>> for align, text in zip('<^>', ['left', 'center', 'right']):
403      ...     '{0:{fill}{align}16}") << text, fill=align, align=align)
404      ...
405      'left<<<<<<<<<<<<'
406      '^^^^^center^^^^^'
407      '>>>>>>>>>>>right'
408      >>>
409      >>> octets = [192, 168, 0, 1]
410      Format("{:02X}{:02X}{:02X}{:02X}") << *octets)
411      'C0A80001'
412      >>> int(_, 16)
413      3232235521
414      >>>
415      >>> width = 5
416      >>> for num in range(5,12):
417      ...     for base in 'dXob':
418      ...         print('{0:{width}{base}}") << num, base=base, width=width), end=' ')
419      ...     print()
420      ...
421          5     5     5   101
422          6     6     6   110
423          7     7     7   111
424          8     8    10  1000
425          9     9    11  1001
426         10     A    12  1010
427         11     B    13  1011
428