Debian Codegraph @

Doc/library/string.rst

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