1:mod:`string` --- Common string operations
2==========================================
3
4.. module:: string
5   :synopsis: Common string operations.
6
7**Source code:** :source:`Lib/string.py`
8
9--------------
10
11
12.. seealso::
13
14   :ref:`textseq`
15
16   :ref:`string-methods`
17
18String constants
19----------------
20
21The constants defined in this module are:
22
23
24.. data:: ascii_letters
25
26   The concatenation of the :const:`ascii_lowercase` and :const:`ascii_uppercase`
27   constants described below.  This value is not locale-dependent.
28
29
30.. data:: ascii_lowercase
31
32   The lowercase letters ``'abcdefghijklmnopqrstuvwxyz'``.  This value is not
33   locale-dependent and will not change.
34
35
36.. data:: ascii_uppercase
37
38   The uppercase letters ``'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``.  This value is not
39   locale-dependent and will not change.
40
41
42.. data:: digits
43
44   The string ``'0123456789'``.
45
46
47.. data:: hexdigits
48
49   The string ``'0123456789abcdefABCDEF'``.
50
51
52.. data:: octdigits
53
54   The string ``'01234567'``.
55
56
57.. data:: punctuation
58
59   String of ASCII characters which are considered punctuation characters
60   in the ``C`` locale: ``!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~``.
61
62.. data:: printable
63
64   String of ASCII characters which are considered printable.  This is a
65   combination of :const:`digits`, :const:`ascii_letters`, :const:`punctuation`,
66   and :const:`whitespace`.
67
68
69.. data:: whitespace
70
71   A string containing all ASCII characters that are considered whitespace.
72   This includes the characters space, tab, linefeed, return, formfeed, and
73   vertical tab.
74
75
76.. _string-formatting:
77
78Custom String Formatting
79------------------------
80
81The built-in string class provides the ability to do complex variable
82substitutions and value formatting via the :meth:`~str.format` method described in
83:pep:`3101`.  The :class:`Formatter` class in the :mod:`string` module allows
84you to create and customize your own string formatting behaviors using the same
85implementation as the built-in :meth:`~str.format` method.
86
87
88.. class:: Formatter
89
90   The :class:`Formatter` class has the following public methods:
91
92   .. method:: format(format_string, /, *args, **kwargs)
93
94      The primary API method.  It takes a format string and
95      an arbitrary set of positional and keyword arguments.
96      It is just a wrapper that calls :meth:`vformat`.
97
98      .. versionchanged:: 3.7
99         A format string argument is now :ref:`positional-only
100         <positional-only_parameter>`.
101
102   .. method:: vformat(format_string, args, kwargs)
103
104      This function does the actual work of formatting.  It is exposed as a
105      separate function for cases where you want to pass in a predefined
106      dictionary of arguments, rather than unpacking and repacking the
107      dictionary as individual arguments using the ``*args`` and ``**kwargs``
108      syntax.  :meth:`vformat` does the work of breaking up the format string
109      into character data and replacement fields.  It calls the various
110      methods described below.
111
112   In addition, the :class:`Formatter` defines a number of methods that are
113   intended to be replaced by subclasses:
114
115   .. method:: parse(format_string)
116
117      Loop over the format_string and return an iterable of tuples
118      (*literal_text*, *field_name*, *format_spec*, *conversion*).  This is used
119      by :meth:`vformat` to break the string into either literal text, or
120      replacement fields.
121
122      The values in the tuple conceptually represent a span of literal text
123      followed by a single replacement field.  If there is no literal text
124      (which can happen if two replacement fields occur consecutively), then
125      *literal_text* will be a zero-length string.  If there is no replacement
126      field, then the values of *field_name*, *format_spec* and *conversion*
127      will be ``None``.
128
129   .. method:: get_field(field_name, args, kwargs)
130
131      Given *field_name* as returned by :meth:`parse` (see above), convert it to
132      an object to be formatted.  Returns a tuple (obj, used_key).  The default
133      version takes strings of the form defined in :pep:`3101`, such as
134      "0[name]" or "label.title".  *args* and *kwargs* are as passed in to
135      :meth:`vformat`.  The return value *used_key* has the same meaning as the
136      *key* parameter to :meth:`get_value`.
137
138   .. method:: get_value(key, args, kwargs)
139
140      Retrieve a given field value.  The *key* argument will be either an
141      integer or a string.  If it is an integer, it represents the index of the
142      positional argument in *args*; if it is a string, then it represents a
143      named argument in *kwargs*.
144
145      The *args* parameter is set to the list of positional arguments to
146      :meth:`vformat`, and the *kwargs* parameter is set to the dictionary of
147      keyword arguments.
148
149      For compound field names, these functions are only called for the first
150      component of the field name; subsequent components are handled through
151      normal attribute and indexing operations.
152
153      So for example, the field expression '0.name' would cause
154      :meth:`get_value` to be called with a *key* argument of 0.  The ``name``
155      attribute will be looked up after :meth:`get_value` returns by calling the
156      built-in :func:`getattr` function.
157
158      If the index or keyword refers to an item that does not exist, then an
159      :exc:`IndexError` or :exc:`KeyError` should be raised.
160
161   .. method:: check_unused_args(used_args, args, kwargs)
162
163      Implement checking for unused arguments if desired.  The arguments to this
164      function is the set of all argument keys that were actually referred to in
165      the format string (integers for positional arguments, and strings for
166      named arguments), and a reference to the *args* and *kwargs* that was
167      passed to vformat.  The set of unused args can be calculated from these
168      parameters.  :meth:`check_unused_args` is assumed to raise an exception if
169      the check fails.
170
171   .. method:: format_field(value, format_spec)
172
173      :meth:`format_field` simply calls the global :func:`format` built-in.  The
174      method is provided so that subclasses can override it.
175
176   .. method:: convert_field(value, conversion)
177
178      Converts the value (returned by :meth:`get_field`) given a conversion type
179      (as in the tuple returned by the :meth:`parse` method).  The default
180      version understands 's' (str), 'r' (repr) and 'a' (ascii) conversion
181      types.
182
183
184.. _formatstrings:
185
186Format String Syntax
187--------------------
188
189The :meth:`str.format` method and the :class:`Formatter` class share the same
190syntax for format strings (although in the case of :class:`Formatter`,
191subclasses can define their own format string syntax).  The syntax is
192related to that of :ref:`formatted string literals <f-strings>`, but it is
193less sophisticated and, in particular, does not support arbitrary expressions.
194
195.. index::
196   single: {} (curly brackets); in string formatting
197   single: . (dot); in string formatting
198   single: [] (square brackets); in string formatting
199   single: ! (exclamation); in string formatting
200   single: : (colon); in string formatting
201
202Format strings contain "replacement fields" surrounded by curly braces ``{}``.
203Anything that is not contained in braces is considered literal text, which is
204copied unchanged to the output.  If you need to include a brace character in the
205literal text, it can be escaped by doubling: ``{{`` and ``}}``.
206
207The grammar for a replacement field is as follows:
208
209   .. productionlist:: format-string
210      replacement_field: "{" [`field_name`] ["!" `conversion`] [":" `format_spec`] "}"
211      field_name: arg_name ("." `attribute_name` | "[" `element_index` "]")*
212      arg_name: [`identifier` | `digit`+]
213      attribute_name: `identifier`
214      element_index: `digit`+ | `index_string`
215      index_string: <any source character except "]"> +
216      conversion: "r" | "s" | "a"
217      format_spec: <described in the next section>
218
219In less formal terms, the replacement field can start with a *field_name* that specifies
220the object whose value is to be formatted and inserted
221into the output instead of the replacement field.
222The *field_name* is optionally followed by a  *conversion* field, which is
223preceded by an exclamation point ``'!'``, and a *format_spec*, which is preceded
224by a colon ``':'``.  These specify a non-default format for the replacement value.
225
226See also the :ref:`formatspec` section.
227
228The *field_name* itself begins with an *arg_name* that is either a number or a
229keyword.  If it's a number, it refers to a positional argument, and if it's a keyword,
230it refers to a named keyword argument.  If the numerical arg_names in a format string
231are 0, 1, 2, ... in sequence, they can all be omitted (not just some)
232and the numbers 0, 1, 2, ... will be automatically inserted in that order.
233Because *arg_name* is not quote-delimited, it is not possible to specify arbitrary
234dictionary keys (e.g., the strings ``'10'`` or ``':-]'``) within a format string.
235The *arg_name* can be followed by any number of index or
236attribute expressions. An expression of the form ``'.name'`` selects the named
237attribute using :func:`getattr`, while an expression of the form ``'[index]'``
238does an index lookup using :func:`__getitem__`.
239
240.. versionchanged:: 3.1
241   The positional argument specifiers can be omitted for :meth:`str.format`,
242   so ``'{} {}'.format(a, b)`` is equivalent to ``'{0} {1}'.format(a, b)``.
243
244.. versionchanged:: 3.4
245   The positional argument specifiers can be omitted for :class:`Formatter`.
246
247Some simple format string examples::
248
249   "First, thou shalt count to {0}"  # References first positional argument
250   "Bring me a {}"                   # Implicitly references the first positional argument
251   "From {} to {}"                   # Same as "From {0} to {1}"
252   "My quest is {name}"              # References keyword argument 'name'
253   "Weight in tons {0.weight}"       # 'weight' attribute of first positional arg
254   "Units destroyed: {players[0]}"   # First element of keyword argument 'players'.
255
256The *conversion* field causes a type coercion before formatting.  Normally, the
257job of formatting a value is done by the :meth:`__format__` method of the value
258itself.  However, in some cases it is desirable to force a type to be formatted
259as a string, overriding its own definition of formatting.  By converting the
260value to a string before calling :meth:`__format__`, the normal formatting logic
261is bypassed.
262
263Three conversion flags are currently supported: ``'!s'`` which calls :func:`str`
264on the value, ``'!r'`` which calls :func:`repr` and ``'!a'`` which calls
265:func:`ascii`.
266
267Some examples::
268
269   "Harold's a clever {0!s}"        # Calls str() on the argument first
270   "Bring out the holy {name!r}"    # Calls repr() on the argument first
271   "More {!a}"                      # Calls ascii() on the argument first
272
273The *format_spec* field contains a specification of how the value should be
274presented, including such details as field width, alignment, padding, decimal
275precision and so on.  Each value type can define its own "formatting
276mini-language" or interpretation of the *format_spec*.
277
278Most built-in types support a common formatting mini-language, which is
279described in the next section.
280
281A *format_spec* field can also include nested replacement fields within it.
282These nested replacement fields may contain a field name, conversion flag
283and format specification, but deeper nesting is
284not allowed.  The replacement fields within the
285format_spec are substituted before the *format_spec* string is interpreted.
286This allows the formatting of a value to be dynamically specified.
287
288See the :ref:`formatexamples` section for some examples.
289
290
291.. _formatspec:
292
293Format Specification Mini-Language
294^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
295
296"Format specifications" are used within replacement fields contained within a
297format string to define how individual values are presented (see
298:ref:`formatstrings` and :ref:`f-strings`).
299They can also be passed directly to the built-in
300:func:`format` function.  Each formattable type may define how the format
301specification is to be interpreted.
302
303Most built-in types implement the following options for format specifications,
304although some of the formatting options are only supported by the numeric types.
305
306A general convention is that an empty format specification produces
307the same result as if you had called :func:`str` on the value. A
308non-empty format specification typically modifies the result.
309
310The general form of a *standard format specifier* is:
311
312.. productionlist:: format-spec
313   format_spec: [[`fill`]`align`][`sign`]["z"]["#"]["0"][`width`][`grouping_option`]["." `precision`][`type`]
314   fill: <any character>
315   align: "<" | ">" | "=" | "^"
316   sign: "+" | "-" | " "
317   width: `digit`+
318   grouping_option: "_" | ","
319   precision: `digit`+
320   type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
321
322If a valid *align* value is specified, it can be preceded by a *fill*
323character that can be any character and defaults to a space if omitted.
324It is not possible to use a literal curly brace ("``{``" or "``}``") as
325the *fill* character in a :ref:`formatted string literal
326<f-strings>` or when using the :meth:`str.format`
327method.  However, it is possible to insert a curly brace
328with a nested replacement field.  This limitation doesn't
329affect the :func:`format` function.
330
331The meaning of the various alignment options is as follows:
332
333   .. index::
334      single: < (less); in string formatting
335      single: > (greater); in string formatting
336      single: = (equals); in string formatting
337      single: ^ (caret); in string formatting
338
339   +---------+----------------------------------------------------------+
340   | Option  | Meaning                                                  |
341   +=========+==========================================================+
342   | ``'<'`` | Forces the field to be left-aligned within the available |
343   |         | space (this is the default for most objects).            |
344   +---------+----------------------------------------------------------+
345   | ``'>'`` | Forces the field to be right-aligned within the          |
346   |         | available space (this is the default for numbers).       |
347   +---------+----------------------------------------------------------+
348   | ``'='`` | Forces the padding to be placed after the sign (if any)  |
349   |         | but before the digits.  This is used for printing fields |
350   |         | in the form '+000000120'. This alignment option is only  |
351   |         | valid for numeric types.  It becomes the default for     |
352   |         | numbers when '0' immediately precedes the field width.   |
353   +---------+----------------------------------------------------------+
354   | ``'^'`` | Forces the field to be centered within the available     |
355   |         | space.                                                   |
356   +---------+----------------------------------------------------------+
357
358Note that unless a minimum field width is defined, the field width will always
359be the same size as the data to fill it, so that the alignment option has no
360meaning in this case.
361
362The *sign* option is only valid for number types, and can be one of the
363following:
364
365   .. index::
366      single: + (plus); in string formatting
367      single: - (minus); in string formatting
368      single: space; in string formatting
369
370   +---------+----------------------------------------------------------+
371   | Option  | Meaning                                                  |
372   +=========+==========================================================+
373   | ``'+'`` | indicates that a sign should be used for both            |
374   |         | positive as well as negative numbers.                    |
375   +---------+----------------------------------------------------------+
376   | ``'-'`` | indicates that a sign should be used only for negative   |
377   |         | numbers (this is the default behavior).                  |
378   +---------+----------------------------------------------------------+
379   | space   | indicates that a leading space should be used on         |
380   |         | positive numbers, and a minus sign on negative numbers.  |
381   +---------+----------------------------------------------------------+
382
383
384.. index:: single: z; in string formatting
385
386The ``'z'`` option coerces negative zero floating-point values to positive
387zero after rounding to the format precision.  This option is only valid for
388floating-point presentation types.
389
390.. versionchanged:: 3.11
391   Added the ``'z'`` option (see also :pep:`682`).
392
393.. index:: single: # (hash); in string formatting
394
395The ``'#'`` option causes the "alternate form" to be used for the
396conversion.  The alternate form is defined differently for different
397types.  This option is only valid for integer, float and complex
398types. For integers, when binary, octal, or hexadecimal output
399is used, this option adds the respective prefix ``'0b'``, ``'0o'``,
400``'0x'``, or ``'0X'`` to the output value. For float and complex the
401alternate form causes the result of the conversion to always contain a
402decimal-point character, even if no digits follow it. Normally, a
403decimal-point character appears in the result of these conversions
404only if a digit follows it. In addition, for ``'g'`` and ``'G'``
405conversions, trailing zeros are not removed from the result.
406
407.. index:: single: , (comma); in string formatting
408
409The ``','`` option signals the use of a comma for a thousands separator.
410For a locale aware separator, use the ``'n'`` integer presentation type
411instead.
412
413.. versionchanged:: 3.1
414   Added the ``','`` option (see also :pep:`378`).
415
416.. index:: single: _ (underscore); in string formatting
417
418The ``'_'`` option signals the use of an underscore for a thousands
419separator for floating point presentation types and for integer
420presentation type ``'d'``.  For integer presentation types ``'b'``,
421``'o'``, ``'x'``, and ``'X'``, underscores will be inserted every 4
422digits.  For other presentation types, specifying this option is an
423error.
424
425.. versionchanged:: 3.6
426   Added the ``'_'`` option (see also :pep:`515`).
427
428*width* is a decimal integer defining the minimum total field width,
429including any prefixes, separators, and other formatting characters.
430If not specified, then the field width will be determined by the content.
431
432When no explicit alignment is given, preceding the *width* field by a zero
433(``'0'``) character enables
434sign-aware zero-padding for numeric types.  This is equivalent to a *fill*
435character of ``'0'`` with an *alignment* type of ``'='``.
436
437.. versionchanged:: 3.10
438   Preceding the *width* field by ``'0'`` no longer affects the default
439   alignment for strings.
440
441The *precision* is a decimal integer indicating how many digits should be
442displayed after the decimal point for presentation types
443``'f'`` and ``'F'``, or before and after the decimal point for presentation
444types ``'g'`` or ``'G'``.  For string presentation types the field
445indicates the maximum field size - in other words, how many characters will be
446used from the field content.  The *precision* is not allowed for integer
447presentation types.
448
449Finally, the *type* determines how the data should be presented.
450
451The available string presentation types are:
452
453   +---------+----------------------------------------------------------+
454   | Type    | Meaning                                                  |
455   +=========+==========================================================+
456   | ``'s'`` | String format. This is the default type for strings and  |
457   |         | may be omitted.                                          |
458   +---------+----------------------------------------------------------+
459   | None    | The same as ``'s'``.                                     |
460   +---------+----------------------------------------------------------+
461
462The available integer presentation types are:
463
464   +---------+----------------------------------------------------------+
465   | Type    | Meaning                                                  |
466   +=========+==========================================================+
467   | ``'b'`` | Binary format. Outputs the number in base 2.             |
468   +---------+----------------------------------------------------------+
469   | ``'c'`` | Character. Converts the integer to the corresponding     |
470   |         | unicode character before printing.                       |
471   +---------+----------------------------------------------------------+
472   | ``'d'`` | Decimal Integer. Outputs the number in base 10.          |
473   +---------+----------------------------------------------------------+
474   | ``'o'`` | Octal format. Outputs the number in base 8.              |
475   +---------+----------------------------------------------------------+
476   | ``'x'`` | Hex format. Outputs the number in base 16, using         |
477   |         | lower-case letters for the digits above 9.               |
478   +---------+----------------------------------------------------------+
479   | ``'X'`` | Hex format. Outputs the number in base 16, using         |
480   |         | upper-case letters for the digits above 9.               |
481   |         | In case ``'#'`` is specified, the prefix ``'0x'`` will   |
482   |         | be upper-cased to ``'0X'`` as well.                      |
483   +---------+----------------------------------------------------------+
484   | ``'n'`` | Number. This is the same as ``'d'``, except that it uses |
485   |         | the current locale setting to insert the appropriate     |
486   |         | number separator characters.                             |
487   +---------+----------------------------------------------------------+
488   | None    | The same as ``'d'``.                                     |
489   +---------+----------------------------------------------------------+
490
491In addition to the above presentation types, integers can be formatted
492with the floating point presentation types listed below (except
493``'n'`` and ``None``). When doing so, :func:`float` is used to convert the
494integer to a floating point number before formatting.
495
496The available presentation types for :class:`float` and
497:class:`~decimal.Decimal` values are:
498
499   +---------+----------------------------------------------------------+
500   | Type    | Meaning                                                  |
501   +=========+==========================================================+
502   | ``'e'`` | Scientific notation. For a given precision ``p``,        |
503   |         | formats the number in scientific notation with the       |
504   |         | letter 'e' separating the coefficient from the exponent. |
505   |         | The coefficient has one digit before and ``p`` digits    |
506   |         | after the decimal point, for a total of ``p + 1``        |
507   |         | significant digits. With no precision given, uses a      |
508   |         | precision of ``6`` digits after the decimal point for    |
509   |         | :class:`float`, and shows all coefficient digits         |
510   |         | for :class:`~decimal.Decimal`. If no digits follow the   |
511   |         | decimal point, the decimal point is also removed unless  |
512   |         | the ``#`` option is used.                                |
513   +---------+----------------------------------------------------------+
514   | ``'E'`` | Scientific notation. Same as ``'e'`` except it uses      |
515   |         | an upper case 'E' as the separator character.            |
516   +---------+----------------------------------------------------------+
517   | ``'f'`` | Fixed-point notation. For a given precision ``p``,       |
518   |         | formats the number as a decimal number with exactly      |
519   |         | ``p`` digits following the decimal point. With no        |
520   |         | precision given, uses a precision of ``6`` digits after  |
521   |         | the decimal point for :class:`float`, and uses a         |
522   |         | precision large enough to show all coefficient digits    |
523   |         | for :class:`~decimal.Decimal`. If no digits follow the   |
524   |         | decimal point, the decimal point is also removed unless  |
525   |         | the ``#`` option is used.                                |
526   +---------+----------------------------------------------------------+
527   | ``'F'`` | Fixed-point notation. Same as ``'f'``, but converts      |
528   |         | ``nan`` to  ``NAN`` and ``inf`` to ``INF``.              |
529   +---------+----------------------------------------------------------+
530   | ``'g'`` | General format.  For a given precision ``p >= 1``,       |
531   |         | this rounds the number to ``p`` significant digits and   |
532   |         | then formats the result in either fixed-point format     |
533   |         | or in scientific notation, depending on its magnitude.   |
534   |         | A precision of ``0`` is treated as equivalent to a       |
535   |         | precision of ``1``.                                      |
536   |         |                                                          |
537   |         | The precise rules are as follows: suppose that the       |
538   |         | result formatted with presentation type ``'e'`` and      |
539   |         | precision ``p-1`` would have exponent ``exp``.  Then,    |
540   |         | if ``m <= exp < p``, where ``m`` is -4 for floats and -6 |
541   |         | for :class:`Decimals <decimal.Decimal>`, the number is   |
542   |         | formatted with presentation type ``'f'`` and precision   |
543   |         | ``p-1-exp``.  Otherwise, the number is formatted         |
544   |         | with presentation type ``'e'`` and precision ``p-1``.    |
545   |         | In both cases insignificant trailing zeros are removed   |
546   |         | from the significand, and the decimal point is also      |
547   |         | removed if there are no remaining digits following it,   |
548   |         | unless the ``'#'`` option is used.                       |
549   |         |                                                          |
550   |         | With no precision given, uses a precision of ``6``       |
551   |         | significant digits for :class:`float`. For               |
552   |         | :class:`~decimal.Decimal`, the coefficient of the result |
553   |         | is formed from the coefficient digits of the value;      |
554   |         | scientific notation is used for values smaller than      |
555   |         | ``1e-6`` in absolute value and values where the place    |
556   |         | value of the least significant digit is larger than 1,   |
557   |         | and fixed-point notation is used otherwise.              |
558   |         |                                                          |
559   |         | Positive and negative infinity, positive and negative    |
560   |         | zero, and nans, are formatted as ``inf``, ``-inf``,      |
561   |         | ``0``, ``-0`` and ``nan`` respectively, regardless of    |
562   |         | the precision.                                           |
563   +---------+----------------------------------------------------------+
564   | ``'G'`` | General format. Same as ``'g'`` except switches to       |
565   |         | ``'E'`` if the number gets too large. The                |
566   |         | representations of infinity and NaN are uppercased, too. |
567   +---------+----------------------------------------------------------+
568   | ``'n'`` | Number. This is the same as ``'g'``, except that it uses |
569   |         | the current locale setting to insert the appropriate     |
570   |         | number separator characters.                             |
571   +---------+----------------------------------------------------------+
572   | ``'%'`` | Percentage. Multiplies the number by 100 and displays    |
573   |         | in fixed (``'f'``) format, followed by a percent sign.   |
574   +---------+----------------------------------------------------------+
575   | None    | For :class:`float` this is the same as ``'g'``, except   |
576   |         | that when fixed-point notation is used to format the     |
577   |         | result, it always includes at least one digit past the   |
578   |         | decimal point. The precision used is as large as needed  |
579   |         | to represent the given value faithfully.                 |
580   |         |                                                          |
581   |         | For :class:`~decimal.Decimal`, this is the same as       |
582   |         | either ``'g'`` or ``'G'`` depending on the value of      |
583   |         | ``context.capitals`` for the current decimal context.    |
584   |         |                                                          |
585   |         | The overall effect is to match the output of :func:`str` |
586   |         | as altered by the other format modifiers.                |
587   +---------+----------------------------------------------------------+
588
589
590.. _formatexamples:
591
592Format examples
593^^^^^^^^^^^^^^^
594
595This section contains examples of the :meth:`str.format` syntax and
596comparison with the old ``%``-formatting.
597
598In most of the cases the syntax is similar to the old ``%``-formatting, with the
599addition of the ``{}`` and with ``:`` used instead of ``%``.
600For example, ``'%03.2f'`` can be translated to ``'{:03.2f}'``.
601
602The new format syntax also supports new and different options, shown in the
603following examples.
604
605Accessing arguments by position::
606
607   >>> '{0}, {1}, {2}'.format('a', 'b', 'c')
608   'a, b, c'
609   >>> '{}, {}, {}'.format('a', 'b', 'c')  # 3.1+ only
610   'a, b, c'
611   >>> '{2}, {1}, {0}'.format('a', 'b', 'c')
612   'c, b, a'
613   >>> '{2}, {1}, {0}'.format(*'abc')      # unpacking argument sequence
614   'c, b, a'
615   >>> '{0}{1}{0}'.format('abra', 'cad')   # arguments' indices can be repeated
616   'abracadabra'
617
618Accessing arguments by name::
619
620   >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
621   'Coordinates: 37.24N, -115.81W'
622   >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
623   >>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
624   'Coordinates: 37.24N, -115.81W'
625
626Accessing arguments' attributes::
627
628   >>> c = 3-5j
629   >>> ('The complex number {0} is formed from the real part {0.real} '
630   ...  'and the imaginary part {0.imag}.').format(c)
631   'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
632   >>> class Point:
633   ...     def __init__(self, x, y):
634   ...         self.x, self.y = x, y
635   ...     def __str__(self):
636   ...         return 'Point({self.x}, {self.y})'.format(self=self)
637   ...
638   >>> str(Point(4, 2))
639   'Point(4, 2)'
640
641Accessing arguments' items::
642
643   >>> coord = (3, 5)
644   >>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
645   'X: 3;  Y: 5'
646
647Replacing ``%s`` and ``%r``::
648
649   >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
650   "repr() shows quotes: 'test1'; str() doesn't: test2"
651
652Aligning the text and specifying a width::
653
654   >>> '{:<30}'.format('left aligned')
655   'left aligned                  '
656   >>> '{:>30}'.format('right aligned')
657   '                 right aligned'
658   >>> '{:^30}'.format('centered')
659   '           centered           '
660   >>> '{:*^30}'.format('centered')  # use '*' as a fill char
661   '***********centered***********'
662
663Replacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign::
664
665   >>> '{:+f}; {:+f}'.format(3.14, -3.14)  # show it always
666   '+3.140000; -3.140000'
667   >>> '{: f}; {: f}'.format(3.14, -3.14)  # show a space for positive numbers
668   ' 3.140000; -3.140000'
669   >>> '{:-f}; {:-f}'.format(3.14, -3.14)  # show only the minus -- same as '{:f}; {:f}'
670   '3.140000; -3.140000'
671
672Replacing ``%x`` and ``%o`` and converting the value to different bases::
673
674   >>> # format also supports binary numbers
675   >>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
676   'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
677   >>> # with 0x, 0o, or 0b as prefix:
678   >>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
679   'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'
680
681Using the comma as a thousands separator::
682
683   >>> '{:,}'.format(1234567890)
684   '1,234,567,890'
685
686Expressing a percentage::
687
688   >>> points = 19
689   >>> total = 22
690   >>> 'Correct answers: {:.2%}'.format(points/total)
691   'Correct answers: 86.36%'
692
693Using type-specific formatting::
694
695   >>> import datetime
696   >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
697   >>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
698   '2010-07-04 12:15:58'
699
700Nesting arguments and more complex examples::
701
702   >>> for align, text in zip('<^>', ['left', 'center', 'right']):
703   ...     '{0:{fill}{align}16}'.format(text, fill=align, align=align)
704   ...
705   'left<<<<<<<<<<<<'
706   '^^^^^center^^^^^'
707   '>>>>>>>>>>>right'
708   >>>
709   >>> octets = [192, 168, 0, 1]
710   >>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
711   'C0A80001'
712   >>> int(_, 16)
713   3232235521
714   >>>
715   >>> width = 5
716   >>> for num in range(5,12): #doctest: +NORMALIZE_WHITESPACE
717   ...     for base in 'dXob':
718   ...         print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
719   ...     print()
720   ...
721       5     5     5   101
722       6     6     6   110
723       7     7     7   111
724       8     8    10  1000
725       9     9    11  1001
726      10     A    12  1010
727      11     B    13  1011
728
729
730
731.. _template-strings:
732
733Template strings
734----------------
735
736Template strings provide simpler string substitutions as described in
737:pep:`292`.  A primary use case for template strings is for
738internationalization (i18n) since in that context, the simpler syntax and
739functionality makes it easier to translate than other built-in string
740formatting facilities in Python.  As an example of a library built on template
741strings for i18n, see the
742`flufl.i18n <https://flufli18n.readthedocs.io/en/latest/>`_ package.
743
744.. index:: single: $ (dollar); in template strings
745
746Template strings support ``$``-based substitutions, using the following rules:
747
748* ``$$`` is an escape; it is replaced with a single ``$``.
749
750* ``$identifier`` names a substitution placeholder matching a mapping key of
751  ``"identifier"``.  By default, ``"identifier"`` is restricted to any
752  case-insensitive ASCII alphanumeric string (including underscores) that
753  starts with an underscore or ASCII letter.  The first non-identifier
754  character after the ``$`` character terminates this placeholder
755  specification.
756
757* ``${identifier}`` is equivalent to ``$identifier``.  It is required when
758  valid identifier characters follow the placeholder but are not part of the
759  placeholder, such as ``"${noun}ification"``.
760
761Any other appearance of ``$`` in the string will result in a :exc:`ValueError`
762being raised.
763
764The :mod:`string` module provides a :class:`Template` class that implements
765these rules.  The methods of :class:`Template` are:
766
767
768.. class:: Template(template)
769
770   The constructor takes a single argument which is the template string.
771
772
773   .. method:: substitute(mapping={}, /, **kwds)
774
775      Performs the template substitution, returning a new string.  *mapping* is
776      any dictionary-like object with keys that match the placeholders in the
777      template.  Alternatively, you can provide keyword arguments, where the
778      keywords are the placeholders.  When both *mapping* and *kwds* are given
779      and there are duplicates, the placeholders from *kwds* take precedence.
780
781
782   .. method:: safe_substitute(mapping={}, /, **kwds)
783
784      Like :meth:`substitute`, except that if placeholders are missing from
785      *mapping* and *kwds*, instead of raising a :exc:`KeyError` exception, the
786      original placeholder will appear in the resulting string intact.  Also,
787      unlike with :meth:`substitute`, any other appearances of the ``$`` will
788      simply return ``$`` instead of raising :exc:`ValueError`.
789
790      While other exceptions may still occur, this method is called "safe"
791      because it always tries to return a usable string instead of
792      raising an exception.  In another sense, :meth:`safe_substitute` may be
793      anything other than safe, since it will silently ignore malformed
794      templates containing dangling delimiters, unmatched braces, or
795      placeholders that are not valid Python identifiers.
796
797
798   .. method:: is_valid()
799
800      Returns false if the template has invalid placeholders that will cause
801      :meth:`substitute` to raise :exc:`ValueError`.
802
803      .. versionadded:: 3.11
804
805
806   .. method:: get_identifiers()
807
808      Returns a list of the valid identifiers in the template, in the order
809      they first appear, ignoring any invalid identifiers.
810
811      .. versionadded:: 3.11
812
813   :class:`Template` instances also provide one public data attribute:
814
815   .. attribute:: template
816
817      This is the object passed to the constructor's *template* argument.  In
818      general, you shouldn't change it, but read-only access is not enforced.
819
820Here is an example of how to use a Template::
821
822   >>> from string import Template
823   >>> s = Template('$who likes $what')
824   >>> s.substitute(who='tim', what='kung pao')
825   'tim likes kung pao'
826   >>> d = dict(who='tim')
827   >>> Template('Give $who $100').substitute(d)
828   Traceback (most recent call last):
829   ...
830   ValueError: Invalid placeholder in string: line 1, col 11
831   >>> Template('$who likes $what').substitute(d)
832   Traceback (most recent call last):
833   ...
834   KeyError: 'what'
835   >>> Template('$who likes $what').safe_substitute(d)
836   'tim likes $what'
837
838Advanced usage: you can derive subclasses of :class:`Template` to customize
839the placeholder syntax, delimiter character, or the entire regular expression
840used to parse template strings.  To do this, you can override these class
841attributes:
842
843* *delimiter* -- This is the literal string describing a placeholder
844  introducing delimiter.  The default value is ``$``.  Note that this should
845  *not* be a regular expression, as the implementation will call
846  :meth:`re.escape` on this string as needed.  Note further that you cannot
847  change the delimiter after class creation (i.e. a different delimiter must
848  be set in the subclass's class namespace).
849
850* *idpattern* -- This is the regular expression describing the pattern for
851  non-braced placeholders.  The default value is the regular expression
852  ``(?a:[_a-z][_a-z0-9]*)``.  If this is given and *braceidpattern* is
853  ``None`` this pattern will also apply to braced placeholders.
854
855  .. note::
856
857     Since default *flags* is ``re.IGNORECASE``, pattern ``[a-z]`` can match
858     with some non-ASCII characters. That's why we use the local ``a`` flag
859     here.
860
861  .. versionchanged:: 3.7
862     *braceidpattern* can be used to define separate patterns used inside and
863     outside the braces.
864
865* *braceidpattern* -- This is like *idpattern* but describes the pattern for
866  braced placeholders.  Defaults to ``None`` which means to fall back to
867  *idpattern* (i.e. the same pattern is used both inside and outside braces).
868  If given, this allows you to define different patterns for braced and
869  unbraced placeholders.
870
871  .. versionadded:: 3.7
872
873* *flags* -- The regular expression flags that will be applied when compiling
874  the regular expression used for recognizing substitutions.  The default value
875  is ``re.IGNORECASE``.  Note that ``re.VERBOSE`` will always be added to the
876  flags, so custom *idpattern*\ s must follow conventions for verbose regular
877  expressions.
878
879  .. versionadded:: 3.2
880
881Alternatively, you can provide the entire regular expression pattern by
882overriding the class attribute *pattern*.  If you do this, the value must be a
883regular expression object with four named capturing groups.  The capturing
884groups correspond to the rules given above, along with the invalid placeholder
885rule:
886
887* *escaped* -- This group matches the escape sequence, e.g. ``$$``, in the
888  default pattern.
889
890* *named* -- This group matches the unbraced placeholder name; it should not
891  include the delimiter in capturing group.
892
893* *braced* -- This group matches the brace enclosed placeholder name; it should
894  not include either the delimiter or braces in the capturing group.
895
896* *invalid* -- This group matches any other delimiter pattern (usually a single
897  delimiter), and it should appear last in the regular expression.
898
899The methods on this class will raise :exc:`ValueError` if the pattern matches
900the template without one of these named groups matching.
901
902
903Helper functions
904----------------
905
906.. function:: capwords(s, sep=None)
907
908   Split the argument into words using :meth:`str.split`, capitalize each word
909   using :meth:`str.capitalize`, and join the capitalized words using
910   :meth:`str.join`.  If the optional second argument *sep* is absent
911   or ``None``, runs of whitespace characters are replaced by a single space
912   and leading and trailing whitespace are removed, otherwise *sep* is used to
913   split and join the words.
914