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