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