blob: 55913f8c07f50419c51f1866d41fbcdf0aa0c8bf [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`string` --- Common string operations
2==========================================
3
4.. module:: string
5 :synopsis: Common string operations.
6
Éric Araujo19f9b712011-08-19 00:49:18 +02007**Source code:** :source:`Lib/string.py`
8
9--------------
Georg Brandl116aa622007-08-15 14:28:22 +000010
Éric Araujo6e6cb8e2010-11-16 19:13:50 +000011.. seealso::
12
Ezio Melottia6229e62012-10-12 10:59:14 +030013 :ref:`textseq`
Georg Brandlb30f3302011-01-06 09:23:56 +000014
15 :ref:`string-methods`
16
Georg Brandl116aa622007-08-15 14:28:22 +000017String 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
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
Georg Brandl50767402008-11-22 08:31:09 +000071 A string containing all ASCII characters that are considered whitespace.
Georg Brandl116aa622007-08-15 14:28:22 +000072 This includes the characters space, tab, linefeed, return, formfeed, and
73 vertical tab.
74
75
Georg Brandl4b491312007-08-31 09:22:56 +000076.. _string-formatting:
77
Martin Panterd5db1472016-02-08 01:34:09 +000078Custom String Formatting
79------------------------
Georg Brandl4b491312007-08-31 09:22:56 +000080
Benjamin Peterson50923f92008-05-25 19:45:17 +000081The built-in string class provides the ability to do complex variable
Martin Panterd5db1472016-02-08 01:34:09 +000082substitutions and value formatting via the :meth:`~str.format` method described in
Benjamin Peterson50923f92008-05-25 19:45:17 +000083: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
Martin Panterd5db1472016-02-08 01:34:09 +000085implementation as the built-in :meth:`~str.format` method.
Georg Brandl4b491312007-08-31 09:22:56 +000086
Benjamin Peterson1baf4652009-12-31 03:11:23 +000087
Georg Brandl4b491312007-08-31 09:22:56 +000088.. class:: Formatter
89
90 The :class:`Formatter` class has the following public methods:
91
Georg Brandl8e490de2011-01-24 19:53:18 +000092 .. method:: format(format_string, *args, **kwargs)
Georg Brandl4b491312007-08-31 09:22:56 +000093
Martin Panterd5db1472016-02-08 01:34:09 +000094 The primary API method. It takes a format string and
R David Murraye56bf972012-08-19 17:26:34 -040095 an arbitrary set of positional and keyword arguments.
Martin Panterd5db1472016-02-08 01:34:09 +000096 It is just a wrapper that calls :meth:`vformat`.
Georg Brandl4b491312007-08-31 09:22:56 +000097
Serhiy Storchaka009b0a12017-01-13 09:10:51 +020098 .. versionchanged:: 3.7
99 A format string argument is now :ref:`positional-only
100 <positional-only_parameter>`.
Serhiy Storchakab876df42015-03-24 22:30:46 +0200101
Georg Brandl4b491312007-08-31 09:22:56 +0000102 .. method:: vformat(format_string, args, kwargs)
Georg Brandl48310cd2009-01-03 21:18:54 +0000103
Georg Brandl4b491312007-08-31 09:22:56 +0000104 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
Ezio Melotti28c88f42012-11-27 19:17:57 +0200107 dictionary as individual arguments using the ``*args`` and ``**kwargs``
R David Murraye56bf972012-08-19 17:26:34 -0400108 syntax. :meth:`vformat` does the work of breaking up the format string
109 into character data and replacement fields. It calls the various
Georg Brandl4b491312007-08-31 09:22:56 +0000110 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)
Georg Brandl48310cd2009-01-03 21:18:54 +0000116
Georg Brandl4b491312007-08-31 09:22:56 +0000117 Loop over the format_string and return an iterable of tuples
118 (*literal_text*, *field_name*, *format_spec*, *conversion*). This is used
Georg Brandl70cd7bc2010-10-26 19:31:06 +0000119 by :meth:`vformat` to break the string into either literal text, or
Georg Brandl4b491312007-08-31 09:22:56 +0000120 replacement fields.
Georg Brandl48310cd2009-01-03 21:18:54 +0000121
Georg Brandl4b491312007-08-31 09:22:56 +0000122 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
Eric Smith9d4ba392007-09-02 15:33:26 +0000129 .. method:: get_field(field_name, args, kwargs)
Georg Brandl4b491312007-08-31 09:22:56 +0000130
131 Given *field_name* as returned by :meth:`parse` (see above), convert it to
Georg Brandl7f13e6b2007-08-31 10:37:15 +0000132 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`.
Georg Brandl4b491312007-08-31 09:22:56 +0000137
138 .. method:: get_value(key, args, kwargs)
Georg Brandl48310cd2009-01-03 21:18:54 +0000139
Georg Brandl4b491312007-08-31 09:22:56 +0000140 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
Georg Brandl7cb13192010-08-03 12:06:29 +0000168 parameters. :meth:`check_unused_args` is assumed to raise an exception if
Georg Brandl4b491312007-08-31 09:22:56 +0000169 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)
Georg Brandl48310cd2009-01-03 21:18:54 +0000177
Georg Brandl4b491312007-08-31 09:22:56 +0000178 Converts the value (returned by :meth:`get_field`) given a conversion type
Ezio Melottid2191e02010-07-02 23:18:51 +0000179 (as in the tuple returned by the :meth:`parse` method). The default
R David Murraye56bf972012-08-19 17:26:34 -0400180 version understands 's' (str), 'r' (repr) and 'a' (ascii) conversion
181 types.
Georg Brandl4b491312007-08-31 09:22:56 +0000182
Georg Brandl4b491312007-08-31 09:22:56 +0000183
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`,
Martin Panterbc1ee462016-02-13 00:41:37 +0000191subclasses can define their own format string syntax). The syntax is
192related to that of :ref:`formatted string literals <f-strings>`, but
193there are differences.
Georg Brandl4b491312007-08-31 09:22:56 +0000194
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300195.. index::
196 single: {; in string formatting
197 single: }; in string formatting
198 single: .; in string formatting
199 single: [; in string formatting
200 single: ]; in string formatting
201 single: !; in string formatting
202 single: :; in string formatting
203
Georg Brandl4b491312007-08-31 09:22:56 +0000204Format strings contain "replacement fields" surrounded by curly braces ``{}``.
205Anything that is not contained in braces is considered literal text, which is
206copied unchanged to the output. If you need to include a brace character in the
207literal text, it can be escaped by doubling: ``{{`` and ``}}``.
208
209The grammar for a replacement field is as follows:
210
211 .. productionlist:: sf
Georg Brandl2f3ed682009-09-01 07:42:40 +0000212 replacement_field: "{" [`field_name`] ["!" `conversion`] [":" `format_spec`] "}"
Eric Smithc4cae322009-04-22 00:53:01 +0000213 field_name: arg_name ("." `attribute_name` | "[" `element_index` "]")*
Mariatta7a561af2018-02-05 04:29:02 -0500214 arg_name: [`identifier` | `digit`+]
Georg Brandl4b491312007-08-31 09:22:56 +0000215 attribute_name: `identifier`
Mariatta7a561af2018-02-05 04:29:02 -0500216 element_index: `digit`+ | `index_string`
Eric Smith2e9f2022010-02-25 14:58:13 +0000217 index_string: <any source character except "]"> +
Benjamin Peterson065ba702008-11-09 01:43:02 +0000218 conversion: "r" | "s" | "a"
Georg Brandl4b491312007-08-31 09:22:56 +0000219 format_spec: <described in the next section>
Georg Brandl48310cd2009-01-03 21:18:54 +0000220
Georg Brandl2f3ed682009-09-01 07:42:40 +0000221In less formal terms, the replacement field can start with a *field_name* that specifies
Eric Smithc4cae322009-04-22 00:53:01 +0000222the object whose value is to be formatted and inserted
223into the output instead of the replacement field.
224The *field_name* is optionally followed by a *conversion* field, which is
Georg Brandl4b491312007-08-31 09:22:56 +0000225preceded by an exclamation point ``'!'``, and a *format_spec*, which is preceded
Eric Smithc4cae322009-04-22 00:53:01 +0000226by a colon ``':'``. These specify a non-default format for the replacement value.
Georg Brandl4b491312007-08-31 09:22:56 +0000227
Ezio Melottid2191e02010-07-02 23:18:51 +0000228See also the :ref:`formatspec` section.
229
Ezio Melottie130a522011-10-19 10:58:56 +0300230The *field_name* itself begins with an *arg_name* that is either a number or a
Eric Smithc4cae322009-04-22 00:53:01 +0000231keyword. If it's a number, it refers to a positional argument, and if it's a keyword,
232it refers to a named keyword argument. If 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.
Éric Araujo29cf58c2011-09-01 18:59:06 +0200235Because *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.
Eric Smithc4cae322009-04-22 00:53:01 +0000237The *arg_name* can be followed by any number of index or
Georg Brandl4b491312007-08-31 09:22:56 +0000238attribute 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 :func:`__getitem__`.
241
Ezio Melottid2191e02010-07-02 23:18:51 +0000242.. versionchanged:: 3.1
Xiang Zhangb9d8ad52018-06-13 09:42:44 +0800243 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`.
Ezio Melottid2191e02010-07-02 23:18:51 +0000248
Georg Brandl4b491312007-08-31 09:22:56 +0000249Some simple format string examples::
250
Serhiy Storchakadba90392016-05-10 12:01:23 +0300251 "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'.
Georg Brandl48310cd2009-01-03 21:18:54 +0000257
Georg Brandl4b491312007-08-31 09:22:56 +0000258The *conversion* field causes a type coercion before formatting. Normally, the
259job of formatting a value is done by the :meth:`__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:`__format__`, the normal formatting logic
263is bypassed.
264
Georg Brandl559e5d72008-06-11 18:37:52 +0000265Three 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`.
Georg Brandl4b491312007-08-31 09:22:56 +0000268
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
Georg Brandl2f3ed682009-09-01 07:42:40 +0000273 "More {!a}" # Calls ascii() on the argument first
Georg Brandl4b491312007-08-31 09:22:56 +0000274
275The *format_spec* field contains a specification of how the value should be
276presented, including such details as field width, alignment, padding, decimal
Eric Smith0f7affe2010-02-15 11:57:31 +0000277precision and so on. Each value type can define its own "formatting
Georg Brandl4b491312007-08-31 09:22:56 +0000278mini-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.
Martin Panterd5db1472016-02-08 01:34:09 +0000284These nested replacement fields may contain a field name, conversion flag
285and format specification, but deeper nesting is
286not allowed. The replacement fields within the
Georg Brandl4b491312007-08-31 09:22:56 +0000287format_spec are substituted before the *format_spec* string is interpreted.
288This allows the formatting of a value to be dynamically specified.
289
Ezio Melottid2191e02010-07-02 23:18:51 +0000290See the :ref:`formatexamples` section for some examples.
Georg Brandl4b491312007-08-31 09:22:56 +0000291
Georg Brandl4b491312007-08-31 09:22:56 +0000292
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
Martin Panterbc1ee462016-02-13 00:41:37 +0000300:ref:`formatstrings` and :ref:`f-strings`).
301They can also be passed directly to the built-in
Georg Brandl4b491312007-08-31 09:22:56 +0000302: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
Eric Smith05c07742010-02-25 14:18:57 +0000308A general convention is that an empty format string (``""``) produces
309the same result as if you had called :func:`str` on the value. A
310non-empty format string typically modifies the result.
Georg Brandl4b491312007-08-31 09:22:56 +0000311
312The general form of a *standard format specifier* is:
313
314.. productionlist:: sf
Eric V. Smithd7665ca2016-09-09 23:13:01 -0400315 format_spec: [[`fill`]`align`][`sign`][#][0][`width`][`grouping_option`][.`precision`][`type`]
Ezio Melottic3184422013-10-21 02:53:07 +0300316 fill: <any character>
Georg Brandl4b491312007-08-31 09:22:56 +0000317 align: "<" | ">" | "=" | "^"
318 sign: "+" | "-" | " "
nathankerr968b5fa282018-02-03 21:42:08 -0800319 width: `digit`+
Eric V. Smithd7665ca2016-09-09 23:13:01 -0400320 grouping_option: "_" | ","
nathankerr968b5fa282018-02-03 21:42:08 -0800321 precision: `digit`+
Eric Smith05c07742010-02-25 14:18:57 +0000322 type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
Georg Brandl48310cd2009-01-03 21:18:54 +0000323
Ezio Melotti2bbdfe72013-11-17 02:47:12 +0200324If a valid *align* value is specified, it can be preceded by a *fill*
Ezio Melottic3184422013-10-21 02:53:07 +0300325character that can be any character and defaults to a space if omitted.
Martin Panterd5db1472016-02-08 01:34:09 +0000326It is not possible to use a literal curly brace ("``{``" or "``}``") as
Martin Panterbc1ee462016-02-13 00:41:37 +0000327the *fill* character in a :ref:`formatted string literal
328<f-strings>` or when using the :meth:`str.format`
Martin Panterd5db1472016-02-08 01:34:09 +0000329method. However, it is possible to insert a curly brace
330with a nested replacement field. This limitation doesn't
Ezio Melottic3184422013-10-21 02:53:07 +0300331affect the :func:`format` function.
Georg Brandl4b491312007-08-31 09:22:56 +0000332
333The meaning of the various alignment options is as follows:
334
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300335 .. index::
336 single: <; in string formatting
337 single: >; in string formatting
338 single: =; in string formatting
339 single: ^; in string formatting
340
Georg Brandl4b491312007-08-31 09:22:56 +0000341 +---------+----------------------------------------------------------+
342 | Option | Meaning |
343 +=========+==========================================================+
344 | ``'<'`` | Forces the field to be left-aligned within the available |
Georg Brandlca583b62011-02-07 12:13:58 +0000345 | | space (this is the default for most objects). |
Georg Brandl4b491312007-08-31 09:22:56 +0000346 +---------+----------------------------------------------------------+
347 | ``'>'`` | Forces the field to be right-aligned within the |
Georg Brandlca583b62011-02-07 12:13:58 +0000348 | | available space (this is the default for numbers). |
Georg Brandl4b491312007-08-31 09:22:56 +0000349 +---------+----------------------------------------------------------+
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 |
Terry Jan Reedy4902c462016-03-20 21:05:57 -0400353 | | valid for numeric types. It becomes the default when '0'|
354 | | immediately precedes the field width. |
Georg Brandl4b491312007-08-31 09:22:56 +0000355 +---------+----------------------------------------------------------+
356 | ``'^'`` | Forces the field to be centered within the available |
357 | | space. |
358 +---------+----------------------------------------------------------+
359
360Note that unless a minimum field width is defined, the field width will always
361be the same size as the data to fill it, so that the alignment option has no
362meaning in this case.
363
364The *sign* option is only valid for number types, and can be one of the
365following:
366
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300367 .. index::
368 single: +; in string formatting
369 single: -; in string formatting
370 single: space; in string formatting
371
Georg Brandl4b491312007-08-31 09:22:56 +0000372 +---------+----------------------------------------------------------+
373 | Option | Meaning |
374 +=========+==========================================================+
375 | ``'+'`` | indicates that a sign should be used for both |
376 | | positive as well as negative numbers. |
377 +---------+----------------------------------------------------------+
378 | ``'-'`` | indicates that a sign should be used only for negative |
379 | | numbers (this is the default behavior). |
380 +---------+----------------------------------------------------------+
381 | space | indicates that a leading space should be used on |
382 | | positive numbers, and a minus sign on negative numbers. |
383 +---------+----------------------------------------------------------+
384
Eric Smith984bb582010-11-25 16:08:06 +0000385
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300386.. index:: single: #; in string formatting
387
Eric Smith984bb582010-11-25 16:08:06 +0000388The ``'#'`` option causes the "alternate form" to be used for the
389conversion. The alternate form is defined differently for different
390types. This option is only valid for integer, float, complex and
391Decimal types. For integers, when binary, octal, or hexadecimal output
392is used, this option adds the prefix respective ``'0b'``, ``'0o'``, or
393``'0x'`` to the output value. For floats, complex and Decimal the
394alternate form causes the result of the conversion to always contain a
395decimal-point character, even if no digits follow it. Normally, a
396decimal-point character appears in the result of these conversions
397only if a digit follows it. In addition, for ``'g'`` and ``'G'``
398conversions, trailing zeros are not removed from the result.
Eric Smithd68af8f2008-07-16 00:15:35 +0000399
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300400.. index:: single: ,; in string formatting
401
Raymond Hettinger6db94702009-07-12 20:49:21 +0000402The ``','`` option signals the use of a comma for a thousands separator.
403For a locale aware separator, use the ``'n'`` integer presentation type
404instead.
405
Ezio Melottid2191e02010-07-02 23:18:51 +0000406.. versionchanged:: 3.1
407 Added the ``','`` option (see also :pep:`378`).
408
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300409.. index:: single: _; in string formatting
410
Eric V. Smith89e1b1a2016-09-09 23:06:47 -0400411The ``'_'`` option signals the use of an underscore for a thousands
412separator for floating point presentation types and for integer
413presentation type ``'d'``. For integer presentation types ``'b'``,
414``'o'``, ``'x'``, and ``'X'``, underscores will be inserted every 4
415digits. For other presentation types, specifying this option is an
416error.
417
418.. versionchanged:: 3.6
419 Added the ``'_'`` option (see also :pep:`515`).
420
Georg Brandl4b491312007-08-31 09:22:56 +0000421*width* is a decimal integer defining the minimum field width. If not
422specified, then the field width will be determined by the content.
423
Terry Jan Reedy4902c462016-03-20 21:05:57 -0400424When no explicit alignment is given, preceding the *width* field by a zero
425(``'0'``) character enables
Terry Jan Reedyf6190c12012-08-17 15:40:46 -0400426sign-aware zero-padding for numeric types. This is equivalent to a *fill*
427character of ``'0'`` with an *alignment* type of ``'='``.
Georg Brandl4b491312007-08-31 09:22:56 +0000428
429The *precision* is a decimal number indicating how many digits should be
Georg Brandl3dbca812008-07-23 16:10:53 +0000430displayed after the decimal point for a floating point value formatted with
431``'f'`` and ``'F'``, or before and after the decimal point for a floating point
432value formatted with ``'g'`` or ``'G'``. For non-number types the field
433indicates the maximum field size - in other words, how many characters will be
Eric Smithe5fffc72009-05-07 19:38:09 +0000434used from the field content. The *precision* is not allowed for integer values.
Georg Brandl4b491312007-08-31 09:22:56 +0000435
436Finally, the *type* determines how the data should be presented.
437
Eric Smith05c07742010-02-25 14:18:57 +0000438The available string presentation types are:
439
440 +---------+----------------------------------------------------------+
441 | Type | Meaning |
442 +=========+==========================================================+
443 | ``'s'`` | String format. This is the default type for strings and |
444 | | may be omitted. |
445 +---------+----------------------------------------------------------+
446 | None | The same as ``'s'``. |
447 +---------+----------------------------------------------------------+
448
Georg Brandl4b491312007-08-31 09:22:56 +0000449The available integer presentation types are:
450
451 +---------+----------------------------------------------------------+
452 | Type | Meaning |
453 +=========+==========================================================+
Eric Smithd68af8f2008-07-16 00:15:35 +0000454 | ``'b'`` | Binary format. Outputs the number in base 2. |
Georg Brandl4b491312007-08-31 09:22:56 +0000455 +---------+----------------------------------------------------------+
456 | ``'c'`` | Character. Converts the integer to the corresponding |
457 | | unicode character before printing. |
458 +---------+----------------------------------------------------------+
459 | ``'d'`` | Decimal Integer. Outputs the number in base 10. |
460 +---------+----------------------------------------------------------+
461 | ``'o'`` | Octal format. Outputs the number in base 8. |
462 +---------+----------------------------------------------------------+
463 | ``'x'`` | Hex format. Outputs the number in base 16, using lower- |
464 | | case letters for the digits above 9. |
465 +---------+----------------------------------------------------------+
466 | ``'X'`` | Hex format. Outputs the number in base 16, using upper- |
467 | | case letters for the digits above 9. |
468 +---------+----------------------------------------------------------+
Eric Smith5e18a202008-05-12 10:01:24 +0000469 | ``'n'`` | Number. This is the same as ``'d'``, except that it uses |
470 | | the current locale setting to insert the appropriate |
471 | | number separator characters. |
472 +---------+----------------------------------------------------------+
Georg Brandl3dbca812008-07-23 16:10:53 +0000473 | None | The same as ``'d'``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000474 +---------+----------------------------------------------------------+
Georg Brandl48310cd2009-01-03 21:18:54 +0000475
Eric Smith05c07742010-02-25 14:18:57 +0000476In addition to the above presentation types, integers can be formatted
477with the floating point presentation types listed below (except
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300478``'n'`` and ``None``). When doing so, :func:`float` is used to convert the
Eric Smith05c07742010-02-25 14:18:57 +0000479integer to a floating point number before formatting.
480
Georg Brandl4b491312007-08-31 09:22:56 +0000481The available presentation types for floating point and decimal values are:
Georg Brandl48310cd2009-01-03 21:18:54 +0000482
Georg Brandl4b491312007-08-31 09:22:56 +0000483 +---------+----------------------------------------------------------+
484 | Type | Meaning |
485 +=========+==========================================================+
486 | ``'e'`` | Exponent notation. Prints the number in scientific |
487 | | notation using the letter 'e' to indicate the exponent. |
Eric V. Smith45fe62d2013-04-15 09:51:54 -0400488 | | The default precision is ``6``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000489 +---------+----------------------------------------------------------+
Eric Smith22b85b32008-07-17 19:18:29 +0000490 | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an |
491 | | upper case 'E' as the separator character. |
Georg Brandl4b491312007-08-31 09:22:56 +0000492 +---------+----------------------------------------------------------+
Terry Jan Reedy28c7f8c2018-08-06 08:41:17 -0400493 | ``'f'`` | Fixed-point notation. Displays the number as a |
494 | | fixed-point number. The default precision is ``6``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000495 +---------+----------------------------------------------------------+
Terry Jan Reedy28c7f8c2018-08-06 08:41:17 -0400496 | ``'F'`` | Fixed-point notation. Same as ``'f'``, but converts |
497 | | ``nan`` to ``NAN`` and ``inf`` to ``INF``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000498 +---------+----------------------------------------------------------+
Mark Dickinsonc70614f2009-10-08 20:05:48 +0000499 | ``'g'`` | General format. For a given precision ``p >= 1``, |
500 | | this rounds the number to ``p`` significant digits and |
501 | | then formats the result in either fixed-point format |
502 | | or in scientific notation, depending on its magnitude. |
503 | | |
504 | | The precise rules are as follows: suppose that the |
505 | | result formatted with presentation type ``'e'`` and |
506 | | precision ``p-1`` would have exponent ``exp``. Then |
507 | | if ``-4 <= exp < p``, the number is formatted |
508 | | with presentation type ``'f'`` and precision |
509 | | ``p-1-exp``. Otherwise, the number is formatted |
510 | | with presentation type ``'e'`` and precision ``p-1``. |
511 | | In both cases insignificant trailing zeros are removed |
512 | | from the significand, and the decimal point is also |
513 | | removed if there are no remaining digits following it. |
514 | | |
Benjamin Peterson73a3f2d2010-10-12 23:07:13 +0000515 | | Positive and negative infinity, positive and negative |
Mark Dickinsonc70614f2009-10-08 20:05:48 +0000516 | | zero, and nans, are formatted as ``inf``, ``-inf``, |
517 | | ``0``, ``-0`` and ``nan`` respectively, regardless of |
518 | | the precision. |
519 | | |
520 | | A precision of ``0`` is treated as equivalent to a |
Eric V. Smith45fe62d2013-04-15 09:51:54 -0400521 | | precision of ``1``. The default precision is ``6``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000522 +---------+----------------------------------------------------------+
523 | ``'G'`` | General format. Same as ``'g'`` except switches to |
Mark Dickinsonc70614f2009-10-08 20:05:48 +0000524 | | ``'E'`` if the number gets too large. The |
525 | | representations of infinity and NaN are uppercased, too. |
Georg Brandl4b491312007-08-31 09:22:56 +0000526 +---------+----------------------------------------------------------+
527 | ``'n'`` | Number. This is the same as ``'g'``, except that it uses |
528 | | the current locale setting to insert the appropriate |
529 | | number separator characters. |
530 +---------+----------------------------------------------------------+
531 | ``'%'`` | Percentage. Multiplies the number by 100 and displays |
532 | | in fixed (``'f'``) format, followed by a percent sign. |
533 +---------+----------------------------------------------------------+
Terry Jan Reedyc6ad5762014-10-06 02:04:33 -0400534 | None | Similar to ``'g'``, except that fixed-point notation, |
535 | | when used, has at least one digit past the decimal point.|
536 | | The default precision is as high as needed to represent |
537 | | the particular value. The overall effect is to match the |
538 | | output of :func:`str` as altered by the other format |
539 | | modifiers. |
Georg Brandl4b491312007-08-31 09:22:56 +0000540 +---------+----------------------------------------------------------+
541
542
Ezio Melottid2191e02010-07-02 23:18:51 +0000543.. _formatexamples:
544
545Format examples
546^^^^^^^^^^^^^^^
547
Martin Panterd5db1472016-02-08 01:34:09 +0000548This section contains examples of the :meth:`str.format` syntax and
549comparison with the old ``%``-formatting.
Ezio Melottid2191e02010-07-02 23:18:51 +0000550
551In most of the cases the syntax is similar to the old ``%``-formatting, with the
552addition of the ``{}`` and with ``:`` used instead of ``%``.
553For example, ``'%03.2f'`` can be translated to ``'{:03.2f}'``.
554
555The new format syntax also supports new and different options, shown in the
556follow examples.
557
558Accessing arguments by position::
559
560 >>> '{0}, {1}, {2}'.format('a', 'b', 'c')
561 'a, b, c'
562 >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only
563 'a, b, c'
564 >>> '{2}, {1}, {0}'.format('a', 'b', 'c')
565 'c, b, a'
566 >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence
567 'c, b, a'
568 >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated
569 'abracadabra'
570
571Accessing arguments by name::
572
573 >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
574 'Coordinates: 37.24N, -115.81W'
575 >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
576 >>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
577 'Coordinates: 37.24N, -115.81W'
578
579Accessing arguments' attributes::
580
581 >>> c = 3-5j
582 >>> ('The complex number {0} is formed from the real part {0.real} '
583 ... 'and the imaginary part {0.imag}.').format(c)
584 'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
585 >>> class Point:
586 ... def __init__(self, x, y):
587 ... self.x, self.y = x, y
588 ... def __str__(self):
589 ... return 'Point({self.x}, {self.y})'.format(self=self)
590 ...
591 >>> str(Point(4, 2))
592 'Point(4, 2)'
593
594Accessing arguments' items::
595
596 >>> coord = (3, 5)
597 >>> 'X: {0[0]}; Y: {0[1]}'.format(coord)
598 'X: 3; Y: 5'
599
600Replacing ``%s`` and ``%r``::
601
602 >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
603 "repr() shows quotes: 'test1'; str() doesn't: test2"
604
605Aligning the text and specifying a width::
606
607 >>> '{:<30}'.format('left aligned')
608 'left aligned '
609 >>> '{:>30}'.format('right aligned')
610 ' right aligned'
611 >>> '{:^30}'.format('centered')
612 ' centered '
613 >>> '{:*^30}'.format('centered') # use '*' as a fill char
614 '***********centered***********'
615
616Replacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign::
617
618 >>> '{:+f}; {:+f}'.format(3.14, -3.14) # show it always
619 '+3.140000; -3.140000'
620 >>> '{: f}; {: f}'.format(3.14, -3.14) # show a space for positive numbers
621 ' 3.140000; -3.140000'
622 >>> '{:-f}; {:-f}'.format(3.14, -3.14) # show only the minus -- same as '{:f}; {:f}'
623 '3.140000; -3.140000'
624
625Replacing ``%x`` and ``%o`` and converting the value to different bases::
626
627 >>> # format also supports binary numbers
628 >>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
629 'int: 42; hex: 2a; oct: 52; bin: 101010'
630 >>> # with 0x, 0o, or 0b as prefix:
631 >>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
632 'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
633
634Using the comma as a thousands separator::
635
636 >>> '{:,}'.format(1234567890)
637 '1,234,567,890'
638
639Expressing a percentage::
640
641 >>> points = 19
642 >>> total = 22
Sandro Tosibaf30da2011-12-24 15:53:35 +0100643 >>> 'Correct answers: {:.2%}'.format(points/total)
Ezio Melottid2191e02010-07-02 23:18:51 +0000644 'Correct answers: 86.36%'
645
646Using type-specific formatting::
647
648 >>> import datetime
649 >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
650 >>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
651 '2010-07-04 12:15:58'
652
653Nesting arguments and more complex examples::
654
655 >>> for align, text in zip('<^>', ['left', 'center', 'right']):
Georg Brandla5770aa2011-02-07 12:10:46 +0000656 ... '{0:{fill}{align}16}'.format(text, fill=align, align=align)
Ezio Melottid2191e02010-07-02 23:18:51 +0000657 ...
658 'left<<<<<<<<<<<<'
659 '^^^^^center^^^^^'
660 '>>>>>>>>>>>right'
661 >>>
662 >>> octets = [192, 168, 0, 1]
663 >>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
664 'C0A80001'
665 >>> int(_, 16)
666 3232235521
667 >>>
668 >>> width = 5
Ezio Melotti40507922013-01-11 09:09:07 +0200669 >>> for num in range(5,12): #doctest: +NORMALIZE_WHITESPACE
Ezio Melottid2191e02010-07-02 23:18:51 +0000670 ... for base in 'dXob':
671 ... print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
672 ... print()
673 ...
674 5 5 5 101
675 6 6 6 110
676 7 7 7 111
677 8 8 10 1000
678 9 9 11 1001
679 10 A 12 1010
680 11 B 13 1011
681
682
683
Georg Brandl4b491312007-08-31 09:22:56 +0000684.. _template-strings:
685
Georg Brandl116aa622007-08-15 14:28:22 +0000686Template strings
687----------------
688
Barry Warsaw9f74deb2017-03-28 10:02:07 -0400689Template strings provide simpler string substitutions as described in
690:pep:`292`. A primary use case for template strings is for
691internationalization (i18n) since in that context, the simpler syntax and
692functionality makes it easier to translate than other built-in string
693formatting facilities in Python. As an example of a library built on template
694strings for i18n, see the
695`flufl.i18n <http://flufli18n.readthedocs.io/en/latest/>`_ package.
696
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300697.. index:: single: $; in template strings
698
Barry Warsaw9f74deb2017-03-28 10:02:07 -0400699Template strings support ``$``-based substitutions, using the following rules:
Georg Brandl116aa622007-08-15 14:28:22 +0000700
701* ``$$`` is an escape; it is replaced with a single ``$``.
702
703* ``$identifier`` names a substitution placeholder matching a mapping key of
Barry Warsaw17d5f472015-06-09 14:20:31 -0400704 ``"identifier"``. By default, ``"identifier"`` is restricted to any
705 case-insensitive ASCII alphanumeric string (including underscores) that
706 starts with an underscore or ASCII letter. The first non-identifier
707 character after the ``$`` character terminates this placeholder
708 specification.
Georg Brandl116aa622007-08-15 14:28:22 +0000709
Barry Warsaw17d5f472015-06-09 14:20:31 -0400710* ``${identifier}`` is equivalent to ``$identifier``. It is required when
711 valid identifier characters follow the placeholder but are not part of the
Georg Brandl116aa622007-08-15 14:28:22 +0000712 placeholder, such as ``"${noun}ification"``.
713
714Any other appearance of ``$`` in the string will result in a :exc:`ValueError`
715being raised.
716
Georg Brandl116aa622007-08-15 14:28:22 +0000717The :mod:`string` module provides a :class:`Template` class that implements
718these rules. The methods of :class:`Template` are:
719
720
721.. class:: Template(template)
722
723 The constructor takes a single argument which is the template string.
724
725
Georg Brandl7f01a132009-09-16 15:58:14 +0000726 .. method:: substitute(mapping, **kwds)
Georg Brandl116aa622007-08-15 14:28:22 +0000727
Benjamin Petersone41251e2008-04-25 01:59:09 +0000728 Performs the template substitution, returning a new string. *mapping* is
729 any dictionary-like object with keys that match the placeholders in the
730 template. Alternatively, you can provide keyword arguments, where the
Georg Brandl7f01a132009-09-16 15:58:14 +0000731 keywords are the placeholders. When both *mapping* and *kwds* are given
732 and there are duplicates, the placeholders from *kwds* take precedence.
Georg Brandl116aa622007-08-15 14:28:22 +0000733
734
Georg Brandl7f01a132009-09-16 15:58:14 +0000735 .. method:: safe_substitute(mapping, **kwds)
Georg Brandl116aa622007-08-15 14:28:22 +0000736
Benjamin Petersone41251e2008-04-25 01:59:09 +0000737 Like :meth:`substitute`, except that if placeholders are missing from
Georg Brandl7f01a132009-09-16 15:58:14 +0000738 *mapping* and *kwds*, instead of raising a :exc:`KeyError` exception, the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000739 original placeholder will appear in the resulting string intact. Also,
740 unlike with :meth:`substitute`, any other appearances of the ``$`` will
741 simply return ``$`` instead of raising :exc:`ValueError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000742
Benjamin Petersone41251e2008-04-25 01:59:09 +0000743 While other exceptions may still occur, this method is called "safe"
744 because substitutions always tries to return a usable string instead of
745 raising an exception. In another sense, :meth:`safe_substitute` may be
746 anything other than safe, since it will silently ignore malformed
747 templates containing dangling delimiters, unmatched braces, or
748 placeholders that are not valid Python identifiers.
Georg Brandl116aa622007-08-15 14:28:22 +0000749
Benjamin Peterson20211002009-11-25 18:34:42 +0000750 :class:`Template` instances also provide one public data attribute:
Georg Brandl116aa622007-08-15 14:28:22 +0000751
Benjamin Peterson20211002009-11-25 18:34:42 +0000752 .. attribute:: template
Georg Brandl116aa622007-08-15 14:28:22 +0000753
Benjamin Peterson20211002009-11-25 18:34:42 +0000754 This is the object passed to the constructor's *template* argument. In
755 general, you shouldn't change it, but read-only access is not enforced.
Georg Brandl116aa622007-08-15 14:28:22 +0000756
Ezio Melottibcbc5672013-02-21 12:30:32 +0200757Here is an example of how to use a Template::
Georg Brandl116aa622007-08-15 14:28:22 +0000758
759 >>> from string import Template
760 >>> s = Template('$who likes $what')
761 >>> s.substitute(who='tim', what='kung pao')
762 'tim likes kung pao'
763 >>> d = dict(who='tim')
764 >>> Template('Give $who $100').substitute(d)
765 Traceback (most recent call last):
Ezio Melottibcbc5672013-02-21 12:30:32 +0200766 ...
Ezio Melotti40507922013-01-11 09:09:07 +0200767 ValueError: Invalid placeholder in string: line 1, col 11
Georg Brandl116aa622007-08-15 14:28:22 +0000768 >>> Template('$who likes $what').substitute(d)
769 Traceback (most recent call last):
Ezio Melottibcbc5672013-02-21 12:30:32 +0200770 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000771 KeyError: 'what'
772 >>> Template('$who likes $what').safe_substitute(d)
773 'tim likes $what'
774
Barry Warsaw9f74deb2017-03-28 10:02:07 -0400775Advanced usage: you can derive subclasses of :class:`Template` to customize
776the placeholder syntax, delimiter character, or the entire regular expression
777used to parse template strings. To do this, you can override these class
778attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000779
Barry Warsaw9f74deb2017-03-28 10:02:07 -0400780* *delimiter* -- This is the literal string describing a placeholder
781 introducing delimiter. The default value is ``$``. Note that this should
782 *not* be a regular expression, as the implementation will call
783 :meth:`re.escape` on this string as needed. Note further that you cannot
784 change the delimiter after class creation (i.e. a different delimiter must
785 be set in the subclass's class namespace).
Georg Brandl116aa622007-08-15 14:28:22 +0000786
787* *idpattern* -- This is the regular expression describing the pattern for
Barry Warsawba427962017-09-04 16:32:10 -0400788 non-braced placeholders. The default value is the regular expression
Serhiy Storchaka87be28f2018-01-04 19:20:11 +0200789 ``(?a:[_a-z][_a-z0-9]*)``. If this is given and *braceidpattern* is
INADA Naokib22273e2017-10-13 16:02:23 +0900790 ``None`` this pattern will also apply to braced placeholders.
791
792 .. note::
793
794 Since default *flags* is ``re.IGNORECASE``, pattern ``[a-z]`` can match
Barry Warsawe256b402017-11-21 10:28:13 -0500795 with some non-ASCII characters. That's why we use the local ``a`` flag
Serhiy Storchaka87be28f2018-01-04 19:20:11 +0200796 here.
Barry Warsawba427962017-09-04 16:32:10 -0400797
798 .. versionchanged:: 3.7
799 *braceidpattern* can be used to define separate patterns used inside and
800 outside the braces.
801
802* *braceidpattern* -- This is like *idpattern* but describes the pattern for
803 braced placeholders. Defaults to ``None`` which means to fall back to
804 *idpattern* (i.e. the same pattern is used both inside and outside braces).
805 If given, this allows you to define different patterns for braced and
806 unbraced placeholders.
807
808 .. versionadded:: 3.7
Georg Brandl116aa622007-08-15 14:28:22 +0000809
Georg Brandl056cb932010-07-29 17:16:10 +0000810* *flags* -- The regular expression flags that will be applied when compiling
811 the regular expression used for recognizing substitutions. The default value
812 is ``re.IGNORECASE``. Note that ``re.VERBOSE`` will always be added to the
813 flags, so custom *idpattern*\ s must follow conventions for verbose regular
814 expressions.
815
816 .. versionadded:: 3.2
817
Georg Brandl116aa622007-08-15 14:28:22 +0000818Alternatively, you can provide the entire regular expression pattern by
819overriding the class attribute *pattern*. If you do this, the value must be a
820regular expression object with four named capturing groups. The capturing
821groups correspond to the rules given above, along with the invalid placeholder
822rule:
823
824* *escaped* -- This group matches the escape sequence, e.g. ``$$``, in the
825 default pattern.
826
827* *named* -- This group matches the unbraced placeholder name; it should not
828 include the delimiter in capturing group.
829
830* *braced* -- This group matches the brace enclosed placeholder name; it should
831 not include either the delimiter or braces in the capturing group.
832
833* *invalid* -- This group matches any other delimiter pattern (usually a single
834 delimiter), and it should appear last in the regular expression.
835
836
Georg Brandlabc38772009-04-12 15:51:51 +0000837Helper functions
Georg Brandl116aa622007-08-15 14:28:22 +0000838----------------
839
Georg Brandl10430ad2009-09-26 20:59:11 +0000840.. function:: capwords(s, sep=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000841
Ezio Melottia40bdda2009-09-26 12:33:22 +0000842 Split the argument into words using :meth:`str.split`, capitalize each word
843 using :meth:`str.capitalize`, and join the capitalized words using
844 :meth:`str.join`. If the optional second argument *sep* is absent
845 or ``None``, runs of whitespace characters are replaced by a single space
846 and leading and trailing whitespace are removed, otherwise *sep* is used to
847 split and join the words.