syntax.rst 24 KB

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