blob: 69cc25bbdf457b72e3c1fefda0c8cfad410d1dcc [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
18
19String constants
20----------------
21
22The constants defined in this module are:
23
24
25.. data:: ascii_letters
26
27 The concatenation of the :const:`ascii_lowercase` and :const:`ascii_uppercase`
28 constants described below. This value is not locale-dependent.
29
30
31.. data:: ascii_lowercase
32
33 The lowercase letters ``'abcdefghijklmnopqrstuvwxyz'``. This value is not
34 locale-dependent and will not change.
35
36
37.. data:: ascii_uppercase
38
39 The uppercase letters ``'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. This value is not
40 locale-dependent and will not change.
41
42
43.. data:: digits
44
45 The string ``'0123456789'``.
46
47
48.. data:: hexdigits
49
50 The string ``'0123456789abcdefABCDEF'``.
51
52
53.. data:: octdigits
54
55 The string ``'01234567'``.
56
57
58.. data:: punctuation
59
60 String of ASCII characters which are considered punctuation characters
61 in the ``C`` locale.
62
63
64.. data:: printable
65
66 String of ASCII characters which are considered printable. This is a
67 combination of :const:`digits`, :const:`ascii_letters`, :const:`punctuation`,
68 and :const:`whitespace`.
69
70
71.. data:: whitespace
72
Georg Brandl50767402008-11-22 08:31:09 +000073 A string containing all ASCII characters that are considered whitespace.
Georg Brandl116aa622007-08-15 14:28:22 +000074 This includes the characters space, tab, linefeed, return, formfeed, and
75 vertical tab.
76
77
Georg Brandl4b491312007-08-31 09:22:56 +000078.. _string-formatting:
79
80String Formatting
81-----------------
82
Benjamin Peterson50923f92008-05-25 19:45:17 +000083The built-in string class provides the ability to do complex variable
84substitutions and value formatting via the :func:`format` method described in
85:pep:`3101`. The :class:`Formatter` class in the :mod:`string` module allows
86you to create and customize your own string formatting behaviors using the same
87implementation as the built-in :meth:`format` method.
Georg Brandl4b491312007-08-31 09:22:56 +000088
Benjamin Peterson1baf4652009-12-31 03:11:23 +000089
Georg Brandl4b491312007-08-31 09:22:56 +000090.. class:: Formatter
91
92 The :class:`Formatter` class has the following public methods:
93
94 .. method:: format(format_string, *args, *kwargs)
95
96 :meth:`format` is the primary API method. It takes a format template
97 string, and an arbitrary set of positional and keyword argument.
98 :meth:`format` is just a wrapper that calls :meth:`vformat`.
99
100 .. method:: vformat(format_string, args, kwargs)
Georg Brandl48310cd2009-01-03 21:18:54 +0000101
Georg Brandl4b491312007-08-31 09:22:56 +0000102 This function does the actual work of formatting. It is exposed as a
103 separate function for cases where you want to pass in a predefined
104 dictionary of arguments, rather than unpacking and repacking the
105 dictionary as individual arguments using the ``*args`` and ``**kwds``
106 syntax. :meth:`vformat` does the work of breaking up the format template
107 string into character data and replacement fields. It calls the various
108 methods described below.
109
110 In addition, the :class:`Formatter` defines a number of methods that are
111 intended to be replaced by subclasses:
112
113 .. method:: parse(format_string)
Georg Brandl48310cd2009-01-03 21:18:54 +0000114
Georg Brandl4b491312007-08-31 09:22:56 +0000115 Loop over the format_string and return an iterable of tuples
116 (*literal_text*, *field_name*, *format_spec*, *conversion*). This is used
Georg Brandl70cd7bc2010-10-26 19:31:06 +0000117 by :meth:`vformat` to break the string into either literal text, or
Georg Brandl4b491312007-08-31 09:22:56 +0000118 replacement fields.
Georg Brandl48310cd2009-01-03 21:18:54 +0000119
Georg Brandl4b491312007-08-31 09:22:56 +0000120 The values in the tuple conceptually represent a span of literal text
121 followed by a single replacement field. If there is no literal text
122 (which can happen if two replacement fields occur consecutively), then
123 *literal_text* will be a zero-length string. If there is no replacement
124 field, then the values of *field_name*, *format_spec* and *conversion*
125 will be ``None``.
126
Eric Smith9d4ba392007-09-02 15:33:26 +0000127 .. method:: get_field(field_name, args, kwargs)
Georg Brandl4b491312007-08-31 09:22:56 +0000128
129 Given *field_name* as returned by :meth:`parse` (see above), convert it to
Georg Brandl7f13e6b2007-08-31 10:37:15 +0000130 an object to be formatted. Returns a tuple (obj, used_key). The default
131 version takes strings of the form defined in :pep:`3101`, such as
132 "0[name]" or "label.title". *args* and *kwargs* are as passed in to
133 :meth:`vformat`. The return value *used_key* has the same meaning as the
134 *key* parameter to :meth:`get_value`.
Georg Brandl4b491312007-08-31 09:22:56 +0000135
136 .. method:: get_value(key, args, kwargs)
Georg Brandl48310cd2009-01-03 21:18:54 +0000137
Georg Brandl4b491312007-08-31 09:22:56 +0000138 Retrieve a given field value. The *key* argument will be either an
139 integer or a string. If it is an integer, it represents the index of the
140 positional argument in *args*; if it is a string, then it represents a
141 named argument in *kwargs*.
142
143 The *args* parameter is set to the list of positional arguments to
144 :meth:`vformat`, and the *kwargs* parameter is set to the dictionary of
145 keyword arguments.
146
147 For compound field names, these functions are only called for the first
148 component of the field name; Subsequent components are handled through
149 normal attribute and indexing operations.
150
151 So for example, the field expression '0.name' would cause
152 :meth:`get_value` to be called with a *key* argument of 0. The ``name``
153 attribute will be looked up after :meth:`get_value` returns by calling the
154 built-in :func:`getattr` function.
155
156 If the index or keyword refers to an item that does not exist, then an
157 :exc:`IndexError` or :exc:`KeyError` should be raised.
158
159 .. method:: check_unused_args(used_args, args, kwargs)
160
161 Implement checking for unused arguments if desired. The arguments to this
162 function is the set of all argument keys that were actually referred to in
163 the format string (integers for positional arguments, and strings for
164 named arguments), and a reference to the *args* and *kwargs* that was
165 passed to vformat. The set of unused args can be calculated from these
Georg Brandl7cb13192010-08-03 12:06:29 +0000166 parameters. :meth:`check_unused_args` is assumed to raise an exception if
Georg Brandl4b491312007-08-31 09:22:56 +0000167 the check fails.
168
169 .. method:: format_field(value, format_spec)
170
171 :meth:`format_field` simply calls the global :func:`format` built-in. The
172 method is provided so that subclasses can override it.
173
174 .. method:: convert_field(value, conversion)
Georg Brandl48310cd2009-01-03 21:18:54 +0000175
Georg Brandl4b491312007-08-31 09:22:56 +0000176 Converts the value (returned by :meth:`get_field`) given a conversion type
Ezio Melottid2191e02010-07-02 23:18:51 +0000177 (as in the tuple returned by the :meth:`parse` method). The default
Georg Brandl4b491312007-08-31 09:22:56 +0000178 version understands 'r' (repr) and 's' (str) conversion types.
179
Georg Brandl4b491312007-08-31 09:22:56 +0000180
181.. _formatstrings:
182
183Format String Syntax
184--------------------
185
186The :meth:`str.format` method and the :class:`Formatter` class share the same
187syntax for format strings (although in the case of :class:`Formatter`,
Ezio Melottid2191e02010-07-02 23:18:51 +0000188subclasses can define their own format string syntax).
Georg Brandl4b491312007-08-31 09:22:56 +0000189
190Format strings contain "replacement fields" surrounded by curly braces ``{}``.
191Anything that is not contained in braces is considered literal text, which is
192copied unchanged to the output. If you need to include a brace character in the
193literal text, it can be escaped by doubling: ``{{`` and ``}}``.
194
195The grammar for a replacement field is as follows:
196
197 .. productionlist:: sf
Georg Brandl2f3ed682009-09-01 07:42:40 +0000198 replacement_field: "{" [`field_name`] ["!" `conversion`] [":" `format_spec`] "}"
Eric Smithc4cae322009-04-22 00:53:01 +0000199 field_name: arg_name ("." `attribute_name` | "[" `element_index` "]")*
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000200 arg_name: [`identifier` | `integer`]
Georg Brandl4b491312007-08-31 09:22:56 +0000201 attribute_name: `identifier`
Eric Smith2e9f2022010-02-25 14:58:13 +0000202 element_index: `integer` | `index_string`
203 index_string: <any source character except "]"> +
Benjamin Peterson065ba702008-11-09 01:43:02 +0000204 conversion: "r" | "s" | "a"
Georg Brandl4b491312007-08-31 09:22:56 +0000205 format_spec: <described in the next section>
Georg Brandl48310cd2009-01-03 21:18:54 +0000206
Georg Brandl2f3ed682009-09-01 07:42:40 +0000207In less formal terms, the replacement field can start with a *field_name* that specifies
Eric Smithc4cae322009-04-22 00:53:01 +0000208the object whose value is to be formatted and inserted
209into the output instead of the replacement field.
210The *field_name* is optionally followed by a *conversion* field, which is
Georg Brandl4b491312007-08-31 09:22:56 +0000211preceded by an exclamation point ``'!'``, and a *format_spec*, which is preceded
Eric Smithc4cae322009-04-22 00:53:01 +0000212by a colon ``':'``. These specify a non-default format for the replacement value.
Georg Brandl4b491312007-08-31 09:22:56 +0000213
Ezio Melottid2191e02010-07-02 23:18:51 +0000214See also the :ref:`formatspec` section.
215
Eric Smithc4cae322009-04-22 00:53:01 +0000216The *field_name* itself begins with an *arg_name* that is either either a number or a
217keyword. If it's a number, it refers to a positional argument, and if it's a keyword,
218it refers to a named keyword argument. If the numerical arg_names in a format string
219are 0, 1, 2, ... in sequence, they can all be omitted (not just some)
220and the numbers 0, 1, 2, ... will be automatically inserted in that order.
221The *arg_name* can be followed by any number of index or
Georg Brandl4b491312007-08-31 09:22:56 +0000222attribute expressions. An expression of the form ``'.name'`` selects the named
223attribute using :func:`getattr`, while an expression of the form ``'[index]'``
224does an index lookup using :func:`__getitem__`.
225
Ezio Melottid2191e02010-07-02 23:18:51 +0000226.. versionchanged:: 3.1
227 The positional argument specifiers can be omitted, so ``'{} {}'`` is
228 equivalent to ``'{0} {1}'``.
229
Georg Brandl4b491312007-08-31 09:22:56 +0000230Some simple format string examples::
231
232 "First, thou shalt count to {0}" # References first positional argument
Benjamin Peterson5879d412009-03-30 14:51:56 +0000233 "Bring me a {}" # Implicitly references the first positional argument
Georg Brandl2f3ed682009-09-01 07:42:40 +0000234 "From {} to {}" # Same as "From {0} to {1}"
Georg Brandl4b491312007-08-31 09:22:56 +0000235 "My quest is {name}" # References keyword argument 'name'
236 "Weight in tons {0.weight}" # 'weight' attribute of first positional arg
237 "Units destroyed: {players[0]}" # First element of keyword argument 'players'.
Georg Brandl48310cd2009-01-03 21:18:54 +0000238
Georg Brandl4b491312007-08-31 09:22:56 +0000239The *conversion* field causes a type coercion before formatting. Normally, the
240job of formatting a value is done by the :meth:`__format__` method of the value
241itself. However, in some cases it is desirable to force a type to be formatted
242as a string, overriding its own definition of formatting. By converting the
243value to a string before calling :meth:`__format__`, the normal formatting logic
244is bypassed.
245
Georg Brandl559e5d72008-06-11 18:37:52 +0000246Three conversion flags are currently supported: ``'!s'`` which calls :func:`str`
247on the value, ``'!r'`` which calls :func:`repr` and ``'!a'`` which calls
248:func:`ascii`.
Georg Brandl4b491312007-08-31 09:22:56 +0000249
250Some examples::
251
252 "Harold's a clever {0!s}" # Calls str() on the argument first
253 "Bring out the holy {name!r}" # Calls repr() on the argument first
Georg Brandl2f3ed682009-09-01 07:42:40 +0000254 "More {!a}" # Calls ascii() on the argument first
Georg Brandl4b491312007-08-31 09:22:56 +0000255
256The *format_spec* field contains a specification of how the value should be
257presented, including such details as field width, alignment, padding, decimal
Eric Smith0f7affe2010-02-15 11:57:31 +0000258precision and so on. Each value type can define its own "formatting
Georg Brandl4b491312007-08-31 09:22:56 +0000259mini-language" or interpretation of the *format_spec*.
260
261Most built-in types support a common formatting mini-language, which is
262described in the next section.
263
264A *format_spec* field can also include nested replacement fields within it.
265These nested replacement fields can contain only a field name; conversion flags
266and format specifications are not allowed. The replacement fields within the
267format_spec are substituted before the *format_spec* string is interpreted.
268This allows the formatting of a value to be dynamically specified.
269
Ezio Melottid2191e02010-07-02 23:18:51 +0000270See the :ref:`formatexamples` section for some examples.
Georg Brandl4b491312007-08-31 09:22:56 +0000271
Georg Brandl4b491312007-08-31 09:22:56 +0000272
273.. _formatspec:
274
275Format Specification Mini-Language
276^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
277
278"Format specifications" are used within replacement fields contained within a
279format string to define how individual values are presented (see
Ezio Melottid2191e02010-07-02 23:18:51 +0000280:ref:`formatstrings`). They can also be passed directly to the built-in
Georg Brandl4b491312007-08-31 09:22:56 +0000281:func:`format` function. Each formattable type may define how the format
282specification is to be interpreted.
283
284Most built-in types implement the following options for format specifications,
285although some of the formatting options are only supported by the numeric types.
286
Eric Smith05c07742010-02-25 14:18:57 +0000287A general convention is that an empty format string (``""``) produces
288the same result as if you had called :func:`str` on the value. A
289non-empty format string typically modifies the result.
Georg Brandl4b491312007-08-31 09:22:56 +0000290
291The general form of a *standard format specifier* is:
292
293.. productionlist:: sf
Raymond Hettinger6db94702009-07-12 20:49:21 +0000294 format_spec: [[`fill`]`align`][`sign`][#][0][`width`][,][.`precision`][`type`]
Georg Brandl4b491312007-08-31 09:22:56 +0000295 fill: <a character other than '}'>
296 align: "<" | ">" | "=" | "^"
297 sign: "+" | "-" | " "
298 width: `integer`
299 precision: `integer`
Eric Smith05c07742010-02-25 14:18:57 +0000300 type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
Georg Brandl48310cd2009-01-03 21:18:54 +0000301
Georg Brandlc86adb42010-09-06 06:49:07 +0000302The *fill* character can be any character other than '{' or '}'. The presence
303of a fill character is signaled by the character following it, which must be
304one of the alignment options. If the second character of *format_spec* is not
305a valid alignment option, then it is assumed that both the fill character and
306the alignment option are absent.
Georg Brandl4b491312007-08-31 09:22:56 +0000307
308The meaning of the various alignment options is as follows:
309
310 +---------+----------------------------------------------------------+
311 | Option | Meaning |
312 +=========+==========================================================+
313 | ``'<'`` | Forces the field to be left-aligned within the available |
Ezio Melottid2191e02010-07-02 23:18:51 +0000314 | | space (this is the default). |
Georg Brandl4b491312007-08-31 09:22:56 +0000315 +---------+----------------------------------------------------------+
316 | ``'>'`` | Forces the field to be right-aligned within the |
317 | | available space. |
318 +---------+----------------------------------------------------------+
319 | ``'='`` | Forces the padding to be placed after the sign (if any) |
320 | | but before the digits. This is used for printing fields |
321 | | in the form '+000000120'. This alignment option is only |
322 | | valid for numeric types. |
323 +---------+----------------------------------------------------------+
324 | ``'^'`` | Forces the field to be centered within the available |
325 | | space. |
326 +---------+----------------------------------------------------------+
327
328Note that unless a minimum field width is defined, the field width will always
329be the same size as the data to fill it, so that the alignment option has no
330meaning in this case.
331
332The *sign* option is only valid for number types, and can be one of the
333following:
334
335 +---------+----------------------------------------------------------+
336 | Option | Meaning |
337 +=========+==========================================================+
338 | ``'+'`` | indicates that a sign should be used for both |
339 | | positive as well as negative numbers. |
340 +---------+----------------------------------------------------------+
341 | ``'-'`` | indicates that a sign should be used only for negative |
342 | | numbers (this is the default behavior). |
343 +---------+----------------------------------------------------------+
344 | space | indicates that a leading space should be used on |
345 | | positive numbers, and a minus sign on negative numbers. |
346 +---------+----------------------------------------------------------+
347
Benjamin Petersond7b03282008-09-13 15:58:53 +0000348The ``'#'`` option is only valid for integers, and only for binary, octal, or
349hexadecimal output. If present, it specifies that the output will be prefixed
350by ``'0b'``, ``'0o'``, or ``'0x'``, respectively.
Eric Smithd68af8f2008-07-16 00:15:35 +0000351
Raymond Hettinger6db94702009-07-12 20:49:21 +0000352The ``','`` option signals the use of a comma for a thousands separator.
353For a locale aware separator, use the ``'n'`` integer presentation type
354instead.
355
Ezio Melottid2191e02010-07-02 23:18:51 +0000356.. versionchanged:: 3.1
357 Added the ``','`` option (see also :pep:`378`).
358
Georg Brandl4b491312007-08-31 09:22:56 +0000359*width* is a decimal integer defining the minimum field width. If not
360specified, then the field width will be determined by the content.
361
362If the *width* field is preceded by a zero (``'0'``) character, this enables
363zero-padding. This is equivalent to an *alignment* type of ``'='`` and a *fill*
364character of ``'0'``.
365
366The *precision* is a decimal number indicating how many digits should be
Georg Brandl3dbca812008-07-23 16:10:53 +0000367displayed after the decimal point for a floating point value formatted with
368``'f'`` and ``'F'``, or before and after the decimal point for a floating point
369value formatted with ``'g'`` or ``'G'``. For non-number types the field
370indicates the maximum field size - in other words, how many characters will be
Eric Smithe5fffc72009-05-07 19:38:09 +0000371used from the field content. The *precision* is not allowed for integer values.
Georg Brandl4b491312007-08-31 09:22:56 +0000372
373Finally, the *type* determines how the data should be presented.
374
Eric Smith05c07742010-02-25 14:18:57 +0000375The available string presentation types are:
376
377 +---------+----------------------------------------------------------+
378 | Type | Meaning |
379 +=========+==========================================================+
380 | ``'s'`` | String format. This is the default type for strings and |
381 | | may be omitted. |
382 +---------+----------------------------------------------------------+
383 | None | The same as ``'s'``. |
384 +---------+----------------------------------------------------------+
385
Georg Brandl4b491312007-08-31 09:22:56 +0000386The available integer presentation types are:
387
388 +---------+----------------------------------------------------------+
389 | Type | Meaning |
390 +=========+==========================================================+
Eric Smithd68af8f2008-07-16 00:15:35 +0000391 | ``'b'`` | Binary format. Outputs the number in base 2. |
Georg Brandl4b491312007-08-31 09:22:56 +0000392 +---------+----------------------------------------------------------+
393 | ``'c'`` | Character. Converts the integer to the corresponding |
394 | | unicode character before printing. |
395 +---------+----------------------------------------------------------+
396 | ``'d'`` | Decimal Integer. Outputs the number in base 10. |
397 +---------+----------------------------------------------------------+
398 | ``'o'`` | Octal format. Outputs the number in base 8. |
399 +---------+----------------------------------------------------------+
400 | ``'x'`` | Hex format. Outputs the number in base 16, using lower- |
401 | | case letters for the digits above 9. |
402 +---------+----------------------------------------------------------+
403 | ``'X'`` | Hex format. Outputs the number in base 16, using upper- |
404 | | case letters for the digits above 9. |
405 +---------+----------------------------------------------------------+
Eric Smith5e18a202008-05-12 10:01:24 +0000406 | ``'n'`` | Number. This is the same as ``'d'``, except that it uses |
407 | | the current locale setting to insert the appropriate |
408 | | number separator characters. |
409 +---------+----------------------------------------------------------+
Georg Brandl3dbca812008-07-23 16:10:53 +0000410 | None | The same as ``'d'``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000411 +---------+----------------------------------------------------------+
Georg Brandl48310cd2009-01-03 21:18:54 +0000412
Eric Smith05c07742010-02-25 14:18:57 +0000413In addition to the above presentation types, integers can be formatted
414with the floating point presentation types listed below (except
415``'n'`` and None). When doing so, :func:`float` is used to convert the
416integer to a floating point number before formatting.
417
Georg Brandl4b491312007-08-31 09:22:56 +0000418The available presentation types for floating point and decimal values are:
Georg Brandl48310cd2009-01-03 21:18:54 +0000419
Georg Brandl4b491312007-08-31 09:22:56 +0000420 +---------+----------------------------------------------------------+
421 | Type | Meaning |
422 +=========+==========================================================+
423 | ``'e'`` | Exponent notation. Prints the number in scientific |
424 | | notation using the letter 'e' to indicate the exponent. |
425 +---------+----------------------------------------------------------+
Eric Smith22b85b32008-07-17 19:18:29 +0000426 | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an |
427 | | upper case 'E' as the separator character. |
Georg Brandl4b491312007-08-31 09:22:56 +0000428 +---------+----------------------------------------------------------+
429 | ``'f'`` | Fixed point. Displays the number as a fixed-point |
430 | | number. |
431 +---------+----------------------------------------------------------+
Eric Smith741191f2009-05-06 13:08:15 +0000432 | ``'F'`` | Fixed point. Same as ``'f'``, but converts ``nan`` to |
433 | | ``NAN`` and ``inf`` to ``INF``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000434 +---------+----------------------------------------------------------+
Mark Dickinsonc70614f2009-10-08 20:05:48 +0000435 | ``'g'`` | General format. For a given precision ``p >= 1``, |
436 | | this rounds the number to ``p`` significant digits and |
437 | | then formats the result in either fixed-point format |
438 | | or in scientific notation, depending on its magnitude. |
439 | | |
440 | | The precise rules are as follows: suppose that the |
441 | | result formatted with presentation type ``'e'`` and |
442 | | precision ``p-1`` would have exponent ``exp``. Then |
443 | | if ``-4 <= exp < p``, the number is formatted |
444 | | with presentation type ``'f'`` and precision |
445 | | ``p-1-exp``. Otherwise, the number is formatted |
446 | | with presentation type ``'e'`` and precision ``p-1``. |
447 | | In both cases insignificant trailing zeros are removed |
448 | | from the significand, and the decimal point is also |
449 | | removed if there are no remaining digits following it. |
450 | | |
Benjamin Peterson73a3f2d2010-10-12 23:07:13 +0000451 | | Positive and negative infinity, positive and negative |
Mark Dickinsonc70614f2009-10-08 20:05:48 +0000452 | | zero, and nans, are formatted as ``inf``, ``-inf``, |
453 | | ``0``, ``-0`` and ``nan`` respectively, regardless of |
454 | | the precision. |
455 | | |
456 | | A precision of ``0`` is treated as equivalent to a |
457 | | precision of ``1``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000458 +---------+----------------------------------------------------------+
459 | ``'G'`` | General format. Same as ``'g'`` except switches to |
Mark Dickinsonc70614f2009-10-08 20:05:48 +0000460 | | ``'E'`` if the number gets too large. The |
461 | | representations of infinity and NaN are uppercased, too. |
Georg Brandl4b491312007-08-31 09:22:56 +0000462 +---------+----------------------------------------------------------+
463 | ``'n'`` | Number. This is the same as ``'g'``, except that it uses |
464 | | the current locale setting to insert the appropriate |
465 | | number separator characters. |
466 +---------+----------------------------------------------------------+
467 | ``'%'`` | Percentage. Multiplies the number by 100 and displays |
468 | | in fixed (``'f'``) format, followed by a percent sign. |
469 +---------+----------------------------------------------------------+
Eric Smith3bef15b2009-05-05 17:19:46 +0000470 | None | Similar to ``'g'``, except with at least one digit past |
471 | | the decimal point and a default precision of 12. This is |
472 | | intended to match :func:`str`, except you can add the |
473 | | other format modifiers. |
Georg Brandl4b491312007-08-31 09:22:56 +0000474 +---------+----------------------------------------------------------+
475
476
Ezio Melottid2191e02010-07-02 23:18:51 +0000477.. _formatexamples:
478
479Format examples
480^^^^^^^^^^^^^^^
481
482This section contains examples of the new format syntax and comparison with
483the old ``%``-formatting.
484
485In most of the cases the syntax is similar to the old ``%``-formatting, with the
486addition of the ``{}`` and with ``:`` used instead of ``%``.
487For example, ``'%03.2f'`` can be translated to ``'{:03.2f}'``.
488
489The new format syntax also supports new and different options, shown in the
490follow examples.
491
492Accessing arguments by position::
493
494 >>> '{0}, {1}, {2}'.format('a', 'b', 'c')
495 'a, b, c'
496 >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only
497 'a, b, c'
498 >>> '{2}, {1}, {0}'.format('a', 'b', 'c')
499 'c, b, a'
500 >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence
501 'c, b, a'
502 >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated
503 'abracadabra'
504
505Accessing arguments by name::
506
507 >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
508 'Coordinates: 37.24N, -115.81W'
509 >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
510 >>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
511 'Coordinates: 37.24N, -115.81W'
512
513Accessing arguments' attributes::
514
515 >>> c = 3-5j
516 >>> ('The complex number {0} is formed from the real part {0.real} '
517 ... 'and the imaginary part {0.imag}.').format(c)
518 'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
519 >>> class Point:
520 ... def __init__(self, x, y):
521 ... self.x, self.y = x, y
522 ... def __str__(self):
523 ... return 'Point({self.x}, {self.y})'.format(self=self)
524 ...
525 >>> str(Point(4, 2))
526 'Point(4, 2)'
527
528Accessing arguments' items::
529
530 >>> coord = (3, 5)
531 >>> 'X: {0[0]}; Y: {0[1]}'.format(coord)
532 'X: 3; Y: 5'
533
534Replacing ``%s`` and ``%r``::
535
536 >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
537 "repr() shows quotes: 'test1'; str() doesn't: test2"
538
539Aligning the text and specifying a width::
540
541 >>> '{:<30}'.format('left aligned')
542 'left aligned '
543 >>> '{:>30}'.format('right aligned')
544 ' right aligned'
545 >>> '{:^30}'.format('centered')
546 ' centered '
547 >>> '{:*^30}'.format('centered') # use '*' as a fill char
548 '***********centered***********'
549
550Replacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign::
551
552 >>> '{:+f}; {:+f}'.format(3.14, -3.14) # show it always
553 '+3.140000; -3.140000'
554 >>> '{: f}; {: f}'.format(3.14, -3.14) # show a space for positive numbers
555 ' 3.140000; -3.140000'
556 >>> '{:-f}; {:-f}'.format(3.14, -3.14) # show only the minus -- same as '{:f}; {:f}'
557 '3.140000; -3.140000'
558
559Replacing ``%x`` and ``%o`` and converting the value to different bases::
560
561 >>> # format also supports binary numbers
562 >>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
563 'int: 42; hex: 2a; oct: 52; bin: 101010'
564 >>> # with 0x, 0o, or 0b as prefix:
565 >>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
566 'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
567
568Using the comma as a thousands separator::
569
570 >>> '{:,}'.format(1234567890)
571 '1,234,567,890'
572
573Expressing a percentage::
574
575 >>> points = 19
576 >>> total = 22
577 >>> 'Correct answers: {:.2%}.'.format(points/total)
578 'Correct answers: 86.36%'
579
580Using type-specific formatting::
581
582 >>> import datetime
583 >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
584 >>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
585 '2010-07-04 12:15:58'
586
587Nesting arguments and more complex examples::
588
589 >>> for align, text in zip('<^>', ['left', 'center', 'right']):
590 ... '{0:{align}{fill}16}'.format(text, fill=align, align=align)
591 ...
592 'left<<<<<<<<<<<<'
593 '^^^^^center^^^^^'
594 '>>>>>>>>>>>right'
595 >>>
596 >>> octets = [192, 168, 0, 1]
597 >>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
598 'C0A80001'
599 >>> int(_, 16)
600 3232235521
601 >>>
602 >>> width = 5
603 >>> for num in range(5,12):
604 ... for base in 'dXob':
605 ... print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
606 ... print()
607 ...
608 5 5 5 101
609 6 6 6 110
610 7 7 7 111
611 8 8 10 1000
612 9 9 11 1001
613 10 A 12 1010
614 11 B 13 1011
615
616
617
Georg Brandl4b491312007-08-31 09:22:56 +0000618.. _template-strings:
619
Georg Brandl116aa622007-08-15 14:28:22 +0000620Template strings
621----------------
622
623Templates provide simpler string substitutions as described in :pep:`292`.
624Instead of the normal ``%``\ -based substitutions, Templates support ``$``\
625-based substitutions, using the following rules:
626
627* ``$$`` is an escape; it is replaced with a single ``$``.
628
629* ``$identifier`` names a substitution placeholder matching a mapping key of
630 ``"identifier"``. By default, ``"identifier"`` must spell a Python
631 identifier. The first non-identifier character after the ``$`` character
632 terminates this placeholder specification.
633
634* ``${identifier}`` is equivalent to ``$identifier``. It is required when valid
635 identifier characters follow the placeholder but are not part of the
636 placeholder, such as ``"${noun}ification"``.
637
638Any other appearance of ``$`` in the string will result in a :exc:`ValueError`
639being raised.
640
Georg Brandl116aa622007-08-15 14:28:22 +0000641The :mod:`string` module provides a :class:`Template` class that implements
642these rules. The methods of :class:`Template` are:
643
644
645.. class:: Template(template)
646
647 The constructor takes a single argument which is the template string.
648
649
Georg Brandl7f01a132009-09-16 15:58:14 +0000650 .. method:: substitute(mapping, **kwds)
Georg Brandl116aa622007-08-15 14:28:22 +0000651
Benjamin Petersone41251e2008-04-25 01:59:09 +0000652 Performs the template substitution, returning a new string. *mapping* is
653 any dictionary-like object with keys that match the placeholders in the
654 template. Alternatively, you can provide keyword arguments, where the
Georg Brandl7f01a132009-09-16 15:58:14 +0000655 keywords are the placeholders. When both *mapping* and *kwds* are given
656 and there are duplicates, the placeholders from *kwds* take precedence.
Georg Brandl116aa622007-08-15 14:28:22 +0000657
658
Georg Brandl7f01a132009-09-16 15:58:14 +0000659 .. method:: safe_substitute(mapping, **kwds)
Georg Brandl116aa622007-08-15 14:28:22 +0000660
Benjamin Petersone41251e2008-04-25 01:59:09 +0000661 Like :meth:`substitute`, except that if placeholders are missing from
Georg Brandl7f01a132009-09-16 15:58:14 +0000662 *mapping* and *kwds*, instead of raising a :exc:`KeyError` exception, the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000663 original placeholder will appear in the resulting string intact. Also,
664 unlike with :meth:`substitute`, any other appearances of the ``$`` will
665 simply return ``$`` instead of raising :exc:`ValueError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000666
Benjamin Petersone41251e2008-04-25 01:59:09 +0000667 While other exceptions may still occur, this method is called "safe"
668 because substitutions always tries to return a usable string instead of
669 raising an exception. In another sense, :meth:`safe_substitute` may be
670 anything other than safe, since it will silently ignore malformed
671 templates containing dangling delimiters, unmatched braces, or
672 placeholders that are not valid Python identifiers.
Georg Brandl116aa622007-08-15 14:28:22 +0000673
Benjamin Peterson20211002009-11-25 18:34:42 +0000674 :class:`Template` instances also provide one public data attribute:
Georg Brandl116aa622007-08-15 14:28:22 +0000675
Benjamin Peterson20211002009-11-25 18:34:42 +0000676 .. attribute:: template
Georg Brandl116aa622007-08-15 14:28:22 +0000677
Benjamin Peterson20211002009-11-25 18:34:42 +0000678 This is the object passed to the constructor's *template* argument. In
679 general, you shouldn't change it, but read-only access is not enforced.
Georg Brandl116aa622007-08-15 14:28:22 +0000680
Christian Heimesfe337bf2008-03-23 21:54:12 +0000681Here is an example of how to use a Template:
Georg Brandl116aa622007-08-15 14:28:22 +0000682
683 >>> from string import Template
684 >>> s = Template('$who likes $what')
685 >>> s.substitute(who='tim', what='kung pao')
686 'tim likes kung pao'
687 >>> d = dict(who='tim')
688 >>> Template('Give $who $100').substitute(d)
689 Traceback (most recent call last):
690 [...]
691 ValueError: Invalid placeholder in string: line 1, col 10
692 >>> Template('$who likes $what').substitute(d)
693 Traceback (most recent call last):
694 [...]
695 KeyError: 'what'
696 >>> Template('$who likes $what').safe_substitute(d)
697 'tim likes $what'
698
699Advanced usage: you can derive subclasses of :class:`Template` to customize the
700placeholder syntax, delimiter character, or the entire regular expression used
701to parse template strings. To do this, you can override these class attributes:
702
703* *delimiter* -- This is the literal string describing a placeholder introducing
704 delimiter. The default value ``$``. Note that this should *not* be a regular
705 expression, as the implementation will call :meth:`re.escape` on this string as
706 needed.
707
708* *idpattern* -- This is the regular expression describing the pattern for
709 non-braced placeholders (the braces will be added automatically as
710 appropriate). The default value is the regular expression
711 ``[_a-z][_a-z0-9]*``.
712
Georg Brandl056cb932010-07-29 17:16:10 +0000713* *flags* -- The regular expression flags that will be applied when compiling
714 the regular expression used for recognizing substitutions. The default value
715 is ``re.IGNORECASE``. Note that ``re.VERBOSE`` will always be added to the
716 flags, so custom *idpattern*\ s must follow conventions for verbose regular
717 expressions.
718
719 .. versionadded:: 3.2
720
Georg Brandl116aa622007-08-15 14:28:22 +0000721Alternatively, you can provide the entire regular expression pattern by
722overriding the class attribute *pattern*. If you do this, the value must be a
723regular expression object with four named capturing groups. The capturing
724groups correspond to the rules given above, along with the invalid placeholder
725rule:
726
727* *escaped* -- This group matches the escape sequence, e.g. ``$$``, in the
728 default pattern.
729
730* *named* -- This group matches the unbraced placeholder name; it should not
731 include the delimiter in capturing group.
732
733* *braced* -- This group matches the brace enclosed placeholder name; it should
734 not include either the delimiter or braces in the capturing group.
735
736* *invalid* -- This group matches any other delimiter pattern (usually a single
737 delimiter), and it should appear last in the regular expression.
738
739
Georg Brandlabc38772009-04-12 15:51:51 +0000740Helper functions
Georg Brandl116aa622007-08-15 14:28:22 +0000741----------------
742
Georg Brandl10430ad2009-09-26 20:59:11 +0000743.. function:: capwords(s, sep=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000744
Ezio Melottia40bdda2009-09-26 12:33:22 +0000745 Split the argument into words using :meth:`str.split`, capitalize each word
746 using :meth:`str.capitalize`, and join the capitalized words using
747 :meth:`str.join`. If the optional second argument *sep* is absent
748 or ``None``, runs of whitespace characters are replaced by a single space
749 and leading and trailing whitespace are removed, otherwise *sep* is used to
750 split and join the words.
Georg Brandl116aa622007-08-15 14:28:22 +0000751