blob: b785fc2c048c0db65cd40f2425c813d86e480858 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`string` --- Common string operations
2==========================================
3
4.. module:: string
5 :synopsis: Common string operations.
6
7
8.. index:: module: re
9
Antoine Pitroude5b0242010-07-21 15:54:48 +000010The :mod:`string` module contains a number of useful constants and classes
11for string formatting. In addition, Python's built-in string classes
12support the sequence type methods described in the :ref:`typesseq`
13section, and also the string-specific methods described in the
14:ref:`string-methods` section. To output formatted strings, see the
15:ref:`string-formatting` section. Also, see the :mod:`re` module for
16string functions based on regular expressions.
Georg Brandl116aa622007-08-15 14:28:22 +000017
Éric Araujo6e6cb8e2010-11-16 19:13:50 +000018.. seealso::
19
20 Latest version of the :source:`string module Python source code
21 <Lib/string.py>`
22
Georg Brandl116aa622007-08-15 14:28:22 +000023
24String constants
25----------------
26
27The constants defined in this module are:
28
29
30.. data:: ascii_letters
31
32 The concatenation of the :const:`ascii_lowercase` and :const:`ascii_uppercase`
33 constants described below. This value is not locale-dependent.
34
35
36.. data:: ascii_lowercase
37
38 The lowercase letters ``'abcdefghijklmnopqrstuvwxyz'``. This value is not
39 locale-dependent and will not change.
40
41
42.. data:: ascii_uppercase
43
44 The uppercase letters ``'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. This value is not
45 locale-dependent and will not change.
46
47
48.. data:: digits
49
50 The string ``'0123456789'``.
51
52
53.. data:: hexdigits
54
55 The string ``'0123456789abcdefABCDEF'``.
56
57
58.. data:: octdigits
59
60 The string ``'01234567'``.
61
62
63.. data:: punctuation
64
65 String of ASCII characters which are considered punctuation characters
66 in the ``C`` locale.
67
68
69.. data:: printable
70
71 String of ASCII characters which are considered printable. This is a
72 combination of :const:`digits`, :const:`ascii_letters`, :const:`punctuation`,
73 and :const:`whitespace`.
74
75
76.. data:: whitespace
77
Georg Brandl50767402008-11-22 08:31:09 +000078 A string containing all ASCII characters that are considered whitespace.
Georg Brandl116aa622007-08-15 14:28:22 +000079 This includes the characters space, tab, linefeed, return, formfeed, and
80 vertical tab.
81
82
Georg Brandl4b491312007-08-31 09:22:56 +000083.. _string-formatting:
84
85String Formatting
86-----------------
87
Benjamin Peterson50923f92008-05-25 19:45:17 +000088The built-in string class provides the ability to do complex variable
89substitutions and value formatting via the :func:`format` method described in
90:pep:`3101`. The :class:`Formatter` class in the :mod:`string` module allows
91you to create and customize your own string formatting behaviors using the same
92implementation as the built-in :meth:`format` method.
Georg Brandl4b491312007-08-31 09:22:56 +000093
Benjamin Peterson1baf4652009-12-31 03:11:23 +000094
Georg Brandl4b491312007-08-31 09:22:56 +000095.. class:: Formatter
96
97 The :class:`Formatter` class has the following public methods:
98
99 .. method:: format(format_string, *args, *kwargs)
100
101 :meth:`format` is the primary API method. It takes a format template
102 string, and an arbitrary set of positional and keyword argument.
103 :meth:`format` is just a wrapper that calls :meth:`vformat`.
104
105 .. method:: vformat(format_string, args, kwargs)
Georg Brandl48310cd2009-01-03 21:18:54 +0000106
Georg Brandl4b491312007-08-31 09:22:56 +0000107 This function does the actual work of formatting. It is exposed as a
108 separate function for cases where you want to pass in a predefined
109 dictionary of arguments, rather than unpacking and repacking the
110 dictionary as individual arguments using the ``*args`` and ``**kwds``
111 syntax. :meth:`vformat` does the work of breaking up the format template
112 string into character data and replacement fields. It calls the various
113 methods described below.
114
115 In addition, the :class:`Formatter` defines a number of methods that are
116 intended to be replaced by subclasses:
117
118 .. method:: parse(format_string)
Georg Brandl48310cd2009-01-03 21:18:54 +0000119
Georg Brandl4b491312007-08-31 09:22:56 +0000120 Loop over the format_string and return an iterable of tuples
121 (*literal_text*, *field_name*, *format_spec*, *conversion*). This is used
Georg Brandl70cd7bc2010-10-26 19:31:06 +0000122 by :meth:`vformat` to break the string into either literal text, or
Georg Brandl4b491312007-08-31 09:22:56 +0000123 replacement fields.
Georg Brandl48310cd2009-01-03 21:18:54 +0000124
Georg Brandl4b491312007-08-31 09:22:56 +0000125 The values in the tuple conceptually represent a span of literal text
126 followed by a single replacement field. If there is no literal text
127 (which can happen if two replacement fields occur consecutively), then
128 *literal_text* will be a zero-length string. If there is no replacement
129 field, then the values of *field_name*, *format_spec* and *conversion*
130 will be ``None``.
131
Eric Smith9d4ba392007-09-02 15:33:26 +0000132 .. method:: get_field(field_name, args, kwargs)
Georg Brandl4b491312007-08-31 09:22:56 +0000133
134 Given *field_name* as returned by :meth:`parse` (see above), convert it to
Georg Brandl7f13e6b2007-08-31 10:37:15 +0000135 an object to be formatted. Returns a tuple (obj, used_key). The default
136 version takes strings of the form defined in :pep:`3101`, such as
137 "0[name]" or "label.title". *args* and *kwargs* are as passed in to
138 :meth:`vformat`. The return value *used_key* has the same meaning as the
139 *key* parameter to :meth:`get_value`.
Georg Brandl4b491312007-08-31 09:22:56 +0000140
141 .. method:: get_value(key, args, kwargs)
Georg Brandl48310cd2009-01-03 21:18:54 +0000142
Georg Brandl4b491312007-08-31 09:22:56 +0000143 Retrieve a given field value. The *key* argument will be either an
144 integer or a string. If it is an integer, it represents the index of the
145 positional argument in *args*; if it is a string, then it represents a
146 named argument in *kwargs*.
147
148 The *args* parameter is set to the list of positional arguments to
149 :meth:`vformat`, and the *kwargs* parameter is set to the dictionary of
150 keyword arguments.
151
152 For compound field names, these functions are only called for the first
153 component of the field name; Subsequent components are handled through
154 normal attribute and indexing operations.
155
156 So for example, the field expression '0.name' would cause
157 :meth:`get_value` to be called with a *key* argument of 0. The ``name``
158 attribute will be looked up after :meth:`get_value` returns by calling the
159 built-in :func:`getattr` function.
160
161 If the index or keyword refers to an item that does not exist, then an
162 :exc:`IndexError` or :exc:`KeyError` should be raised.
163
164 .. method:: check_unused_args(used_args, args, kwargs)
165
166 Implement checking for unused arguments if desired. The arguments to this
167 function is the set of all argument keys that were actually referred to in
168 the format string (integers for positional arguments, and strings for
169 named arguments), and a reference to the *args* and *kwargs* that was
170 passed to vformat. The set of unused args can be calculated from these
Georg Brandl7cb13192010-08-03 12:06:29 +0000171 parameters. :meth:`check_unused_args` is assumed to raise an exception if
Georg Brandl4b491312007-08-31 09:22:56 +0000172 the check fails.
173
174 .. method:: format_field(value, format_spec)
175
176 :meth:`format_field` simply calls the global :func:`format` built-in. The
177 method is provided so that subclasses can override it.
178
179 .. method:: convert_field(value, conversion)
Georg Brandl48310cd2009-01-03 21:18:54 +0000180
Georg Brandl4b491312007-08-31 09:22:56 +0000181 Converts the value (returned by :meth:`get_field`) given a conversion type
Ezio Melottid2191e02010-07-02 23:18:51 +0000182 (as in the tuple returned by the :meth:`parse` method). The default
Georg Brandl4b491312007-08-31 09:22:56 +0000183 version understands 'r' (repr) and 's' (str) conversion types.
184
Georg Brandl4b491312007-08-31 09:22:56 +0000185
186.. _formatstrings:
187
188Format String Syntax
189--------------------
190
191The :meth:`str.format` method and the :class:`Formatter` class share the same
192syntax for format strings (although in the case of :class:`Formatter`,
Ezio Melottid2191e02010-07-02 23:18:51 +0000193subclasses can define their own format string syntax).
Georg Brandl4b491312007-08-31 09:22:56 +0000194
195Format strings contain "replacement fields" surrounded by curly braces ``{}``.
196Anything that is not contained in braces is considered literal text, which is
197copied unchanged to the output. If you need to include a brace character in the
198literal text, it can be escaped by doubling: ``{{`` and ``}}``.
199
200The grammar for a replacement field is as follows:
201
202 .. productionlist:: sf
Georg Brandl2f3ed682009-09-01 07:42:40 +0000203 replacement_field: "{" [`field_name`] ["!" `conversion`] [":" `format_spec`] "}"
Eric Smithc4cae322009-04-22 00:53:01 +0000204 field_name: arg_name ("." `attribute_name` | "[" `element_index` "]")*
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000205 arg_name: [`identifier` | `integer`]
Georg Brandl4b491312007-08-31 09:22:56 +0000206 attribute_name: `identifier`
Eric Smith2e9f2022010-02-25 14:58:13 +0000207 element_index: `integer` | `index_string`
208 index_string: <any source character except "]"> +
Benjamin Peterson065ba702008-11-09 01:43:02 +0000209 conversion: "r" | "s" | "a"
Georg Brandl4b491312007-08-31 09:22:56 +0000210 format_spec: <described in the next section>
Georg Brandl48310cd2009-01-03 21:18:54 +0000211
Georg Brandl2f3ed682009-09-01 07:42:40 +0000212In less formal terms, the replacement field can start with a *field_name* that specifies
Eric Smithc4cae322009-04-22 00:53:01 +0000213the object whose value is to be formatted and inserted
214into the output instead of the replacement field.
215The *field_name* is optionally followed by a *conversion* field, which is
Georg Brandl4b491312007-08-31 09:22:56 +0000216preceded by an exclamation point ``'!'``, and a *format_spec*, which is preceded
Eric Smithc4cae322009-04-22 00:53:01 +0000217by a colon ``':'``. These specify a non-default format for the replacement value.
Georg Brandl4b491312007-08-31 09:22:56 +0000218
Ezio Melottid2191e02010-07-02 23:18:51 +0000219See also the :ref:`formatspec` section.
220
Eric Smithc4cae322009-04-22 00:53:01 +0000221The *field_name* itself begins with an *arg_name* that is either either a number or a
222keyword. If it's a number, it refers to a positional argument, and if it's a keyword,
223it refers to a named keyword argument. If the numerical arg_names in a format string
224are 0, 1, 2, ... in sequence, they can all be omitted (not just some)
225and the numbers 0, 1, 2, ... will be automatically inserted in that order.
226The *arg_name* can be followed by any number of index or
Georg Brandl4b491312007-08-31 09:22:56 +0000227attribute expressions. An expression of the form ``'.name'`` selects the named
228attribute using :func:`getattr`, while an expression of the form ``'[index]'``
229does an index lookup using :func:`__getitem__`.
230
Ezio Melottid2191e02010-07-02 23:18:51 +0000231.. versionchanged:: 3.1
232 The positional argument specifiers can be omitted, so ``'{} {}'`` is
233 equivalent to ``'{0} {1}'``.
234
Georg Brandl4b491312007-08-31 09:22:56 +0000235Some simple format string examples::
236
237 "First, thou shalt count to {0}" # References first positional argument
Benjamin Peterson5879d412009-03-30 14:51:56 +0000238 "Bring me a {}" # Implicitly references the first positional argument
Georg Brandl2f3ed682009-09-01 07:42:40 +0000239 "From {} to {}" # Same as "From {0} to {1}"
Georg Brandl4b491312007-08-31 09:22:56 +0000240 "My quest is {name}" # References keyword argument 'name'
241 "Weight in tons {0.weight}" # 'weight' attribute of first positional arg
242 "Units destroyed: {players[0]}" # First element of keyword argument 'players'.
Georg Brandl48310cd2009-01-03 21:18:54 +0000243
Georg Brandl4b491312007-08-31 09:22:56 +0000244The *conversion* field causes a type coercion before formatting. Normally, the
245job of formatting a value is done by the :meth:`__format__` method of the value
246itself. However, in some cases it is desirable to force a type to be formatted
247as a string, overriding its own definition of formatting. By converting the
248value to a string before calling :meth:`__format__`, the normal formatting logic
249is bypassed.
250
Georg Brandl559e5d72008-06-11 18:37:52 +0000251Three conversion flags are currently supported: ``'!s'`` which calls :func:`str`
252on the value, ``'!r'`` which calls :func:`repr` and ``'!a'`` which calls
253:func:`ascii`.
Georg Brandl4b491312007-08-31 09:22:56 +0000254
255Some examples::
256
257 "Harold's a clever {0!s}" # Calls str() on the argument first
258 "Bring out the holy {name!r}" # Calls repr() on the argument first
Georg Brandl2f3ed682009-09-01 07:42:40 +0000259 "More {!a}" # Calls ascii() on the argument first
Georg Brandl4b491312007-08-31 09:22:56 +0000260
261The *format_spec* field contains a specification of how the value should be
262presented, including such details as field width, alignment, padding, decimal
Eric Smith0f7affe2010-02-15 11:57:31 +0000263precision and so on. Each value type can define its own "formatting
Georg Brandl4b491312007-08-31 09:22:56 +0000264mini-language" or interpretation of the *format_spec*.
265
266Most built-in types support a common formatting mini-language, which is
267described in the next section.
268
269A *format_spec* field can also include nested replacement fields within it.
270These nested replacement fields can contain only a field name; conversion flags
271and format specifications are not allowed. The replacement fields within the
272format_spec are substituted before the *format_spec* string is interpreted.
273This allows the formatting of a value to be dynamically specified.
274
Ezio Melottid2191e02010-07-02 23:18:51 +0000275See the :ref:`formatexamples` section for some examples.
Georg Brandl4b491312007-08-31 09:22:56 +0000276
Georg Brandl4b491312007-08-31 09:22:56 +0000277
278.. _formatspec:
279
280Format Specification Mini-Language
281^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
282
283"Format specifications" are used within replacement fields contained within a
284format string to define how individual values are presented (see
Ezio Melottid2191e02010-07-02 23:18:51 +0000285:ref:`formatstrings`). They can also be passed directly to the built-in
Georg Brandl4b491312007-08-31 09:22:56 +0000286:func:`format` function. Each formattable type may define how the format
287specification is to be interpreted.
288
289Most built-in types implement the following options for format specifications,
290although some of the formatting options are only supported by the numeric types.
291
Eric Smith05c07742010-02-25 14:18:57 +0000292A general convention is that an empty format string (``""``) produces
293the same result as if you had called :func:`str` on the value. A
294non-empty format string typically modifies the result.
Georg Brandl4b491312007-08-31 09:22:56 +0000295
296The general form of a *standard format specifier* is:
297
298.. productionlist:: sf
Raymond Hettinger6db94702009-07-12 20:49:21 +0000299 format_spec: [[`fill`]`align`][`sign`][#][0][`width`][,][.`precision`][`type`]
Georg Brandl4b491312007-08-31 09:22:56 +0000300 fill: <a character other than '}'>
301 align: "<" | ">" | "=" | "^"
302 sign: "+" | "-" | " "
303 width: `integer`
304 precision: `integer`
Eric Smith05c07742010-02-25 14:18:57 +0000305 type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
Georg Brandl48310cd2009-01-03 21:18:54 +0000306
Georg Brandlc86adb42010-09-06 06:49:07 +0000307The *fill* character can be any character other than '{' or '}'. The presence
308of a fill character is signaled by the character following it, which must be
309one of the alignment options. If the second character of *format_spec* is not
310a valid alignment option, then it is assumed that both the fill character and
311the alignment option are absent.
Georg Brandl4b491312007-08-31 09:22:56 +0000312
313The meaning of the various alignment options is as follows:
314
315 +---------+----------------------------------------------------------+
316 | Option | Meaning |
317 +=========+==========================================================+
318 | ``'<'`` | Forces the field to be left-aligned within the available |
Ezio Melottid2191e02010-07-02 23:18:51 +0000319 | | space (this is the default). |
Georg Brandl4b491312007-08-31 09:22:56 +0000320 +---------+----------------------------------------------------------+
321 | ``'>'`` | Forces the field to be right-aligned within the |
322 | | available space. |
323 +---------+----------------------------------------------------------+
324 | ``'='`` | Forces the padding to be placed after the sign (if any) |
325 | | but before the digits. This is used for printing fields |
326 | | in the form '+000000120'. This alignment option is only |
327 | | valid for numeric types. |
328 +---------+----------------------------------------------------------+
329 | ``'^'`` | Forces the field to be centered within the available |
330 | | space. |
331 +---------+----------------------------------------------------------+
332
333Note that unless a minimum field width is defined, the field width will always
334be the same size as the data to fill it, so that the alignment option has no
335meaning in this case.
336
337The *sign* option is only valid for number types, and can be one of the
338following:
339
340 +---------+----------------------------------------------------------+
341 | Option | Meaning |
342 +=========+==========================================================+
343 | ``'+'`` | indicates that a sign should be used for both |
344 | | positive as well as negative numbers. |
345 +---------+----------------------------------------------------------+
346 | ``'-'`` | indicates that a sign should be used only for negative |
347 | | numbers (this is the default behavior). |
348 +---------+----------------------------------------------------------+
349 | space | indicates that a leading space should be used on |
350 | | positive numbers, and a minus sign on negative numbers. |
351 +---------+----------------------------------------------------------+
352
Benjamin Petersond7b03282008-09-13 15:58:53 +0000353The ``'#'`` option is only valid for integers, and only for binary, octal, or
354hexadecimal output. If present, it specifies that the output will be prefixed
355by ``'0b'``, ``'0o'``, or ``'0x'``, respectively.
Eric Smithd68af8f2008-07-16 00:15:35 +0000356
Raymond Hettinger6db94702009-07-12 20:49:21 +0000357The ``','`` option signals the use of a comma for a thousands separator.
358For a locale aware separator, use the ``'n'`` integer presentation type
359instead.
360
Ezio Melottid2191e02010-07-02 23:18:51 +0000361.. versionchanged:: 3.1
362 Added the ``','`` option (see also :pep:`378`).
363
Georg Brandl4b491312007-08-31 09:22:56 +0000364*width* is a decimal integer defining the minimum field width. If not
365specified, then the field width will be determined by the content.
366
367If the *width* field is preceded by a zero (``'0'``) character, this enables
368zero-padding. This is equivalent to an *alignment* type of ``'='`` and a *fill*
369character of ``'0'``.
370
371The *precision* is a decimal number indicating how many digits should be
Georg Brandl3dbca812008-07-23 16:10:53 +0000372displayed after the decimal point for a floating point value formatted with
373``'f'`` and ``'F'``, or before and after the decimal point for a floating point
374value formatted with ``'g'`` or ``'G'``. For non-number types the field
375indicates the maximum field size - in other words, how many characters will be
Eric Smithe5fffc72009-05-07 19:38:09 +0000376used from the field content. The *precision* is not allowed for integer values.
Georg Brandl4b491312007-08-31 09:22:56 +0000377
378Finally, the *type* determines how the data should be presented.
379
Eric Smith05c07742010-02-25 14:18:57 +0000380The available string presentation types are:
381
382 +---------+----------------------------------------------------------+
383 | Type | Meaning |
384 +=========+==========================================================+
385 | ``'s'`` | String format. This is the default type for strings and |
386 | | may be omitted. |
387 +---------+----------------------------------------------------------+
388 | None | The same as ``'s'``. |
389 +---------+----------------------------------------------------------+
390
Georg Brandl4b491312007-08-31 09:22:56 +0000391The available integer presentation types are:
392
393 +---------+----------------------------------------------------------+
394 | Type | Meaning |
395 +=========+==========================================================+
Eric Smithd68af8f2008-07-16 00:15:35 +0000396 | ``'b'`` | Binary format. Outputs the number in base 2. |
Georg Brandl4b491312007-08-31 09:22:56 +0000397 +---------+----------------------------------------------------------+
398 | ``'c'`` | Character. Converts the integer to the corresponding |
399 | | unicode character before printing. |
400 +---------+----------------------------------------------------------+
401 | ``'d'`` | Decimal Integer. Outputs the number in base 10. |
402 +---------+----------------------------------------------------------+
403 | ``'o'`` | Octal format. Outputs the number in base 8. |
404 +---------+----------------------------------------------------------+
405 | ``'x'`` | Hex format. Outputs the number in base 16, using lower- |
406 | | case letters for the digits above 9. |
407 +---------+----------------------------------------------------------+
408 | ``'X'`` | Hex format. Outputs the number in base 16, using upper- |
409 | | case letters for the digits above 9. |
410 +---------+----------------------------------------------------------+
Eric Smith5e18a202008-05-12 10:01:24 +0000411 | ``'n'`` | Number. This is the same as ``'d'``, except that it uses |
412 | | the current locale setting to insert the appropriate |
413 | | number separator characters. |
414 +---------+----------------------------------------------------------+
Georg Brandl3dbca812008-07-23 16:10:53 +0000415 | None | The same as ``'d'``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000416 +---------+----------------------------------------------------------+
Georg Brandl48310cd2009-01-03 21:18:54 +0000417
Eric Smith05c07742010-02-25 14:18:57 +0000418In addition to the above presentation types, integers can be formatted
419with the floating point presentation types listed below (except
420``'n'`` and None). When doing so, :func:`float` is used to convert the
421integer to a floating point number before formatting.
422
Georg Brandl4b491312007-08-31 09:22:56 +0000423The available presentation types for floating point and decimal values are:
Georg Brandl48310cd2009-01-03 21:18:54 +0000424
Georg Brandl4b491312007-08-31 09:22:56 +0000425 +---------+----------------------------------------------------------+
426 | Type | Meaning |
427 +=========+==========================================================+
428 | ``'e'`` | Exponent notation. Prints the number in scientific |
429 | | notation using the letter 'e' to indicate the exponent. |
430 +---------+----------------------------------------------------------+
Eric Smith22b85b32008-07-17 19:18:29 +0000431 | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an |
432 | | upper case 'E' as the separator character. |
Georg Brandl4b491312007-08-31 09:22:56 +0000433 +---------+----------------------------------------------------------+
434 | ``'f'`` | Fixed point. Displays the number as a fixed-point |
435 | | number. |
436 +---------+----------------------------------------------------------+
Eric Smith741191f2009-05-06 13:08:15 +0000437 | ``'F'`` | Fixed point. Same as ``'f'``, but converts ``nan`` to |
438 | | ``NAN`` and ``inf`` to ``INF``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000439 +---------+----------------------------------------------------------+
Mark Dickinsonc70614f2009-10-08 20:05:48 +0000440 | ``'g'`` | General format. For a given precision ``p >= 1``, |
441 | | this rounds the number to ``p`` significant digits and |
442 | | then formats the result in either fixed-point format |
443 | | or in scientific notation, depending on its magnitude. |
444 | | |
445 | | The precise rules are as follows: suppose that the |
446 | | result formatted with presentation type ``'e'`` and |
447 | | precision ``p-1`` would have exponent ``exp``. Then |
448 | | if ``-4 <= exp < p``, the number is formatted |
449 | | with presentation type ``'f'`` and precision |
450 | | ``p-1-exp``. Otherwise, the number is formatted |
451 | | with presentation type ``'e'`` and precision ``p-1``. |
452 | | In both cases insignificant trailing zeros are removed |
453 | | from the significand, and the decimal point is also |
454 | | removed if there are no remaining digits following it. |
455 | | |
Benjamin Peterson73a3f2d2010-10-12 23:07:13 +0000456 | | Positive and negative infinity, positive and negative |
Mark Dickinsonc70614f2009-10-08 20:05:48 +0000457 | | zero, and nans, are formatted as ``inf``, ``-inf``, |
458 | | ``0``, ``-0`` and ``nan`` respectively, regardless of |
459 | | the precision. |
460 | | |
461 | | A precision of ``0`` is treated as equivalent to a |
462 | | precision of ``1``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000463 +---------+----------------------------------------------------------+
464 | ``'G'`` | General format. Same as ``'g'`` except switches to |
Mark Dickinsonc70614f2009-10-08 20:05:48 +0000465 | | ``'E'`` if the number gets too large. The |
466 | | representations of infinity and NaN are uppercased, too. |
Georg Brandl4b491312007-08-31 09:22:56 +0000467 +---------+----------------------------------------------------------+
468 | ``'n'`` | Number. This is the same as ``'g'``, except that it uses |
469 | | the current locale setting to insert the appropriate |
470 | | number separator characters. |
471 +---------+----------------------------------------------------------+
472 | ``'%'`` | Percentage. Multiplies the number by 100 and displays |
473 | | in fixed (``'f'``) format, followed by a percent sign. |
474 +---------+----------------------------------------------------------+
Eric Smith3bef15b2009-05-05 17:19:46 +0000475 | None | Similar to ``'g'``, except with at least one digit past |
476 | | the decimal point and a default precision of 12. This is |
477 | | intended to match :func:`str`, except you can add the |
478 | | other format modifiers. |
Georg Brandl4b491312007-08-31 09:22:56 +0000479 +---------+----------------------------------------------------------+
480
481
Ezio Melottid2191e02010-07-02 23:18:51 +0000482.. _formatexamples:
483
484Format examples
485^^^^^^^^^^^^^^^
486
487This section contains examples of the new format syntax and comparison with
488the old ``%``-formatting.
489
490In most of the cases the syntax is similar to the old ``%``-formatting, with the
491addition of the ``{}`` and with ``:`` used instead of ``%``.
492For example, ``'%03.2f'`` can be translated to ``'{:03.2f}'``.
493
494The new format syntax also supports new and different options, shown in the
495follow examples.
496
497Accessing arguments by position::
498
499 >>> '{0}, {1}, {2}'.format('a', 'b', 'c')
500 'a, b, c'
501 >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only
502 'a, b, c'
503 >>> '{2}, {1}, {0}'.format('a', 'b', 'c')
504 'c, b, a'
505 >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence
506 'c, b, a'
507 >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated
508 'abracadabra'
509
510Accessing arguments by name::
511
512 >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
513 'Coordinates: 37.24N, -115.81W'
514 >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
515 >>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
516 'Coordinates: 37.24N, -115.81W'
517
518Accessing arguments' attributes::
519
520 >>> c = 3-5j
521 >>> ('The complex number {0} is formed from the real part {0.real} '
522 ... 'and the imaginary part {0.imag}.').format(c)
523 'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
524 >>> class Point:
525 ... def __init__(self, x, y):
526 ... self.x, self.y = x, y
527 ... def __str__(self):
528 ... return 'Point({self.x}, {self.y})'.format(self=self)
529 ...
530 >>> str(Point(4, 2))
531 'Point(4, 2)'
532
533Accessing arguments' items::
534
535 >>> coord = (3, 5)
536 >>> 'X: {0[0]}; Y: {0[1]}'.format(coord)
537 'X: 3; Y: 5'
538
539Replacing ``%s`` and ``%r``::
540
541 >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
542 "repr() shows quotes: 'test1'; str() doesn't: test2"
543
544Aligning the text and specifying a width::
545
546 >>> '{:<30}'.format('left aligned')
547 'left aligned '
548 >>> '{:>30}'.format('right aligned')
549 ' right aligned'
550 >>> '{:^30}'.format('centered')
551 ' centered '
552 >>> '{:*^30}'.format('centered') # use '*' as a fill char
553 '***********centered***********'
554
555Replacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign::
556
557 >>> '{:+f}; {:+f}'.format(3.14, -3.14) # show it always
558 '+3.140000; -3.140000'
559 >>> '{: f}; {: f}'.format(3.14, -3.14) # show a space for positive numbers
560 ' 3.140000; -3.140000'
561 >>> '{:-f}; {:-f}'.format(3.14, -3.14) # show only the minus -- same as '{:f}; {:f}'
562 '3.140000; -3.140000'
563
564Replacing ``%x`` and ``%o`` and converting the value to different bases::
565
566 >>> # format also supports binary numbers
567 >>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
568 'int: 42; hex: 2a; oct: 52; bin: 101010'
569 >>> # with 0x, 0o, or 0b as prefix:
570 >>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
571 'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
572
573Using the comma as a thousands separator::
574
575 >>> '{:,}'.format(1234567890)
576 '1,234,567,890'
577
578Expressing a percentage::
579
580 >>> points = 19
581 >>> total = 22
582 >>> 'Correct answers: {:.2%}.'.format(points/total)
583 'Correct answers: 86.36%'
584
585Using type-specific formatting::
586
587 >>> import datetime
588 >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
589 >>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
590 '2010-07-04 12:15:58'
591
592Nesting arguments and more complex examples::
593
594 >>> for align, text in zip('<^>', ['left', 'center', 'right']):
595 ... '{0:{align}{fill}16}'.format(text, fill=align, align=align)
596 ...
597 'left<<<<<<<<<<<<'
598 '^^^^^center^^^^^'
599 '>>>>>>>>>>>right'
600 >>>
601 >>> octets = [192, 168, 0, 1]
602 >>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
603 'C0A80001'
604 >>> int(_, 16)
605 3232235521
606 >>>
607 >>> width = 5
608 >>> for num in range(5,12):
609 ... for base in 'dXob':
610 ... print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
611 ... print()
612 ...
613 5 5 5 101
614 6 6 6 110
615 7 7 7 111
616 8 8 10 1000
617 9 9 11 1001
618 10 A 12 1010
619 11 B 13 1011
620
621
622
Georg Brandl4b491312007-08-31 09:22:56 +0000623.. _template-strings:
624
Georg Brandl116aa622007-08-15 14:28:22 +0000625Template strings
626----------------
627
628Templates provide simpler string substitutions as described in :pep:`292`.
629Instead of the normal ``%``\ -based substitutions, Templates support ``$``\
630-based substitutions, using the following rules:
631
632* ``$$`` is an escape; it is replaced with a single ``$``.
633
634* ``$identifier`` names a substitution placeholder matching a mapping key of
635 ``"identifier"``. By default, ``"identifier"`` must spell a Python
636 identifier. The first non-identifier character after the ``$`` character
637 terminates this placeholder specification.
638
639* ``${identifier}`` is equivalent to ``$identifier``. It is required when valid
640 identifier characters follow the placeholder but are not part of the
641 placeholder, such as ``"${noun}ification"``.
642
643Any other appearance of ``$`` in the string will result in a :exc:`ValueError`
644being raised.
645
Georg Brandl116aa622007-08-15 14:28:22 +0000646The :mod:`string` module provides a :class:`Template` class that implements
647these rules. The methods of :class:`Template` are:
648
649
650.. class:: Template(template)
651
652 The constructor takes a single argument which is the template string.
653
654
Georg Brandl7f01a132009-09-16 15:58:14 +0000655 .. method:: substitute(mapping, **kwds)
Georg Brandl116aa622007-08-15 14:28:22 +0000656
Benjamin Petersone41251e2008-04-25 01:59:09 +0000657 Performs the template substitution, returning a new string. *mapping* is
658 any dictionary-like object with keys that match the placeholders in the
659 template. Alternatively, you can provide keyword arguments, where the
Georg Brandl7f01a132009-09-16 15:58:14 +0000660 keywords are the placeholders. When both *mapping* and *kwds* are given
661 and there are duplicates, the placeholders from *kwds* take precedence.
Georg Brandl116aa622007-08-15 14:28:22 +0000662
663
Georg Brandl7f01a132009-09-16 15:58:14 +0000664 .. method:: safe_substitute(mapping, **kwds)
Georg Brandl116aa622007-08-15 14:28:22 +0000665
Benjamin Petersone41251e2008-04-25 01:59:09 +0000666 Like :meth:`substitute`, except that if placeholders are missing from
Georg Brandl7f01a132009-09-16 15:58:14 +0000667 *mapping* and *kwds*, instead of raising a :exc:`KeyError` exception, the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000668 original placeholder will appear in the resulting string intact. Also,
669 unlike with :meth:`substitute`, any other appearances of the ``$`` will
670 simply return ``$`` instead of raising :exc:`ValueError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000671
Benjamin Petersone41251e2008-04-25 01:59:09 +0000672 While other exceptions may still occur, this method is called "safe"
673 because substitutions always tries to return a usable string instead of
674 raising an exception. In another sense, :meth:`safe_substitute` may be
675 anything other than safe, since it will silently ignore malformed
676 templates containing dangling delimiters, unmatched braces, or
677 placeholders that are not valid Python identifiers.
Georg Brandl116aa622007-08-15 14:28:22 +0000678
Benjamin Peterson20211002009-11-25 18:34:42 +0000679 :class:`Template` instances also provide one public data attribute:
Georg Brandl116aa622007-08-15 14:28:22 +0000680
Benjamin Peterson20211002009-11-25 18:34:42 +0000681 .. attribute:: template
Georg Brandl116aa622007-08-15 14:28:22 +0000682
Benjamin Peterson20211002009-11-25 18:34:42 +0000683 This is the object passed to the constructor's *template* argument. In
684 general, you shouldn't change it, but read-only access is not enforced.
Georg Brandl116aa622007-08-15 14:28:22 +0000685
Christian Heimesfe337bf2008-03-23 21:54:12 +0000686Here is an example of how to use a Template:
Georg Brandl116aa622007-08-15 14:28:22 +0000687
688 >>> from string import Template
689 >>> s = Template('$who likes $what')
690 >>> s.substitute(who='tim', what='kung pao')
691 'tim likes kung pao'
692 >>> d = dict(who='tim')
693 >>> Template('Give $who $100').substitute(d)
694 Traceback (most recent call last):
695 [...]
696 ValueError: Invalid placeholder in string: line 1, col 10
697 >>> Template('$who likes $what').substitute(d)
698 Traceback (most recent call last):
699 [...]
700 KeyError: 'what'
701 >>> Template('$who likes $what').safe_substitute(d)
702 'tim likes $what'
703
704Advanced usage: you can derive subclasses of :class:`Template` to customize the
705placeholder syntax, delimiter character, or the entire regular expression used
706to parse template strings. To do this, you can override these class attributes:
707
708* *delimiter* -- This is the literal string describing a placeholder introducing
709 delimiter. The default value ``$``. Note that this should *not* be a regular
710 expression, as the implementation will call :meth:`re.escape` on this string as
711 needed.
712
713* *idpattern* -- This is the regular expression describing the pattern for
714 non-braced placeholders (the braces will be added automatically as
715 appropriate). The default value is the regular expression
716 ``[_a-z][_a-z0-9]*``.
717
Georg Brandl056cb932010-07-29 17:16:10 +0000718* *flags* -- The regular expression flags that will be applied when compiling
719 the regular expression used for recognizing substitutions. The default value
720 is ``re.IGNORECASE``. Note that ``re.VERBOSE`` will always be added to the
721 flags, so custom *idpattern*\ s must follow conventions for verbose regular
722 expressions.
723
724 .. versionadded:: 3.2
725
Georg Brandl116aa622007-08-15 14:28:22 +0000726Alternatively, you can provide the entire regular expression pattern by
727overriding the class attribute *pattern*. If you do this, the value must be a
728regular expression object with four named capturing groups. The capturing
729groups correspond to the rules given above, along with the invalid placeholder
730rule:
731
732* *escaped* -- This group matches the escape sequence, e.g. ``$$``, in the
733 default pattern.
734
735* *named* -- This group matches the unbraced placeholder name; it should not
736 include the delimiter in capturing group.
737
738* *braced* -- This group matches the brace enclosed placeholder name; it should
739 not include either the delimiter or braces in the capturing group.
740
741* *invalid* -- This group matches any other delimiter pattern (usually a single
742 delimiter), and it should appear last in the regular expression.
743
744
Georg Brandlabc38772009-04-12 15:51:51 +0000745Helper functions
Georg Brandl116aa622007-08-15 14:28:22 +0000746----------------
747
Georg Brandl10430ad2009-09-26 20:59:11 +0000748.. function:: capwords(s, sep=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000749
Ezio Melottia40bdda2009-09-26 12:33:22 +0000750 Split the argument into words using :meth:`str.split`, capitalize each word
751 using :meth:`str.capitalize`, and join the capitalized words using
752 :meth:`str.join`. If the optional second argument *sep* is absent
753 or ``None``, runs of whitespace characters are replaced by a single space
754 and leading and trailing whitespace are removed, otherwise *sep* is used to
755 split and join the words.
Georg Brandl116aa622007-08-15 14:28:22 +0000756