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'``
476 :ref:`float presentation type <n-format-float>` or
477 :ref:`integer presentation type <n-format-integer>` instead.
478
479 .. versionchanged:: 3.1
480 Added the ``','`` option (see also :pep:`378`).
481
482 .. versionchanged:: 3.6
483 Added the ``'_'`` option (see also :pep:`515`).
484
485 .. versionchanged:: 3.14
486 Support the *grouping* option for the fractional part.
487
488 Finally, the *type* determines how the data should be presented.
489
490 The available string presentation types are:
491
492 +---------+----------------------------------------------------------+
493 | Type | Meaning |
494 +=========+==========================================================+
495 | ``'s'`` | String format. This is the default type for strings and |
496 | | may be omitted. |
497 +---------+----------------------------------------------------------+
498 | None | The same as ``'s'``. |
499 +---------+----------------------------------------------------------+
500
501 The available integer presentation types are:
502
503 +---------+----------------------------------------------------------+
504 | Type | Meaning |
505 +=========+==========================================================+
506 | ``'b'`` | Binary format. Outputs the number in base 2. |
507 +---------+----------------------------------------------------------+
508 | ``'c'`` | Character. Converts the integer to the corresponding |
509 | | unicode character before printing. |
510 +---------+----------------------------------------------------------+
511 | ``'d'`` | Decimal Integer. Outputs the number in base 10. |
512 +---------+----------------------------------------------------------+
513 | ``'o'`` | Octal format. Outputs the number in base 8. |
514 +---------+----------------------------------------------------------+
515 | ``'x'`` | Hex format. Outputs the number in base 16, using |
516 | | lower-case letters for the digits above 9. |
517 +---------+----------------------------------------------------------+
518 | ``'X'`` | Hex format. Outputs the number in base 16, using |
519 | | upper-case letters for the digits above 9. |
520 | | In case ``'#'`` is specified, the prefix ``'0x'`` will |
521 | | be upper-cased to ``'0X'`` as well. |
522 +---------+----------------------------------------------------------+
523 | ``'n'`` | .. _n-format-integer: |
524 | | |
525 | | Number. This is the same as ``'d'``, except that it uses |
526 | | the current locale setting to insert the appropriate |
527 | | digit group separators. Note that the default locale is |
528 | | not the system locale. Depending on your use case, you |
529 | | may wish to set :const:`~locale.LC_NUMERIC` with |
530 | | :func:`locale.setlocale` before using ``'n'``. |
531 +---------+----------------------------------------------------------+
532 | None | The same as ``'d'``. |
533 +---------+----------------------------------------------------------+
534
535 In addition to the above presentation types, integers can be formatted
536 with the floating-point presentation types listed below (except
537 ``'n'`` and ``None``). When doing so, :func:`float` is used to convert the
538 integer to a floating-point number before formatting.
539
540 The available presentation types for :class:`float` and
541 :class:`~decimal.Decimal` values are:
542
543 +---------+----------------------------------------------------------+
544 | Type | Meaning |
545 +=========+==========================================================+
546 | ``'e'`` | Scientific notation. For a given precision ``p``, |
547 | | formats the number in scientific notation with the |
548 | | letter 'e' separating the coefficient from the exponent. |
549 | | The coefficient has one digit before and ``p`` digits |
550 | | after the decimal point, for a total of ``p + 1`` |
551 | | significant digits. With no precision given, uses a |
552 | | precision of ``6`` digits after the decimal point for |
553 | | :class:`float`, and shows all coefficient digits |
554 | | for :class:`~decimal.Decimal`. If ``p=0``, the decimal |
555 | | point is omitted unless the ``#`` option is used. |
556 | | |
557 | | For :class:`float`, the exponent always contains at |
558 | | least two digits, and is zero if the value is zero. |
559 +---------+----------------------------------------------------------+
560 | ``'E'`` | Scientific notation. Same as ``'e'`` except it uses |
561 | | an upper case 'E' as the separator character. |
562 +---------+----------------------------------------------------------+
563 | ``'f'`` | Fixed-point notation. For a given precision ``p``, |
564 | | formats the number as a decimal number with exactly |
565 | | ``p`` digits following the decimal point. With no |
566 | | precision given, uses a precision of ``6`` digits after |
567 | | the decimal point for :class:`float`, and uses a |
568 | | precision large enough to show all coefficient digits |
569 | | for :class:`~decimal.Decimal`. If ``p=0``, the decimal |
570 | | point is omitted unless the ``#`` option is used. |
571 +---------+----------------------------------------------------------+
572 | ``'F'`` | Fixed-point notation. Same as ``'f'``, but converts |
573 | | ``nan`` to ``NAN`` and ``inf`` to ``INF``. |
574 +---------+----------------------------------------------------------+
575 | ``'g'`` | General format. For a given precision ``p >= 1``, |
576 | | this rounds the number to ``p`` significant digits and |
577 | | then formats the result in either fixed-point format |
578 | | or in scientific notation, depending on its magnitude. |
579 | | A precision of ``0`` is treated as equivalent to a |
580 | | precision of ``1``. |
581 | | |
582 | | The precise rules are as follows: suppose that the |
583 | | result formatted with presentation type ``'e'`` and |
584 | | precision ``p-1`` would have exponent ``exp``. Then, |
585 | | if ``m <= exp < p``, where ``m`` is -4 for floats and -6 |
586 | | for :class:`Decimals <decimal.Decimal>`, the number is |
587 | | formatted with presentation type ``'f'`` and precision |
588 | | ``p-1-exp``. Otherwise, the number is formatted |
589 | | with presentation type ``'e'`` and precision ``p-1``. |
590 | | In both cases insignificant trailing zeros are removed |
591 | | from the significand, and the decimal point is also |
592 | | removed if there are no remaining digits following it, |
593 | | unless the ``'#'`` option is used. |
594 | | |
595 | | With no precision given, uses a precision of ``6`` |
596 | | significant digits for :class:`float`. For |
597 | | :class:`~decimal.Decimal`, the coefficient of the result |
598 | | is formed from the coefficient digits of the value; |
599 | | scientific notation is used for values smaller than |
600 | | ``1e-6`` in absolute value and values where the place |
601 | | value of the least significant digit is larger than 1, |
602 | | and fixed-point notation is used otherwise. |
603 | | |
604 | | Positive and negative infinity, positive and negative |
605 | | zero, and nans, are formatted as ``inf``, ``-inf``, |
606 | | ``0``, ``-0`` and ``nan`` respectively, regardless of |
607 | | the precision. |
608 +---------+----------------------------------------------------------+
609 | ``'G'`` | General format. Same as ``'g'`` except switches to |
610 | | ``'E'`` if the number gets too large. The |
611 | | representations of infinity and NaN are uppercased, too. |
612 +---------+----------------------------------------------------------+
613 | ``'n'`` | .. _n-format-float: |
614 | | |
615 | | Number. This is the same as ``'g'``, except that it uses |
616 | | the current locale setting to insert the appropriate |
617 | | digit group separators for the integral part of a |
618 | | number. Note that the default locale is not the system |
619 | | locale. Depending on your use case, you may wish to set |
620 | | :const:`~locale.LC_NUMERIC` with |
621 | | :func:`locale.setlocale` before using ``'n'``. |
622 +---------+----------------------------------------------------------+
623 | ``'%'`` | Percentage. Multiplies the number by 100 and displays |
624 | | in fixed (``'f'``) format, followed by a percent sign. |
625 +---------+----------------------------------------------------------+
626 | None | For :class:`float` this is like the ``'g'`` type, except |
627 | | that when fixed-point notation is used to format the |
628 | | result, it always includes at least one digit past the |
629 | | decimal point, and switches to the scientific notation |
630 | | when ``exp >= p - 1``. When the precision is not |
631 | | specified, the latter will be as large as needed to |
632 | | represent the given value faithfully. |
633 | | |
634 | | For :class:`~decimal.Decimal`, this is the same as |
635 | | either ``'g'`` or ``'G'`` depending on the value of |
636 | | ``context.capitals`` for the current decimal context. |
637 | | |
638 | | The overall effect is to match the output of :func:`str` |
639 | | as altered by the other format modifiers. |
640 +---------+----------------------------------------------------------+
641
642 The result should be correctly rounded to a given precision ``p`` of digits
643 after the decimal point. The rounding mode for :class:`float` matches that
644 of the :func:`round` builtin. For :class:`~decimal.Decimal`, the rounding
645 mode of the current :ref:`context <decimal-context>` will be used.
646
647 The available presentation types for :class:`complex` are the same as those for
648 :class:`float` (``'%'`` is not allowed). Both the real and imaginary components
649 of a complex number are formatted as floating-point numbers, according to the
650 specified presentation type. They are separated by the mandatory sign of the
651 imaginary part, the latter being terminated by a ``j`` suffix. If the presentation
652 type is missing, the result will match the output of :func:`str` (complex numbers with
653 a non-zero real part are also surrounded by parentheses), possibly altered by
654 other format modifiers.
655
656
657 .. _formatexamples:
658
659 Format examples
660 ^^^^^^^^^^^^^^^
661
662 This section contains examples of the :meth:`str.format` syntax and
663 comparison with the old ``%``-formatting.
664
665 In most of the cases the syntax is similar to the old ``%``-formatting, with the
666 addition of the ``{}`` and with ``:`` used instead of ``%``.
667 For example, ``'%03.2f'`` can be translated to ``'{:03.2f}'``.
668
669 The new format syntax also supports new and different options, shown in the
670 following examples.
671
672 Accessing arguments by position::
673
674 >>> '{0}, {1}, {2}'.format('a', 'b', 'c')
675 'a, b, c'
676 >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only
677 'a, b, c'
678 >>> '{2}, {1}, {0}'.format('a', 'b', 'c')
679 'c, b, a'
680 >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence
681 'c, b, a'
682 >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated
683 'abracadabra'
684
685 Accessing arguments by name::
686
687 >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
688 'Coordinates: 37.24N, -115.81W'
689 >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
690 >>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
691 'Coordinates: 37.24N, -115.81W'
692
693 Accessing arguments' attributes::
694
695 >>> c = 3-5j
696 >>> ('The complex number {0} is formed from the real part {0.real} '
697 ... 'and the imaginary part {0.imag}.').format(c)
698 'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
699 >>> class Point:
700 ... def __init__(self, x, y):
701 ... self.x, self.y = x, y
702 ... def __str__(self):
703 ... return 'Point({self.x}, {self.y})'.format(self=self)
704 ...
705 >>> str(Point(4, 2))
706 'Point(4, 2)'
707
708 Accessing arguments' items::
709
710 >>> coord = (3, 5)
711 >>> 'X: {0[0]}; Y: {0[1]}'.format(coord)
712 'X: 3; Y: 5'
713
714 Replacing ``%s`` and ``%r``::
715
716 >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
717 "repr() shows quotes: 'test1'; str() doesn't: test2"
718
719 Aligning the text and specifying a width::
720
721 >>> '{:<30}'.format('left aligned')
722 'left aligned '
723 >>> '{:>30}'.format('right aligned')
724 ' right aligned'
725 >>> '{:^30}'.format('centered')
726 ' centered '
727 >>> '{:*^30}'.format('centered') # use '*' as a fill char
728 '***********centered***********'
729
730 Replacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign::
731
732 >>> '{:+f}; {:+f}'.format(3.14, -3.14) # show it always
733 '+3.140000; -3.140000'
734 >>> '{: f}; {: f}'.format(3.14, -3.14) # show a space for positive numbers
735 ' 3.140000; -3.140000'
736 >>> '{:-f}; {:-f}'.format(3.14, -3.14) # show only the minus -- same as '{:f}; {:f}'
737 '3.140000; -3.140000'
738
739 Replacing ``%x`` and ``%o`` and converting the value to different bases::
740
741 >>> # format also supports binary numbers
742 >>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
743 'int: 42; hex: 2a; oct: 52; bin: 101010'
744 >>> # with 0x, 0o, or 0b as prefix:
745 >>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
746 'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
747
748 Using the comma or the underscore as a digit group separator::
749
750 >>> '{:,}'.format(1234567890)
751 '1,234,567,890'
752 >>> '{:_}'.format(1234567890)
753 '1_234_567_890'
754 >>> '{:_b}'.format(1234567890)
755 '100_1001_1001_0110_0000_0010_1101_0010'
756 >>> '{:_x}'.format(1234567890)
757 '4996_02d2'
758 >>> '{:_}'.format(123456789.123456789)
759 '123_456_789.12345679'
760 >>> '{:.,}'.format(123456789.123456789)
761 '123456789.123,456,79'
762 >>> '{:,._}'.format(123456789.123456789)
763 '123,456,789.123_456_79'
764
765 Expressing a percentage::
766
767 >>> points = 19
768 >>> total = 22
769 >>> 'Correct answers: {:.2%}'.format(points/total)
770 'Correct answers: 86.36%'
771
772 Using type-specific formatting::
773
774 >>> import datetime as dt
775 >>> d = dt.datetime(2010, 7, 4, 12, 15, 58)
776 >>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
777 '2010-07-04 12:15:58'
778
779 Nesting arguments and more complex examples::
780
781 >>> for align, text in zip('<^>', ['left', 'center', 'right']):
782 ... '{0:{fill}{align}16}'.format(text, fill=align, align=align)
783 ...
784 'left<<<<<<<<<<<<'
785 '^^^^^center^^^^^'
786 '>>>>>>>>>>>right'
787 >>>
788 >>> octets = [192, 168, 0, 1]
789 >>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
790 'C0A80001'
791 >>> int(_, 16)
792 3232235521
793 >>>
794 >>> width = 5
795 >>> for num in range(5,12): #doctest: +NORMALIZE_WHITESPACE
796 ... for base in 'dXob':
797 ... print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
798 ... print()
799 ...
800 5 5 5 101
801 6 6 6 110
802 7 7 7 111
803 8 8 10 1000
804 9 9 11 1001
805 10 A 12 1010
806 11 B 13 1011
807
808
809
810 .. _template-strings-pep292:
811
812 Template strings ($-strings)
813 ----------------------------
814
815 .. note::
816
817 The feature described here was introduced in Python 2.4;
818 a simple templating method based upon regular expressions.
819 It predates :meth:`str.format`, :ref:`formatted string literals <f-strings>`,
820 and :ref:`template string literals <template-strings>`.
821
822 It is unrelated to template string literals (t-strings),
823 which were introduced in Python 3.14.
824 These evaluate to :class:`string.templatelib.Template` objects,
825 found in the :mod:`string.templatelib` module.
826
827 Template strings provide simpler string substitutions as described in
828 :pep:`292`. A primary use case for template strings is for
829 internationalization (i18n) since in that context, the simpler syntax and
830 functionality makes it easier to translate than other built-in string
831 formatting facilities in Python. As an example of a library built on template
832 strings for i18n, see the
833 `flufl.i18n <https://flufli18n.readthedocs.io/en/latest/>`_ package.
834
835 .. index:: single: $ (dollar); in template strings
836
837 Template strings support ``$``-based substitutions, using the following rules:
838
839 * ``$$`` is an escape; it is replaced with a single ``$``.
840
841 * ``$identifier`` names a substitution placeholder matching a mapping key of
842 ``"identifier"``. By default, ``"identifier"`` is restricted to any
843 case-insensitive ASCII alphanumeric string (including underscores) that
844 starts with an underscore or ASCII letter. The first non-identifier
845 character after the ``$`` character terminates this placeholder
846 specification.
847
848 * ``${identifier}`` is equivalent to ``$identifier``. It is required when
849 valid identifier characters follow the placeholder but are not part of the
850 placeholder, such as ``"${noun}ification"``.
851
852 Any other appearance of ``$`` in the string will result in a :exc:`ValueError`
853 being raised.
854
855 The :mod:`!string` module provides a :class:`Template` class that implements
856 these rules. The methods of :class:`Template` are:
857
858
859 .. class:: Template(template)
860
861 The constructor takes a single argument which is the template string.
862
863
864 .. method:: substitute(mapping={}, /, **kwds)
865
866 Performs the template substitution, returning a new string. *mapping* is
867 any dictionary-like object with keys that match the placeholders in the
868 template. Alternatively, you can provide keyword arguments, where the
869 keywords are the placeholders. When both *mapping* and *kwds* are given
870 and there are duplicates, the placeholders from *kwds* take precedence.
871
872
873 .. method:: safe_substitute(mapping={}, /, **kwds)
874
875 Like :meth:`substitute`, except that if placeholders are missing from
876 *mapping* and *kwds*, instead of raising a :exc:`KeyError` exception, the
877 original placeholder will appear in the resulting string intact. Also,
878 unlike with :meth:`substitute`, any other appearances of the ``$`` will
879 simply return ``$`` instead of raising :exc:`ValueError`.
880
881 While other exceptions may still occur, this method is called "safe"
882 because it always tries to return a usable string instead of
883 raising an exception. In another sense, :meth:`safe_substitute` may be
884 anything other than safe, since it will silently ignore malformed
885 templates containing dangling delimiters, unmatched braces, or
886 placeholders that are not valid Python identifiers.
887
888
889 .. method:: is_valid()
890
891 Returns ``False`` if the template has invalid placeholders that will cause
892 :meth:`substitute` to raise :exc:`ValueError`.
893
894 .. versionadded:: 3.11
895
896
897 .. method:: get_identifiers()
898
899 Returns a list of the valid identifiers in the template, in the order
900 they first appear, ignoring any invalid identifiers.
901
902 .. versionadded:: 3.11
903
904 :class:`Template` instances also provide one public data attribute:
905
906 .. attribute:: template
907
908 This is the object passed to the constructor's *template* argument. In
909 general, you shouldn't change it, but read-only access is not enforced.
910
911 Here is an example of how to use a Template::
912
913 >>> from string import Template
914 >>> s = Template('$who likes $what')
915 >>> s.substitute(who='tim', what='kung pao')
916 'tim likes kung pao'
917 >>> d = dict(who='tim')
918 >>> Template('Give $who $100').substitute(d)
919 Traceback (most recent call last):
920 ...
921 ValueError: Invalid placeholder in string: line 1, col 11
922 >>> Template('$who likes $what').substitute(d)
923 Traceback (most recent call last):
924 ...
925 KeyError: 'what'
926 >>> Template('$who likes $what').safe_substitute(d)
927 'tim likes $what'
928
929 Advanced usage: you can derive subclasses of :class:`Template` to customize
930 the placeholder syntax, delimiter character, or the entire regular expression
931 used to parse template strings. To do this, you can override these class
932 attributes:
933
934 * *delimiter* -- This is the literal string describing a placeholder
935 introducing delimiter. The default value is ``$``. Note that this should
936 *not* be a regular expression, as the implementation will call
937 :meth:`re.escape` on this string as needed. Note further that you cannot
938 change the delimiter after class creation (i.e. a different delimiter must
939 be set in the subclass's class namespace).
940
941 * *idpattern* -- This is the regular expression describing the pattern for
942 non-braced placeholders. The default value is the regular expression
943 ``(?a:[_a-z][_a-z0-9]*)``. If this is given and *braceidpattern* is
944 ``None`` this pattern will also apply to braced placeholders.
945
946 .. note::
947
948 Since default *flags* is ``re.IGNORECASE``, pattern ``[a-z]`` can match
949 with some non-ASCII characters. That's why we use the local ``a`` flag
950 here.
951
952 .. versionchanged:: 3.7
953 *braceidpattern* can be used to define separate patterns used inside and
954 outside the braces.
955
956 * *braceidpattern* -- This is like *idpattern* but describes the pattern for
957 braced placeholders. Defaults to ``None`` which means to fall back to
958 *idpattern* (i.e. the same pattern is used both inside and outside braces).
959 If given, this allows you to define different patterns for braced and
960 unbraced placeholders.
961
962 .. versionadded:: 3.7
963
964 * *flags* -- The regular expression flags that will be applied when compiling
965 the regular expression used for recognizing substitutions. The default value
966 is ``re.IGNORECASE``. Note that ``re.VERBOSE`` will always be added to the
967 flags, so custom *idpattern*\ s must follow conventions for verbose regular
968 expressions.
969
970 .. versionadded:: 3.2
971
972 Alternatively, you can provide the entire regular expression pattern by
973 overriding the class attribute *pattern*. If you do this, the value must be a
974 regular expression object with four named capturing groups. The capturing
975 groups correspond to the rules given above, along with the invalid placeholder
976 rule:
977
978 * *escaped* -- This group matches the escape sequence, e.g. ``$$``, in the
979 default pattern.
980
981 * *named* -- This group matches the unbraced placeholder name; it should not
982 include the delimiter in capturing group.
983
984 * *braced* -- This group matches the brace enclosed placeholder name; it should
985 not include either the delimiter or braces in the capturing group.
986
987 * *invalid* -- This group matches any other delimiter pattern (usually a single
988 delimiter), and it should appear last in the regular expression.
989
990 The methods on this class will raise :exc:`ValueError` if the pattern matches
991 the template without one of these named groups matching.
992
993
994 Helper functions
995 ----------------
996
997 .. function:: capwords(s, sep=None)
998
999 Split the argument into words using :meth:`str.split`, capitalize each word
1000 using :meth:`str.capitalize`, and join the capitalized words using
1001 :meth:`str.join`. If the optional second argument *sep* is absent
1002 or ``None``, runs of whitespace characters are replaced by a single space
1003 and leading and trailing whitespace are removed, otherwise *sep* is used to
1004 split and join the words.