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