syntax.rst 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  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 floating point and signed integer types,
  87. and can be one of the 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 duration and time point types as well as
  257. ``std::tm`` have the following 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*) are:
  271. +---------+--------------------------------------------------------------------+
  272. | Type | Meaning |
  273. +=========+====================================================================+
  274. | ``'a'`` | The abbreviated weekday name, e.g. "Sat". If the value does not |
  275. | | contain a valid weekday, an exception of type ``format_error`` is |
  276. | | thrown. |
  277. +---------+--------------------------------------------------------------------+
  278. | ``'A'`` | The full weekday name, e.g. "Saturday". If the value does not |
  279. | | contain a valid weekday, an exception of type ``format_error`` is |
  280. | | thrown. |
  281. +---------+--------------------------------------------------------------------+
  282. | ``'b'`` | The abbreviated month name, e.g. "Nov". If the value does not |
  283. | | contain a valid month, an exception of type ``format_error`` is |
  284. | | thrown. |
  285. +---------+--------------------------------------------------------------------+
  286. | ``'B'`` | The full month name, e.g. "November". If the value does not |
  287. | | contain a valid month, an exception of type ``format_error`` is |
  288. | | thrown. |
  289. +---------+--------------------------------------------------------------------+
  290. | ``'c'`` | The date and time representation, e.g. "Sat Nov 12 22:04:00 1955". |
  291. | | The modified command ``%Ec`` produces the locale's alternate date |
  292. | | and time representation. |
  293. +---------+--------------------------------------------------------------------+
  294. | ``'C'`` | The year divided by 100 using floored division, e.g. "55". If the |
  295. | | result is a single decimal digit, it is prefixed with 0. |
  296. | | The modified command ``%EC`` produces the locale's alternative |
  297. | | representation of the century. |
  298. +---------+--------------------------------------------------------------------+
  299. | ``'d'`` | The day of month as a decimal number. If the result is a single |
  300. | | decimal digit, it is prefixed with 0. The modified command ``%Od`` |
  301. | | produces the locale's alternative representation. |
  302. +---------+--------------------------------------------------------------------+
  303. | ``'D'`` | Equivalent to ``%m/%d/%y``, e.g. "11/12/55". |
  304. +---------+--------------------------------------------------------------------+
  305. | ``'e'`` | The day of month as a decimal number. If the result is a single |
  306. | | decimal digit, it is prefixed with a space. The modified command |
  307. | | ``%Oe`` produces the locale's alternative representation. |
  308. +---------+--------------------------------------------------------------------+
  309. | ``'F'`` | Equivalent to ``%Y-%m-%d``, e.g. "1955-11-12". |
  310. +---------+--------------------------------------------------------------------+
  311. | ``'g'`` | The last two decimal digits of the ISO week-based year. If the |
  312. | | result is a single digit it is prefixed by 0. |
  313. +---------+--------------------------------------------------------------------+
  314. | ``'G'`` | The ISO week-based year as a decimal number. If the result is less |
  315. | | than four digits it is left-padded with 0 to four digits. |
  316. +---------+--------------------------------------------------------------------+
  317. | ``'h'`` | Equivalent to ``%b``, e.g. "Nov". |
  318. +---------+--------------------------------------------------------------------+
  319. | ``'H'`` | The hour (24-hour clock) as a decimal number. If the result is a |
  320. | | single digit, it is prefixed with 0. The modified command ``%OH`` |
  321. | | produces the locale's alternative representation. |
  322. +---------+--------------------------------------------------------------------+
  323. | ``'I'`` | The hour (12-hour clock) as a decimal number. If the result is a |
  324. | | single digit, it is prefixed with 0. The modified command ``%OI`` |
  325. | | produces the locale's alternative representation. |
  326. +---------+--------------------------------------------------------------------+
  327. | ``'j'`` | If the type being formatted is a specialization of duration, the |
  328. | | decimal number of days without padding. Otherwise, the day of the |
  329. | | year as a decimal number. Jan 1 is 001. If the result is less than |
  330. | | three digits, it is left-padded with 0 to three digits. |
  331. +---------+--------------------------------------------------------------------+
  332. | ``'m'`` | The month as a decimal number. Jan is 01. If the result is a |
  333. | | single digit, it is prefixed with 0. The modified command ``%Om`` |
  334. | | produces the locale's alternative representation. |
  335. +---------+--------------------------------------------------------------------+
  336. | ``'M'`` | The minute as a decimal number. If the result is a single digit, |
  337. | | it is prefixed with 0. The modified command ``%OM`` produces the |
  338. | | locale's alternative representation. |
  339. +---------+--------------------------------------------------------------------+
  340. | ``'n'`` | A new-line character. |
  341. +---------+--------------------------------------------------------------------+
  342. | ``'p'`` | The AM/PM designations associated with a 12-hour clock. |
  343. +---------+--------------------------------------------------------------------+
  344. | ``'q'`` | The duration's unit suffix. |
  345. +---------+--------------------------------------------------------------------+
  346. | ``'Q'`` | The duration's numeric value (as if extracted via ``.count()``). |
  347. +---------+--------------------------------------------------------------------+
  348. | ``'r'`` | The 12-hour clock time, e.g. "10:04:00 PM". |
  349. +---------+--------------------------------------------------------------------+
  350. | ``'R'`` | Equivalent to ``%H:%M``, e.g. "22:04". |
  351. +---------+--------------------------------------------------------------------+
  352. | ``'S'`` | Seconds as a decimal number. If the number of seconds is less than |
  353. | | 10, the result is prefixed with 0. If the precision of the input |
  354. | | cannot be exactly represented with seconds, then the format is a |
  355. | | decimal floating-point number with a fixed format and a precision |
  356. | | matching that of the precision of the input (or to a microseconds |
  357. | | precision if the conversion to floating-point decimal seconds |
  358. | | cannot be made within 18 fractional digits). The character for the |
  359. | | decimal point is localized according to the locale. The modified |
  360. | | command ``%OS`` produces the locale's alternative representation. |
  361. +---------+--------------------------------------------------------------------+
  362. | ``'t'`` | A horizontal-tab character. |
  363. +---------+--------------------------------------------------------------------+
  364. | ``'T'`` | Equivalent to ``%H:%M:%S``. |
  365. +---------+--------------------------------------------------------------------+
  366. | ``'u'`` | The ISO weekday as a decimal number (1-7), where Monday is 1. The |
  367. | | modified command ``%Ou`` produces the locale's alternative |
  368. | | representation. |
  369. +---------+--------------------------------------------------------------------+
  370. | ``'U'`` | The week number of the year as a decimal number. The first Sunday |
  371. | | of the year is the first day of week 01. Days of the same year |
  372. | | prior to that are in week 00. If the result is a single digit, it |
  373. | | is prefixed with 0. The modified command ``%OU`` produces the |
  374. | | locale's alternative representation. |
  375. +---------+--------------------------------------------------------------------+
  376. | ``'V'`` | The ISO week-based week number as a decimal number. If the result |
  377. | | is a single digit, it is prefixed with 0. The modified command |
  378. | | ``%OV`` produces the locale's alternative representation. |
  379. +---------+--------------------------------------------------------------------+
  380. | ``'w'`` | The weekday as a decimal number (0-6), where Sunday is 0. |
  381. | | The modified command ``%Ow`` produces the locale's alternative |
  382. | | representation. |
  383. +---------+--------------------------------------------------------------------+
  384. | ``'W'`` | The week number of the year as a decimal number. The first Monday |
  385. | | of the year is the first day of week 01. Days of the same year |
  386. | | prior to that are in week 00. If the result is a single digit, it |
  387. | | is prefixed with 0. The modified command ``%OW`` produces the |
  388. | | locale's alternative representation. |
  389. +---------+--------------------------------------------------------------------+
  390. | ``'x'`` | The date representation, e.g. "11/12/55". The modified command |
  391. | | ``%Ex`` produces the locale's alternate date representation. |
  392. +---------+--------------------------------------------------------------------+
  393. | ``'X'`` | The time representation, e.g. "10:04:00". The modified command |
  394. | | ``%EX`` produces the locale's alternate time representation. |
  395. +---------+--------------------------------------------------------------------+
  396. | ``'y'`` | The last two decimal digits of the year. If the result is a single |
  397. | | digit it is prefixed by 0. The modified command ``%Oy`` produces |
  398. | | the locale's alternative representation. The modified command |
  399. | | ``%Ey`` produces the locale's alternative representation of offset |
  400. | | from ``%EC`` (year only). |
  401. +---------+--------------------------------------------------------------------+
  402. | ``'Y'`` | The year as a decimal number. If the result is less than four |
  403. | | digits it is left-padded with 0 to four digits. The modified |
  404. | | command ``%EY`` produces the locale's alternative full year |
  405. | | representation. |
  406. +---------+--------------------------------------------------------------------+
  407. | ``'z'`` | The offset from UTC in the ISO 8601:2004 format. For example -0430 |
  408. | | refers to 4 hours 30 minutes behind UTC. If the offset is zero, |
  409. | | +0000 is used. The modified commands ``%Ez`` and ``%Oz`` insert a |
  410. | | ``:`` between the hours and minutes: -04:30. If the offset |
  411. | | information is not available, an exception of type |
  412. | | ``format_error`` is thrown. |
  413. +---------+--------------------------------------------------------------------+
  414. | ``'Z'`` | The time zone abbreviation. If the time zone abbreviation is not |
  415. | | available, an exception of type ``format_error`` is thrown. |
  416. +---------+--------------------------------------------------------------------+
  417. | ``'%'`` | A % character. |
  418. +---------+--------------------------------------------------------------------+
  419. Specifiers that have a calendaric component such as ``'d'`` (the day of month)
  420. are valid only for ``std::tm`` and time points but not durations.
  421. .. range-specs:
  422. Range Format Specifications
  423. ===========================
  424. Format specifications for range types have the following syntax:
  425. .. productionlist:: sf
  426. range_format_spec: [":" [`underlying_spec`]]
  427. The `underlying_spec` is parsed based on the formatter of the range's
  428. reference type.
  429. By default, a range of characters or strings is printed escaped and quoted. But
  430. if any `underlying_spec` is provided (even if it is empty), then the characters
  431. or strings are printed according to the provided specification.
  432. Examples::
  433. fmt::format("{}", std::vector{10, 20, 30});
  434. // Result: [10, 20, 30]
  435. fmt::format("{::#x}", std::vector{10, 20, 30});
  436. // Result: [0xa, 0x14, 0x1e]
  437. fmt::format("{}", vector{'h', 'e', 'l', 'l', 'o'});
  438. // Result: ['h', 'e', 'l', 'l', 'o']
  439. fmt::format("{::}", vector{'h', 'e', 'l', 'l', 'o'});
  440. // Result: [h, e, l, l, o]
  441. fmt::format("{::d}", vector{'h', 'e', 'l', 'l', 'o'});
  442. // Result: [104, 101, 108, 108, 111]
  443. .. _formatexamples:
  444. Format Examples
  445. ===============
  446. This section contains examples of the format syntax and comparison with
  447. the printf formatting.
  448. In most of the cases the syntax is similar to the printf formatting, with the
  449. addition of the ``{}`` and with ``:`` used instead of ``%``.
  450. For example, ``"%03.2f"`` can be translated to ``"{:03.2f}"``.
  451. The new format syntax also supports new and different options, shown in the
  452. following examples.
  453. Accessing arguments by position::
  454. fmt::format("{0}, {1}, {2}", 'a', 'b', 'c');
  455. // Result: "a, b, c"
  456. fmt::format("{}, {}, {}", 'a', 'b', 'c');
  457. // Result: "a, b, c"
  458. fmt::format("{2}, {1}, {0}", 'a', 'b', 'c');
  459. // Result: "c, b, a"
  460. fmt::format("{0}{1}{0}", "abra", "cad"); // arguments' indices can be repeated
  461. // Result: "abracadabra"
  462. Aligning the text and specifying a width::
  463. fmt::format("{:<30}", "left aligned");
  464. // Result: "left aligned "
  465. fmt::format("{:>30}", "right aligned");
  466. // Result: " right aligned"
  467. fmt::format("{:^30}", "centered");
  468. // Result: " centered "
  469. fmt::format("{:*^30}", "centered"); // use '*' as a fill char
  470. // Result: "***********centered***********"
  471. Dynamic width::
  472. fmt::format("{:<{}}", "left aligned", 30);
  473. // Result: "left aligned "
  474. Dynamic precision::
  475. fmt::format("{:.{}f}", 3.14, 1);
  476. // Result: "3.1"
  477. Replacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign::
  478. fmt::format("{:+f}; {:+f}", 3.14, -3.14); // show it always
  479. // Result: "+3.140000; -3.140000"
  480. fmt::format("{: f}; {: f}", 3.14, -3.14); // show a space for positive numbers
  481. // Result: " 3.140000; -3.140000"
  482. fmt::format("{:-f}; {:-f}", 3.14, -3.14); // show only the minus -- same as '{:f}; {:f}'
  483. // Result: "3.140000; -3.140000"
  484. Replacing ``%x`` and ``%o`` and converting the value to different bases::
  485. fmt::format("int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
  486. // Result: "int: 42; hex: 2a; oct: 52; bin: 101010"
  487. // with 0x or 0 or 0b as prefix:
  488. fmt::format("int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}", 42);
  489. // Result: "int: 42; hex: 0x2a; oct: 052; bin: 0b101010"
  490. Padded hex byte with prefix and always prints both hex characters::
  491. fmt::format("{:#04x}", 0);
  492. // Result: "0x00"
  493. Box drawing using Unicode fill::
  494. fmt::print(
  495. "┌{0:─^{2}}┐\n"
  496. "│{1: ^{2}}│\n"
  497. "└{0:─^{2}}┘\n", "", "Hello, world!", 20);
  498. prints::
  499. ┌────────────────────┐
  500. │ Hello, world! │
  501. └────────────────────┘
  502. Using type-specific formatting::
  503. #include <fmt/chrono.h>
  504. auto t = tm();
  505. t.tm_year = 2010 - 1900;
  506. t.tm_mon = 7;
  507. t.tm_mday = 4;
  508. t.tm_hour = 12;
  509. t.tm_min = 15;
  510. t.tm_sec = 58;
  511. fmt::print("{:%Y-%m-%d %H:%M:%S}", t);
  512. // Prints: 2010-08-04 12:15:58
  513. Using the comma as a thousands separator::
  514. #include <fmt/format.h>
  515. auto s = fmt::format(std::locale("en_US.UTF-8"), "{:L}", 1234567890);
  516. // s == "1,234,567,890"
  517. .. ifconfig:: False
  518. Nesting arguments and more complex examples::
  519. >>> for align, text in zip('<^>', ['left', 'center', 'right']):
  520. ... '{0:{fill}{align}16}") << text, fill=align, align=align)
  521. ...
  522. 'left<<<<<<<<<<<<'
  523. '^^^^^center^^^^^'
  524. '>>>>>>>>>>>right'
  525. >>>
  526. >>> octets = [192, 168, 0, 1]
  527. Format("{:02X}{:02X}{:02X}{:02X}") << *octets)
  528. 'C0A80001'
  529. >>> int(_, 16)
  530. 3232235521
  531. >>>
  532. >>> width = 5
  533. >>> for num in range(5,12):
  534. ... for base in 'dXob':
  535. ... print('{0:{width}{base}}") << num, base=base, width=width), end=' ')
  536. ... print()
  537. ...
  538. 5 5 5 101
  539. 6 6 6 110
  540. 7 7 7 111
  541. 8 8 10 1000
  542. 9 9 11 1001
  543. 10 A 12 1010
  544. 11 B 13 1011