blob: b7108641805e65285da4b23f47fe6f79d191533d [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
Andre Delfinob4204282019-03-14 16:28:31 -030059 in the ``C`` locale: ``!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~``.
Georg Brandl116aa622007-08-15 14:28:22 +000060
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
Georg Brandl50767402008-11-22 08:31:09 +000070 A string containing all ASCII characters that are considered whitespace.
Georg Brandl116aa622007-08-15 14:28:22 +000071 This includes the characters space, tab, linefeed, return, formfeed, and
72 vertical tab.
73
74
Georg Brandl4b491312007-08-31 09:22:56 +000075.. _string-formatting:
76
Martin Panterd5db1472016-02-08 01:34:09 +000077Custom String Formatting
78------------------------
Georg Brandl4b491312007-08-31 09:22:56 +000079
Benjamin Peterson50923f92008-05-25 19:45:17 +000080The built-in string class provides the ability to do complex variable
Martin Panterd5db1472016-02-08 01:34:09 +000081substitutions and value formatting via the :meth:`~str.format` method described in
Benjamin Peterson50923f92008-05-25 19:45:17 +000082: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
Martin Panterd5db1472016-02-08 01:34:09 +000084implementation as the built-in :meth:`~str.format` method.
Georg Brandl4b491312007-08-31 09:22:56 +000085
Benjamin Peterson1baf4652009-12-31 03:11:23 +000086
Georg Brandl4b491312007-08-31 09:22:56 +000087.. class:: Formatter
88
89 The :class:`Formatter` class has the following public methods:
90
Serhiy Storchaka2085bd02019-06-01 11:00:15 +030091 .. method:: format(format_string, /, *args, **kwargs)
Georg Brandl4b491312007-08-31 09:22:56 +000092
Martin Panterd5db1472016-02-08 01:34:09 +000093 The primary API method. It takes a format string and
R David Murraye56bf972012-08-19 17:26:34 -040094 an arbitrary set of positional and keyword arguments.
Martin Panterd5db1472016-02-08 01:34:09 +000095 It is just a wrapper that calls :meth:`vformat`.
Georg Brandl4b491312007-08-31 09:22:56 +000096
Serhiy Storchaka009b0a12017-01-13 09:10:51 +020097 .. versionchanged:: 3.7
98 A format string argument is now :ref:`positional-only
99 <positional-only_parameter>`.
Serhiy Storchakab876df42015-03-24 22:30:46 +0200100
Georg Brandl4b491312007-08-31 09:22:56 +0000101 .. method:: vformat(format_string, args, kwargs)
Georg Brandl48310cd2009-01-03 21:18:54 +0000102
Georg Brandl4b491312007-08-31 09:22:56 +0000103 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
Ezio Melotti28c88f42012-11-27 19:17:57 +0200106 dictionary as individual arguments using the ``*args`` and ``**kwargs``
R David Murraye56bf972012-08-19 17:26:34 -0400107 syntax. :meth:`vformat` does the work of breaking up the format string
108 into character data and replacement fields. It calls the various
Georg Brandl4b491312007-08-31 09:22:56 +0000109 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)
Georg Brandl48310cd2009-01-03 21:18:54 +0000115
Georg Brandl4b491312007-08-31 09:22:56 +0000116 Loop over the format_string and return an iterable of tuples
117 (*literal_text*, *field_name*, *format_spec*, *conversion*). This is used
Georg Brandl70cd7bc2010-10-26 19:31:06 +0000118 by :meth:`vformat` to break the string into either literal text, or
Georg Brandl4b491312007-08-31 09:22:56 +0000119 replacement fields.
Georg Brandl48310cd2009-01-03 21:18:54 +0000120
Georg Brandl4b491312007-08-31 09:22:56 +0000121 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
Eric Smith9d4ba392007-09-02 15:33:26 +0000128 .. method:: get_field(field_name, args, kwargs)
Georg Brandl4b491312007-08-31 09:22:56 +0000129
130 Given *field_name* as returned by :meth:`parse` (see above), convert it to
Georg Brandl7f13e6b2007-08-31 10:37:15 +0000131 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`.
Georg Brandl4b491312007-08-31 09:22:56 +0000136
137 .. method:: get_value(key, args, kwargs)
Georg Brandl48310cd2009-01-03 21:18:54 +0000138
Georg Brandl4b491312007-08-31 09:22:56 +0000139 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
Krishna Oza12b436e2019-07-01 11:34:20 +0530149 component of the field name; subsequent components are handled through
Georg Brandl4b491312007-08-31 09:22:56 +0000150 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
Georg Brandl7cb13192010-08-03 12:06:29 +0000167 parameters. :meth:`check_unused_args` is assumed to raise an exception if
Georg Brandl4b491312007-08-31 09:22:56 +0000168 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)
Georg Brandl48310cd2009-01-03 21:18:54 +0000176
Georg Brandl4b491312007-08-31 09:22:56 +0000177 Converts the value (returned by :meth:`get_field`) given a conversion type
Ezio Melottid2191e02010-07-02 23:18:51 +0000178 (as in the tuple returned by the :meth:`parse` method). The default
R David Murraye56bf972012-08-19 17:26:34 -0400179 version understands 's' (str), 'r' (repr) and 'a' (ascii) conversion
180 types.
Georg Brandl4b491312007-08-31 09:22:56 +0000181
Georg Brandl4b491312007-08-31 09:22:56 +0000182
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`,
Martin Panterbc1ee462016-02-13 00:41:37 +0000190subclasses can define their own format string syntax). The syntax is
Irit Katrielfb1d01b2021-03-28 21:47:20 +0100191related to that of :ref:`formatted string literals <f-strings>`, but it is
192less sophisticated and, in particular, does not support arbitrary expressions.
Georg Brandl4b491312007-08-31 09:22:56 +0000193
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300194.. index::
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200195 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
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300200
Georg Brandl4b491312007-08-31 09:22:56 +0000201Format 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
Victor Stinner8af239e2020-09-18 09:10:15 +0200208 .. productionlist:: format-string
Georg Brandl2f3ed682009-09-01 07:42:40 +0000209 replacement_field: "{" [`field_name`] ["!" `conversion`] [":" `format_spec`] "}"
Eric Smithc4cae322009-04-22 00:53:01 +0000210 field_name: arg_name ("." `attribute_name` | "[" `element_index` "]")*
Mariatta7a561af2018-02-05 04:29:02 -0500211 arg_name: [`identifier` | `digit`+]
Georg Brandl4b491312007-08-31 09:22:56 +0000212 attribute_name: `identifier`
Mariatta7a561af2018-02-05 04:29:02 -0500213 element_index: `digit`+ | `index_string`
Eric Smith2e9f2022010-02-25 14:58:13 +0000214 index_string: <any source character except "]"> +
Benjamin Peterson065ba702008-11-09 01:43:02 +0000215 conversion: "r" | "s" | "a"
Georg Brandl4b491312007-08-31 09:22:56 +0000216 format_spec: <described in the next section>
Georg Brandl48310cd2009-01-03 21:18:54 +0000217
Georg Brandl2f3ed682009-09-01 07:42:40 +0000218In less formal terms, the replacement field can start with a *field_name* that specifies
Eric Smithc4cae322009-04-22 00:53:01 +0000219the 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
Georg Brandl4b491312007-08-31 09:22:56 +0000222preceded by an exclamation point ``'!'``, and a *format_spec*, which is preceded
Eric Smithc4cae322009-04-22 00:53:01 +0000223by a colon ``':'``. These specify a non-default format for the replacement value.
Georg Brandl4b491312007-08-31 09:22:56 +0000224
Ezio Melottid2191e02010-07-02 23:18:51 +0000225See also the :ref:`formatspec` section.
226
Ezio Melottie130a522011-10-19 10:58:56 +0300227The *field_name* itself begins with an *arg_name* that is either a number or a
Eric Smithc4cae322009-04-22 00:53:01 +0000228keyword. 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.
Éric Araujo29cf58c2011-09-01 18:59:06 +0200232Because *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.
Eric Smithc4cae322009-04-22 00:53:01 +0000234The *arg_name* can be followed by any number of index or
Georg Brandl4b491312007-08-31 09:22:56 +0000235attribute 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
Ezio Melottid2191e02010-07-02 23:18:51 +0000239.. versionchanged:: 3.1
Xiang Zhangb9d8ad52018-06-13 09:42:44 +0800240 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`.
Ezio Melottid2191e02010-07-02 23:18:51 +0000245
Georg Brandl4b491312007-08-31 09:22:56 +0000246Some simple format string examples::
247
Serhiy Storchakadba90392016-05-10 12:01:23 +0300248 "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'.
Georg Brandl48310cd2009-01-03 21:18:54 +0000254
Georg Brandl4b491312007-08-31 09:22:56 +0000255The *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
Georg Brandl559e5d72008-06-11 18:37:52 +0000262Three 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`.
Georg Brandl4b491312007-08-31 09:22:56 +0000265
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
Georg Brandl2f3ed682009-09-01 07:42:40 +0000270 "More {!a}" # Calls ascii() on the argument first
Georg Brandl4b491312007-08-31 09:22:56 +0000271
272The *format_spec* field contains a specification of how the value should be
273presented, including such details as field width, alignment, padding, decimal
Eric Smith0f7affe2010-02-15 11:57:31 +0000274precision and so on. Each value type can define its own "formatting
Georg Brandl4b491312007-08-31 09:22:56 +0000275mini-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.
Martin Panterd5db1472016-02-08 01:34:09 +0000281These nested replacement fields may contain a field name, conversion flag
282and format specification, but deeper nesting is
283not allowed. The replacement fields within the
Georg Brandl4b491312007-08-31 09:22:56 +0000284format_spec are substituted before the *format_spec* string is interpreted.
285This allows the formatting of a value to be dynamically specified.
286
Ezio Melottid2191e02010-07-02 23:18:51 +0000287See the :ref:`formatexamples` section for some examples.
Georg Brandl4b491312007-08-31 09:22:56 +0000288
Georg Brandl4b491312007-08-31 09:22:56 +0000289
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
Martin Panterbc1ee462016-02-13 00:41:37 +0000297:ref:`formatstrings` and :ref:`f-strings`).
298They can also be passed directly to the built-in
Georg Brandl4b491312007-08-31 09:22:56 +0000299: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
Terry Jan Reedy916895f2020-02-28 14:59:16 -0500305A general convention is that an empty format specification produces
Eric Smith05c07742010-02-25 14:18:57 +0000306the same result as if you had called :func:`str` on the value. A
Terry Jan Reedy916895f2020-02-28 14:59:16 -0500307non-empty format specification typically modifies the result.
Georg Brandl4b491312007-08-31 09:22:56 +0000308
309The general form of a *standard format specifier* is:
310
Victor Stinner8af239e2020-09-18 09:10:15 +0200311.. productionlist:: format-spec
Eric V. Smithd7665ca2016-09-09 23:13:01 -0400312 format_spec: [[`fill`]`align`][`sign`][#][0][`width`][`grouping_option`][.`precision`][`type`]
Ezio Melottic3184422013-10-21 02:53:07 +0300313 fill: <any character>
Georg Brandl4b491312007-08-31 09:22:56 +0000314 align: "<" | ">" | "=" | "^"
315 sign: "+" | "-" | " "
nathankerr968b5fa282018-02-03 21:42:08 -0800316 width: `digit`+
Eric V. Smithd7665ca2016-09-09 23:13:01 -0400317 grouping_option: "_" | ","
nathankerr968b5fa282018-02-03 21:42:08 -0800318 precision: `digit`+
Eric Smith05c07742010-02-25 14:18:57 +0000319 type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
Georg Brandl48310cd2009-01-03 21:18:54 +0000320
Ezio Melotti2bbdfe72013-11-17 02:47:12 +0200321If a valid *align* value is specified, it can be preceded by a *fill*
Ezio Melottic3184422013-10-21 02:53:07 +0300322character that can be any character and defaults to a space if omitted.
Martin Panterd5db1472016-02-08 01:34:09 +0000323It is not possible to use a literal curly brace ("``{``" or "``}``") as
Martin Panterbc1ee462016-02-13 00:41:37 +0000324the *fill* character in a :ref:`formatted string literal
325<f-strings>` or when using the :meth:`str.format`
Martin Panterd5db1472016-02-08 01:34:09 +0000326method. However, it is possible to insert a curly brace
327with a nested replacement field. This limitation doesn't
Ezio Melottic3184422013-10-21 02:53:07 +0300328affect the :func:`format` function.
Georg Brandl4b491312007-08-31 09:22:56 +0000329
330The meaning of the various alignment options is as follows:
331
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300332 .. index::
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200333 single: < (less); in string formatting
334 single: > (greater); in string formatting
335 single: = (equals); in string formatting
336 single: ^ (caret); in string formatting
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300337
Georg Brandl4b491312007-08-31 09:22:56 +0000338 +---------+----------------------------------------------------------+
339 | Option | Meaning |
340 +=========+==========================================================+
341 | ``'<'`` | Forces the field to be left-aligned within the available |
Georg Brandlca583b62011-02-07 12:13:58 +0000342 | | space (this is the default for most objects). |
Georg Brandl4b491312007-08-31 09:22:56 +0000343 +---------+----------------------------------------------------------+
344 | ``'>'`` | Forces the field to be right-aligned within the |
Georg Brandlca583b62011-02-07 12:13:58 +0000345 | | available space (this is the default for numbers). |
Georg Brandl4b491312007-08-31 09:22:56 +0000346 +---------+----------------------------------------------------------+
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 |
Serhiy Storchakacf19cc32021-01-25 11:56:33 +0200350 | | valid for numeric types. It becomes the default for |
351 | | numbers when '0' immediately precedes the field width. |
Georg Brandl4b491312007-08-31 09:22:56 +0000352 +---------+----------------------------------------------------------+
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
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300364 .. index::
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200365 single: + (plus); in string formatting
366 single: - (minus); in string formatting
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300367 single: space; in string formatting
368
Georg Brandl4b491312007-08-31 09:22:56 +0000369 +---------+----------------------------------------------------------+
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
Eric Smith984bb582010-11-25 16:08:06 +0000382
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200383.. index:: single: # (hash); in string formatting
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300384
Eric Smith984bb582010-11-25 16:08:06 +0000385The ``'#'`` option causes the "alternate form" to be used for the
386conversion. The alternate form is defined differently for different
Mark Dickinsonc6423742020-11-29 09:34:36 +0000387types. This option is only valid for integer, float and complex
388types. For integers, when binary, octal, or hexadecimal output
Miss Islington (bot)34fc6dd2021-05-06 12:46:08 -0700389is used, this option adds the respective prefix ``'0b'``, ``'0o'``,
390``'0x'``, or ``'0X'`` to the output value. For float and complex the
Eric Smith984bb582010-11-25 16:08:06 +0000391alternate 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.
Eric Smithd68af8f2008-07-16 00:15:35 +0000396
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200397.. index:: single: , (comma); in string formatting
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300398
Raymond Hettinger6db94702009-07-12 20:49:21 +0000399The ``','`` option signals the use of a comma for a thousands separator.
400For a locale aware separator, use the ``'n'`` integer presentation type
401instead.
402
Ezio Melottid2191e02010-07-02 23:18:51 +0000403.. versionchanged:: 3.1
404 Added the ``','`` option (see also :pep:`378`).
405
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200406.. index:: single: _ (underscore); in string formatting
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300407
Eric V. Smith89e1b1a2016-09-09 23:06:47 -0400408The ``'_'`` 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
Pete Wicken424e5682020-02-21 05:53:12 +0000418*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.
Georg Brandl4b491312007-08-31 09:22:56 +0000421
Terry Jan Reedy4902c462016-03-20 21:05:57 -0400422When no explicit alignment is given, preceding the *width* field by a zero
423(``'0'``) character enables
Terry Jan Reedyf6190c12012-08-17 15:40:46 -0400424sign-aware zero-padding for numeric types. This is equivalent to a *fill*
425character of ``'0'`` with an *alignment* type of ``'='``.
Georg Brandl4b491312007-08-31 09:22:56 +0000426
Serhiy Storchakacf19cc32021-01-25 11:56:33 +0200427.. versionchanged:: 3.10
428 Preceding the *width* field by ``'0'`` no longer affects the default
429 alignment for strings.
430
Miss Islington (bot)6a7dd3f2022-02-13 16:21:32 -0800431The *precision* is a decimal integer indicating how many digits should be
432displayed after the decimal point for presentation types
433``'f'`` and ``'F'``, or before and after the decimal point for presentation
434types ``'g'`` or ``'G'``. For string presentation types the field
Georg Brandl3dbca812008-07-23 16:10:53 +0000435indicates the maximum field size - in other words, how many characters will be
Miss Islington (bot)6a7dd3f2022-02-13 16:21:32 -0800436used from the field content. The *precision* is not allowed for integer
437presentation types.
Georg Brandl4b491312007-08-31 09:22:56 +0000438
439Finally, the *type* determines how the data should be presented.
440
Eric Smith05c07742010-02-25 14:18:57 +0000441The available string presentation types are:
442
443 +---------+----------------------------------------------------------+
444 | Type | Meaning |
445 +=========+==========================================================+
446 | ``'s'`` | String format. This is the default type for strings and |
447 | | may be omitted. |
448 +---------+----------------------------------------------------------+
449 | None | The same as ``'s'``. |
450 +---------+----------------------------------------------------------+
451
Georg Brandl4b491312007-08-31 09:22:56 +0000452The available integer presentation types are:
453
454 +---------+----------------------------------------------------------+
455 | Type | Meaning |
456 +=========+==========================================================+
Eric Smithd68af8f2008-07-16 00:15:35 +0000457 | ``'b'`` | Binary format. Outputs the number in base 2. |
Georg Brandl4b491312007-08-31 09:22:56 +0000458 +---------+----------------------------------------------------------+
459 | ``'c'`` | Character. Converts the integer to the corresponding |
460 | | unicode character before printing. |
461 +---------+----------------------------------------------------------+
462 | ``'d'`` | Decimal Integer. Outputs the number in base 10. |
463 +---------+----------------------------------------------------------+
464 | ``'o'`` | Octal format. Outputs the number in base 8. |
465 +---------+----------------------------------------------------------+
Serhiy Storchaka3f819ca2018-10-31 02:26:06 +0200466 | ``'x'`` | Hex format. Outputs the number in base 16, using |
467 | | lower-case letters for the digits above 9. |
Georg Brandl4b491312007-08-31 09:22:56 +0000468 +---------+----------------------------------------------------------+
Serhiy Storchaka3f819ca2018-10-31 02:26:06 +0200469 | ``'X'`` | Hex format. Outputs the number in base 16, using |
470 | | upper-case letters for the digits above 9. |
Miss Islington (bot)34fc6dd2021-05-06 12:46:08 -0700471 | | In case ``'#'`` is specified, the prefix ``'0x'`` will |
472 | | be upper-cased to ``'0X'`` as well. |
Georg Brandl4b491312007-08-31 09:22:56 +0000473 +---------+----------------------------------------------------------+
Eric Smith5e18a202008-05-12 10:01:24 +0000474 | ``'n'`` | Number. This is the same as ``'d'``, except that it uses |
475 | | the current locale setting to insert the appropriate |
476 | | number separator characters. |
477 +---------+----------------------------------------------------------+
Georg Brandl3dbca812008-07-23 16:10:53 +0000478 | None | The same as ``'d'``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000479 +---------+----------------------------------------------------------+
Georg Brandl48310cd2009-01-03 21:18:54 +0000480
Eric Smith05c07742010-02-25 14:18:57 +0000481In addition to the above presentation types, integers can be formatted
482with the floating point presentation types listed below (except
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300483``'n'`` and ``None``). When doing so, :func:`float` is used to convert the
Eric Smith05c07742010-02-25 14:18:57 +0000484integer to a floating point number before formatting.
485
Mark Dickinsonc6423742020-11-29 09:34:36 +0000486The available presentation types for :class:`float` and
487:class:`~decimal.Decimal` values are:
Georg Brandl48310cd2009-01-03 21:18:54 +0000488
Georg Brandl4b491312007-08-31 09:22:56 +0000489 +---------+----------------------------------------------------------+
490 | Type | Meaning |
491 +=========+==========================================================+
Mark Dickinsonc6423742020-11-29 09:34:36 +0000492 | ``'e'`` | Scientific notation. For a given precision ``p``, |
493 | | formats the number in scientific notation with the |
494 | | letter 'e' separating the coefficient from the exponent. |
495 | | The coefficient has one digit before and ``p`` digits |
496 | | after the decimal point, for a total of ``p + 1`` |
497 | | significant digits. With no precision given, uses a |
498 | | precision of ``6`` digits after the decimal point for |
499 | | :class:`float`, and shows all coefficient digits |
500 | | for :class:`~decimal.Decimal`. If no digits follow the |
501 | | decimal point, the decimal point is also removed unless |
502 | | the ``#`` option is used. |
Georg Brandl4b491312007-08-31 09:22:56 +0000503 +---------+----------------------------------------------------------+
Mark Dickinsonc6423742020-11-29 09:34:36 +0000504 | ``'E'`` | Scientific notation. Same as ``'e'`` except it uses |
505 | | an upper case 'E' as the separator character. |
Georg Brandl4b491312007-08-31 09:22:56 +0000506 +---------+----------------------------------------------------------+
Mark Dickinsonc6423742020-11-29 09:34:36 +0000507 | ``'f'`` | Fixed-point notation. For a given precision ``p``, |
508 | | formats the number as a decimal number with exactly |
509 | | ``p`` digits following the decimal point. With no |
510 | | precision given, uses a precision of ``6`` digits after |
511 | | the decimal point for :class:`float`, and uses a |
512 | | precision large enough to show all coefficient digits |
513 | | for :class:`~decimal.Decimal`. If no digits follow the |
514 | | decimal point, the decimal point is also removed unless |
515 | | the ``#`` option is used. |
Georg Brandl4b491312007-08-31 09:22:56 +0000516 +---------+----------------------------------------------------------+
Terry Jan Reedy28c7f8c2018-08-06 08:41:17 -0400517 | ``'F'`` | Fixed-point notation. Same as ``'f'``, but converts |
518 | | ``nan`` to ``NAN`` and ``inf`` to ``INF``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000519 +---------+----------------------------------------------------------+
Mark Dickinsonc70614f2009-10-08 20:05:48 +0000520 | ``'g'`` | General format. For a given precision ``p >= 1``, |
521 | | this rounds the number to ``p`` significant digits and |
522 | | then formats the result in either fixed-point format |
523 | | or in scientific notation, depending on its magnitude. |
Mark Dickinson886b2e52020-12-18 09:24:06 +0000524 | | A precision of ``0`` is treated as equivalent to a |
525 | | precision of ``1``. |
Mark Dickinsonc70614f2009-10-08 20:05:48 +0000526 | | |
527 | | The precise rules are as follows: suppose that the |
528 | | result formatted with presentation type ``'e'`` and |
Brennan D Baraban1660a612019-09-11 06:59:37 -0700529 | | precision ``p-1`` would have exponent ``exp``. Then, |
530 | | if ``m <= exp < p``, where ``m`` is -4 for floats and -6 |
531 | | for :class:`Decimals <decimal.Decimal>`, the number is |
532 | | formatted with presentation type ``'f'`` and precision |
Mark Dickinsonc70614f2009-10-08 20:05:48 +0000533 | | ``p-1-exp``. Otherwise, the number is formatted |
534 | | with presentation type ``'e'`` and precision ``p-1``. |
535 | | In both cases insignificant trailing zeros are removed |
536 | | from the significand, and the decimal point is also |
bchhabra2490d44542f2019-09-13 22:50:21 +0530537 | | removed if there are no remaining digits following it, |
538 | | unless the ``'#'`` option is used. |
Mark Dickinsonc70614f2009-10-08 20:05:48 +0000539 | | |
Mark Dickinson886b2e52020-12-18 09:24:06 +0000540 | | With no precision given, uses a precision of ``6`` |
541 | | significant digits for :class:`float`. For |
542 | | :class:`~decimal.Decimal`, the coefficient of the result |
543 | | is formed from the coefficient digits of the value; |
544 | | scientific notation is used for values smaller than |
545 | | ``1e-6`` in absolute value and values where the place |
546 | | value of the least significant digit is larger than 1, |
547 | | and fixed-point notation is used otherwise. |
548 | | |
Benjamin Peterson73a3f2d2010-10-12 23:07:13 +0000549 | | Positive and negative infinity, positive and negative |
Mark Dickinsonc70614f2009-10-08 20:05:48 +0000550 | | zero, and nans, are formatted as ``inf``, ``-inf``, |
551 | | ``0``, ``-0`` and ``nan`` respectively, regardless of |
552 | | the precision. |
Georg Brandl4b491312007-08-31 09:22:56 +0000553 +---------+----------------------------------------------------------+
554 | ``'G'`` | General format. Same as ``'g'`` except switches to |
Mark Dickinsonc70614f2009-10-08 20:05:48 +0000555 | | ``'E'`` if the number gets too large. The |
556 | | representations of infinity and NaN are uppercased, too. |
Georg Brandl4b491312007-08-31 09:22:56 +0000557 +---------+----------------------------------------------------------+
558 | ``'n'`` | Number. This is the same as ``'g'``, except that it uses |
559 | | the current locale setting to insert the appropriate |
560 | | number separator characters. |
561 +---------+----------------------------------------------------------+
562 | ``'%'`` | Percentage. Multiplies the number by 100 and displays |
563 | | in fixed (``'f'``) format, followed by a percent sign. |
564 +---------+----------------------------------------------------------+
Mark Dickinson886b2e52020-12-18 09:24:06 +0000565 | None | For :class:`float` this is the same as ``'g'``, except |
566 | | that when fixed-point notation is used to format the |
567 | | result, it always includes at least one digit past the |
568 | | decimal point. The precision used is as large as needed |
569 | | to represent the given value faithfully. |
570 | | |
571 | | For :class:`~decimal.Decimal`, this is the same as |
572 | | either ``'g'`` or ``'G'`` depending on the value of |
573 | | ``context.capitals`` for the current decimal context. |
574 | | |
575 | | The overall effect is to match the output of :func:`str` |
576 | | as altered by the other format modifiers. |
Georg Brandl4b491312007-08-31 09:22:56 +0000577 +---------+----------------------------------------------------------+
578
579
Ezio Melottid2191e02010-07-02 23:18:51 +0000580.. _formatexamples:
581
582Format examples
583^^^^^^^^^^^^^^^
584
Martin Panterd5db1472016-02-08 01:34:09 +0000585This section contains examples of the :meth:`str.format` syntax and
586comparison with the old ``%``-formatting.
Ezio Melottid2191e02010-07-02 23:18:51 +0000587
588In most of the cases the syntax is similar to the old ``%``-formatting, with the
589addition of the ``{}`` and with ``:`` used instead of ``%``.
590For example, ``'%03.2f'`` can be translated to ``'{:03.2f}'``.
591
592The new format syntax also supports new and different options, shown in the
Andrés Delfinod6499102018-11-07 14:24:56 -0300593following examples.
Ezio Melottid2191e02010-07-02 23:18:51 +0000594
595Accessing arguments by position::
596
597 >>> '{0}, {1}, {2}'.format('a', 'b', 'c')
598 'a, b, c'
599 >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only
600 'a, b, c'
601 >>> '{2}, {1}, {0}'.format('a', 'b', 'c')
602 'c, b, a'
603 >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence
604 'c, b, a'
605 >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated
606 'abracadabra'
607
608Accessing arguments by name::
609
610 >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
611 'Coordinates: 37.24N, -115.81W'
612 >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
613 >>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
614 'Coordinates: 37.24N, -115.81W'
615
616Accessing arguments' attributes::
617
618 >>> c = 3-5j
619 >>> ('The complex number {0} is formed from the real part {0.real} '
620 ... 'and the imaginary part {0.imag}.').format(c)
621 'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
622 >>> class Point:
623 ... def __init__(self, x, y):
624 ... self.x, self.y = x, y
625 ... def __str__(self):
626 ... return 'Point({self.x}, {self.y})'.format(self=self)
627 ...
628 >>> str(Point(4, 2))
629 'Point(4, 2)'
630
631Accessing arguments' items::
632
633 >>> coord = (3, 5)
634 >>> 'X: {0[0]}; Y: {0[1]}'.format(coord)
635 'X: 3; Y: 5'
636
637Replacing ``%s`` and ``%r``::
638
639 >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
640 "repr() shows quotes: 'test1'; str() doesn't: test2"
641
642Aligning the text and specifying a width::
643
644 >>> '{:<30}'.format('left aligned')
645 'left aligned '
646 >>> '{:>30}'.format('right aligned')
647 ' right aligned'
648 >>> '{:^30}'.format('centered')
649 ' centered '
650 >>> '{:*^30}'.format('centered') # use '*' as a fill char
651 '***********centered***********'
652
653Replacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign::
654
655 >>> '{:+f}; {:+f}'.format(3.14, -3.14) # show it always
656 '+3.140000; -3.140000'
657 >>> '{: f}; {: f}'.format(3.14, -3.14) # show a space for positive numbers
658 ' 3.140000; -3.140000'
659 >>> '{:-f}; {:-f}'.format(3.14, -3.14) # show only the minus -- same as '{:f}; {:f}'
660 '3.140000; -3.140000'
661
662Replacing ``%x`` and ``%o`` and converting the value to different bases::
663
664 >>> # format also supports binary numbers
665 >>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
666 'int: 42; hex: 2a; oct: 52; bin: 101010'
667 >>> # with 0x, 0o, or 0b as prefix:
668 >>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
669 'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
670
671Using the comma as a thousands separator::
672
673 >>> '{:,}'.format(1234567890)
674 '1,234,567,890'
675
676Expressing a percentage::
677
678 >>> points = 19
679 >>> total = 22
Sandro Tosibaf30da2011-12-24 15:53:35 +0100680 >>> 'Correct answers: {:.2%}'.format(points/total)
Ezio Melottid2191e02010-07-02 23:18:51 +0000681 'Correct answers: 86.36%'
682
683Using type-specific formatting::
684
685 >>> import datetime
686 >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
687 >>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
688 '2010-07-04 12:15:58'
689
690Nesting arguments and more complex examples::
691
692 >>> for align, text in zip('<^>', ['left', 'center', 'right']):
Georg Brandla5770aa2011-02-07 12:10:46 +0000693 ... '{0:{fill}{align}16}'.format(text, fill=align, align=align)
Ezio Melottid2191e02010-07-02 23:18:51 +0000694 ...
695 'left<<<<<<<<<<<<'
696 '^^^^^center^^^^^'
697 '>>>>>>>>>>>right'
698 >>>
699 >>> octets = [192, 168, 0, 1]
700 >>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
701 'C0A80001'
702 >>> int(_, 16)
703 3232235521
704 >>>
705 >>> width = 5
Ezio Melotti40507922013-01-11 09:09:07 +0200706 >>> for num in range(5,12): #doctest: +NORMALIZE_WHITESPACE
Ezio Melottid2191e02010-07-02 23:18:51 +0000707 ... for base in 'dXob':
708 ... print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
709 ... print()
710 ...
711 5 5 5 101
712 6 6 6 110
713 7 7 7 111
714 8 8 10 1000
715 9 9 11 1001
716 10 A 12 1010
717 11 B 13 1011
718
719
720
Georg Brandl4b491312007-08-31 09:22:56 +0000721.. _template-strings:
722
Georg Brandl116aa622007-08-15 14:28:22 +0000723Template strings
724----------------
725
Barry Warsaw9f74deb2017-03-28 10:02:07 -0400726Template strings provide simpler string substitutions as described in
727:pep:`292`. A primary use case for template strings is for
728internationalization (i18n) since in that context, the simpler syntax and
729functionality makes it easier to translate than other built-in string
730formatting facilities in Python. As an example of a library built on template
731strings for i18n, see the
732`flufl.i18n <http://flufli18n.readthedocs.io/en/latest/>`_ package.
733
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200734.. index:: single: $ (dollar); in template strings
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300735
Barry Warsaw9f74deb2017-03-28 10:02:07 -0400736Template strings support ``$``-based substitutions, using the following rules:
Georg Brandl116aa622007-08-15 14:28:22 +0000737
738* ``$$`` is an escape; it is replaced with a single ``$``.
739
740* ``$identifier`` names a substitution placeholder matching a mapping key of
Barry Warsaw17d5f472015-06-09 14:20:31 -0400741 ``"identifier"``. By default, ``"identifier"`` is restricted to any
742 case-insensitive ASCII alphanumeric string (including underscores) that
743 starts with an underscore or ASCII letter. The first non-identifier
744 character after the ``$`` character terminates this placeholder
745 specification.
Georg Brandl116aa622007-08-15 14:28:22 +0000746
Barry Warsaw17d5f472015-06-09 14:20:31 -0400747* ``${identifier}`` is equivalent to ``$identifier``. It is required when
748 valid identifier characters follow the placeholder but are not part of the
Georg Brandl116aa622007-08-15 14:28:22 +0000749 placeholder, such as ``"${noun}ification"``.
750
751Any other appearance of ``$`` in the string will result in a :exc:`ValueError`
752being raised.
753
Georg Brandl116aa622007-08-15 14:28:22 +0000754The :mod:`string` module provides a :class:`Template` class that implements
755these rules. The methods of :class:`Template` are:
756
757
758.. class:: Template(template)
759
760 The constructor takes a single argument which is the template string.
761
762
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300763 .. method:: substitute(mapping={}, /, **kwds)
Georg Brandl116aa622007-08-15 14:28:22 +0000764
Benjamin Petersone41251e2008-04-25 01:59:09 +0000765 Performs the template substitution, returning a new string. *mapping* is
766 any dictionary-like object with keys that match the placeholders in the
767 template. Alternatively, you can provide keyword arguments, where the
Georg Brandl7f01a132009-09-16 15:58:14 +0000768 keywords are the placeholders. When both *mapping* and *kwds* are given
769 and there are duplicates, the placeholders from *kwds* take precedence.
Georg Brandl116aa622007-08-15 14:28:22 +0000770
771
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300772 .. method:: safe_substitute(mapping={}, /, **kwds)
Georg Brandl116aa622007-08-15 14:28:22 +0000773
Benjamin Petersone41251e2008-04-25 01:59:09 +0000774 Like :meth:`substitute`, except that if placeholders are missing from
Georg Brandl7f01a132009-09-16 15:58:14 +0000775 *mapping* and *kwds*, instead of raising a :exc:`KeyError` exception, the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000776 original placeholder will appear in the resulting string intact. Also,
777 unlike with :meth:`substitute`, any other appearances of the ``$`` will
778 simply return ``$`` instead of raising :exc:`ValueError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000779
Benjamin Petersone41251e2008-04-25 01:59:09 +0000780 While other exceptions may still occur, this method is called "safe"
Andrés Delfinod6499102018-11-07 14:24:56 -0300781 because it always tries to return a usable string instead of
Benjamin Petersone41251e2008-04-25 01:59:09 +0000782 raising an exception. In another sense, :meth:`safe_substitute` may be
783 anything other than safe, since it will silently ignore malformed
784 templates containing dangling delimiters, unmatched braces, or
785 placeholders that are not valid Python identifiers.
Georg Brandl116aa622007-08-15 14:28:22 +0000786
Benjamin Peterson20211002009-11-25 18:34:42 +0000787 :class:`Template` instances also provide one public data attribute:
Georg Brandl116aa622007-08-15 14:28:22 +0000788
Benjamin Peterson20211002009-11-25 18:34:42 +0000789 .. attribute:: template
Georg Brandl116aa622007-08-15 14:28:22 +0000790
Benjamin Peterson20211002009-11-25 18:34:42 +0000791 This is the object passed to the constructor's *template* argument. In
792 general, you shouldn't change it, but read-only access is not enforced.
Georg Brandl116aa622007-08-15 14:28:22 +0000793
Ezio Melottibcbc5672013-02-21 12:30:32 +0200794Here is an example of how to use a Template::
Georg Brandl116aa622007-08-15 14:28:22 +0000795
796 >>> from string import Template
797 >>> s = Template('$who likes $what')
798 >>> s.substitute(who='tim', what='kung pao')
799 'tim likes kung pao'
800 >>> d = dict(who='tim')
801 >>> Template('Give $who $100').substitute(d)
802 Traceback (most recent call last):
Ezio Melottibcbc5672013-02-21 12:30:32 +0200803 ...
Ezio Melotti40507922013-01-11 09:09:07 +0200804 ValueError: Invalid placeholder in string: line 1, col 11
Georg Brandl116aa622007-08-15 14:28:22 +0000805 >>> Template('$who likes $what').substitute(d)
806 Traceback (most recent call last):
Ezio Melottibcbc5672013-02-21 12:30:32 +0200807 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000808 KeyError: 'what'
809 >>> Template('$who likes $what').safe_substitute(d)
810 'tim likes $what'
811
Barry Warsaw9f74deb2017-03-28 10:02:07 -0400812Advanced usage: you can derive subclasses of :class:`Template` to customize
813the placeholder syntax, delimiter character, or the entire regular expression
814used to parse template strings. To do this, you can override these class
815attributes:
Georg Brandl116aa622007-08-15 14:28:22 +0000816
Barry Warsaw9f74deb2017-03-28 10:02:07 -0400817* *delimiter* -- This is the literal string describing a placeholder
818 introducing delimiter. The default value is ``$``. Note that this should
819 *not* be a regular expression, as the implementation will call
820 :meth:`re.escape` on this string as needed. Note further that you cannot
821 change the delimiter after class creation (i.e. a different delimiter must
822 be set in the subclass's class namespace).
Georg Brandl116aa622007-08-15 14:28:22 +0000823
824* *idpattern* -- This is the regular expression describing the pattern for
Barry Warsawba427962017-09-04 16:32:10 -0400825 non-braced placeholders. The default value is the regular expression
Serhiy Storchaka87be28f2018-01-04 19:20:11 +0200826 ``(?a:[_a-z][_a-z0-9]*)``. If this is given and *braceidpattern* is
INADA Naokib22273e2017-10-13 16:02:23 +0900827 ``None`` this pattern will also apply to braced placeholders.
828
829 .. note::
830
831 Since default *flags* is ``re.IGNORECASE``, pattern ``[a-z]`` can match
Barry Warsawe256b402017-11-21 10:28:13 -0500832 with some non-ASCII characters. That's why we use the local ``a`` flag
Serhiy Storchaka87be28f2018-01-04 19:20:11 +0200833 here.
Barry Warsawba427962017-09-04 16:32:10 -0400834
835 .. versionchanged:: 3.7
836 *braceidpattern* can be used to define separate patterns used inside and
837 outside the braces.
838
839* *braceidpattern* -- This is like *idpattern* but describes the pattern for
840 braced placeholders. Defaults to ``None`` which means to fall back to
841 *idpattern* (i.e. the same pattern is used both inside and outside braces).
842 If given, this allows you to define different patterns for braced and
843 unbraced placeholders.
844
845 .. versionadded:: 3.7
Georg Brandl116aa622007-08-15 14:28:22 +0000846
Georg Brandl056cb932010-07-29 17:16:10 +0000847* *flags* -- The regular expression flags that will be applied when compiling
848 the regular expression used for recognizing substitutions. The default value
849 is ``re.IGNORECASE``. Note that ``re.VERBOSE`` will always be added to the
850 flags, so custom *idpattern*\ s must follow conventions for verbose regular
851 expressions.
852
853 .. versionadded:: 3.2
854
Georg Brandl116aa622007-08-15 14:28:22 +0000855Alternatively, you can provide the entire regular expression pattern by
856overriding the class attribute *pattern*. If you do this, the value must be a
857regular expression object with four named capturing groups. The capturing
858groups correspond to the rules given above, along with the invalid placeholder
859rule:
860
861* *escaped* -- This group matches the escape sequence, e.g. ``$$``, in the
862 default pattern.
863
864* *named* -- This group matches the unbraced placeholder name; it should not
865 include the delimiter in capturing group.
866
867* *braced* -- This group matches the brace enclosed placeholder name; it should
868 not include either the delimiter or braces in the capturing group.
869
870* *invalid* -- This group matches any other delimiter pattern (usually a single
871 delimiter), and it should appear last in the regular expression.
872
873
Georg Brandlabc38772009-04-12 15:51:51 +0000874Helper functions
Georg Brandl116aa622007-08-15 14:28:22 +0000875----------------
876
Georg Brandl10430ad2009-09-26 20:59:11 +0000877.. function:: capwords(s, sep=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000878
Ezio Melottia40bdda2009-09-26 12:33:22 +0000879 Split the argument into words using :meth:`str.split`, capitalize each word
880 using :meth:`str.capitalize`, and join the capitalized words using
881 :meth:`str.join`. If the optional second argument *sep* is absent
882 or ``None``, runs of whitespace characters are replaced by a single space
883 and leading and trailing whitespace are removed, otherwise *sep* is used to
884 split and join the words.