blob: 78f2b4ded36b540aadfb6c85b74ce0f71b0995fb [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
Éric Araujo19f9b712011-08-19 00:49:18 +02007**Source code:** :source:`Lib/string.py`
8
9--------------
Georg Brandl116aa622007-08-15 14:28:22 +000010
Éric Araujo6e6cb8e2010-11-16 19:13:50 +000011.. seealso::
12
Georg Brandlb30f3302011-01-06 09:23:56 +000013 :ref:`typesseq`
14
15 :ref:`string-methods`
16
Georg Brandl116aa622007-08-15 14:28:22 +000017String constants
18----------------
19
20The constants defined in this module are:
21
22
23.. data:: ascii_letters
24
25 The concatenation of the :const:`ascii_lowercase` and :const:`ascii_uppercase`
26 constants described below. This value is not locale-dependent.
27
28
29.. data:: ascii_lowercase
30
31 The lowercase letters ``'abcdefghijklmnopqrstuvwxyz'``. This value is not
32 locale-dependent and will not change.
33
34
35.. data:: ascii_uppercase
36
37 The uppercase letters ``'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. This value is not
38 locale-dependent and will not change.
39
40
41.. data:: digits
42
43 The string ``'0123456789'``.
44
45
46.. data:: hexdigits
47
48 The string ``'0123456789abcdefABCDEF'``.
49
50
51.. data:: octdigits
52
53 The string ``'01234567'``.
54
55
56.. data:: punctuation
57
58 String of ASCII characters which are considered punctuation characters
59 in the ``C`` locale.
60
61
62.. data:: printable
63
64 String of ASCII characters which are considered printable. This is a
65 combination of :const:`digits`, :const:`ascii_letters`, :const:`punctuation`,
66 and :const:`whitespace`.
67
68
69.. data:: whitespace
70
Georg Brandl50767402008-11-22 08:31:09 +000071 A string containing all ASCII characters that are considered whitespace.
Georg Brandl116aa622007-08-15 14:28:22 +000072 This includes the characters space, tab, linefeed, return, formfeed, and
73 vertical tab.
74
75
Georg Brandl4b491312007-08-31 09:22:56 +000076.. _string-formatting:
77
78String Formatting
79-----------------
80
Benjamin Peterson50923f92008-05-25 19:45:17 +000081The built-in string class provides the ability to do complex variable
82substitutions and value formatting via the :func:`format` method described in
83:pep:`3101`. The :class:`Formatter` class in the :mod:`string` module allows
84you to create and customize your own string formatting behaviors using the same
85implementation as the built-in :meth:`format` method.
Georg Brandl4b491312007-08-31 09:22:56 +000086
Benjamin Peterson1baf4652009-12-31 03:11:23 +000087
Georg Brandl4b491312007-08-31 09:22:56 +000088.. class:: Formatter
89
90 The :class:`Formatter` class has the following public methods:
91
Georg Brandl8e490de2011-01-24 19:53:18 +000092 .. method:: format(format_string, *args, **kwargs)
Georg Brandl4b491312007-08-31 09:22:56 +000093
94 :meth:`format` is the primary API method. It takes a format template
95 string, and an arbitrary set of positional and keyword argument.
96 :meth:`format` is just a wrapper that calls :meth:`vformat`.
97
98 .. method:: vformat(format_string, args, kwargs)
Georg Brandl48310cd2009-01-03 21:18:54 +000099
Georg Brandl4b491312007-08-31 09:22:56 +0000100 This function does the actual work of formatting. It is exposed as a
101 separate function for cases where you want to pass in a predefined
102 dictionary of arguments, rather than unpacking and repacking the
103 dictionary as individual arguments using the ``*args`` and ``**kwds``
104 syntax. :meth:`vformat` does the work of breaking up the format template
105 string into character data and replacement fields. It calls the various
106 methods described below.
107
108 In addition, the :class:`Formatter` defines a number of methods that are
109 intended to be replaced by subclasses:
110
111 .. method:: parse(format_string)
Georg Brandl48310cd2009-01-03 21:18:54 +0000112
Georg Brandl4b491312007-08-31 09:22:56 +0000113 Loop over the format_string and return an iterable of tuples
114 (*literal_text*, *field_name*, *format_spec*, *conversion*). This is used
Georg Brandl70cd7bc2010-10-26 19:31:06 +0000115 by :meth:`vformat` to break the string into either literal text, or
Georg Brandl4b491312007-08-31 09:22:56 +0000116 replacement fields.
Georg Brandl48310cd2009-01-03 21:18:54 +0000117
Georg Brandl4b491312007-08-31 09:22:56 +0000118 The values in the tuple conceptually represent a span of literal text
119 followed by a single replacement field. If there is no literal text
120 (which can happen if two replacement fields occur consecutively), then
121 *literal_text* will be a zero-length string. If there is no replacement
122 field, then the values of *field_name*, *format_spec* and *conversion*
123 will be ``None``.
124
Eric Smith9d4ba392007-09-02 15:33:26 +0000125 .. method:: get_field(field_name, args, kwargs)
Georg Brandl4b491312007-08-31 09:22:56 +0000126
127 Given *field_name* as returned by :meth:`parse` (see above), convert it to
Georg Brandl7f13e6b2007-08-31 10:37:15 +0000128 an object to be formatted. Returns a tuple (obj, used_key). The default
129 version takes strings of the form defined in :pep:`3101`, such as
130 "0[name]" or "label.title". *args* and *kwargs* are as passed in to
131 :meth:`vformat`. The return value *used_key* has the same meaning as the
132 *key* parameter to :meth:`get_value`.
Georg Brandl4b491312007-08-31 09:22:56 +0000133
134 .. method:: get_value(key, args, kwargs)
Georg Brandl48310cd2009-01-03 21:18:54 +0000135
Georg Brandl4b491312007-08-31 09:22:56 +0000136 Retrieve a given field value. The *key* argument will be either an
137 integer or a string. If it is an integer, it represents the index of the
138 positional argument in *args*; if it is a string, then it represents a
139 named argument in *kwargs*.
140
141 The *args* parameter is set to the list of positional arguments to
142 :meth:`vformat`, and the *kwargs* parameter is set to the dictionary of
143 keyword arguments.
144
145 For compound field names, these functions are only called for the first
146 component of the field name; Subsequent components are handled through
147 normal attribute and indexing operations.
148
149 So for example, the field expression '0.name' would cause
150 :meth:`get_value` to be called with a *key* argument of 0. The ``name``
151 attribute will be looked up after :meth:`get_value` returns by calling the
152 built-in :func:`getattr` function.
153
154 If the index or keyword refers to an item that does not exist, then an
155 :exc:`IndexError` or :exc:`KeyError` should be raised.
156
157 .. method:: check_unused_args(used_args, args, kwargs)
158
159 Implement checking for unused arguments if desired. The arguments to this
160 function is the set of all argument keys that were actually referred to in
161 the format string (integers for positional arguments, and strings for
162 named arguments), and a reference to the *args* and *kwargs* that was
163 passed to vformat. The set of unused args can be calculated from these
Georg Brandl7cb13192010-08-03 12:06:29 +0000164 parameters. :meth:`check_unused_args` is assumed to raise an exception if
Georg Brandl4b491312007-08-31 09:22:56 +0000165 the check fails.
166
167 .. method:: format_field(value, format_spec)
168
169 :meth:`format_field` simply calls the global :func:`format` built-in. The
170 method is provided so that subclasses can override it.
171
172 .. method:: convert_field(value, conversion)
Georg Brandl48310cd2009-01-03 21:18:54 +0000173
Georg Brandl4b491312007-08-31 09:22:56 +0000174 Converts the value (returned by :meth:`get_field`) given a conversion type
Ezio Melottid2191e02010-07-02 23:18:51 +0000175 (as in the tuple returned by the :meth:`parse` method). The default
Georg Brandl4b491312007-08-31 09:22:56 +0000176 version understands 'r' (repr) and 's' (str) conversion types.
177
Georg Brandl4b491312007-08-31 09:22:56 +0000178
179.. _formatstrings:
180
181Format String Syntax
182--------------------
183
184The :meth:`str.format` method and the :class:`Formatter` class share the same
185syntax for format strings (although in the case of :class:`Formatter`,
Ezio Melottid2191e02010-07-02 23:18:51 +0000186subclasses can define their own format string syntax).
Georg Brandl4b491312007-08-31 09:22:56 +0000187
188Format strings contain "replacement fields" surrounded by curly braces ``{}``.
189Anything that is not contained in braces is considered literal text, which is
190copied unchanged to the output. If you need to include a brace character in the
191literal text, it can be escaped by doubling: ``{{`` and ``}}``.
192
193The grammar for a replacement field is as follows:
194
195 .. productionlist:: sf
Georg Brandl2f3ed682009-09-01 07:42:40 +0000196 replacement_field: "{" [`field_name`] ["!" `conversion`] [":" `format_spec`] "}"
Eric Smithc4cae322009-04-22 00:53:01 +0000197 field_name: arg_name ("." `attribute_name` | "[" `element_index` "]")*
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000198 arg_name: [`identifier` | `integer`]
Georg Brandl4b491312007-08-31 09:22:56 +0000199 attribute_name: `identifier`
Eric Smith2e9f2022010-02-25 14:58:13 +0000200 element_index: `integer` | `index_string`
201 index_string: <any source character except "]"> +
Benjamin Peterson065ba702008-11-09 01:43:02 +0000202 conversion: "r" | "s" | "a"
Georg Brandl4b491312007-08-31 09:22:56 +0000203 format_spec: <described in the next section>
Georg Brandl48310cd2009-01-03 21:18:54 +0000204
Georg Brandl2f3ed682009-09-01 07:42:40 +0000205In less formal terms, the replacement field can start with a *field_name* that specifies
Eric Smithc4cae322009-04-22 00:53:01 +0000206the object whose value is to be formatted and inserted
207into the output instead of the replacement field.
208The *field_name* is optionally followed by a *conversion* field, which is
Georg Brandl4b491312007-08-31 09:22:56 +0000209preceded by an exclamation point ``'!'``, and a *format_spec*, which is preceded
Eric Smithc4cae322009-04-22 00:53:01 +0000210by a colon ``':'``. These specify a non-default format for the replacement value.
Georg Brandl4b491312007-08-31 09:22:56 +0000211
Ezio Melottid2191e02010-07-02 23:18:51 +0000212See also the :ref:`formatspec` section.
213
Eric Smithc4cae322009-04-22 00:53:01 +0000214The *field_name* itself begins with an *arg_name* that is either either a number or a
215keyword. If it's a number, it refers to a positional argument, and if it's a keyword,
216it refers to a named keyword argument. If the numerical arg_names in a format string
217are 0, 1, 2, ... in sequence, they can all be omitted (not just some)
218and the numbers 0, 1, 2, ... will be automatically inserted in that order.
Éric Araujo29cf58c2011-09-01 18:59:06 +0200219Because *arg_name* is not quote-delimited, it is not possible to specify arbitrary
220dictionary keys (e.g., the strings ``'10'`` or ``':-]'``) within a format string.
Eric Smithc4cae322009-04-22 00:53:01 +0000221The *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 |
Georg Brandlca583b62011-02-07 12:13:58 +0000314 | | space (this is the default for most objects). |
Georg Brandl4b491312007-08-31 09:22:56 +0000315 +---------+----------------------------------------------------------+
316 | ``'>'`` | Forces the field to be right-aligned within the |
Georg Brandlca583b62011-02-07 12:13:58 +0000317 | | available space (this is the default for numbers). |
Georg Brandl4b491312007-08-31 09:22:56 +0000318 +---------+----------------------------------------------------------+
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
Eric Smith984bb582010-11-25 16:08:06 +0000348
349The ``'#'`` option causes the "alternate form" to be used for the
350conversion. The alternate form is defined differently for different
351types. This option is only valid for integer, float, complex and
352Decimal types. For integers, when binary, octal, or hexadecimal output
353is used, this option adds the prefix respective ``'0b'``, ``'0o'``, or
354``'0x'`` to the output value. For floats, complex and Decimal the
355alternate form causes the result of the conversion to always contain a
356decimal-point character, even if no digits follow it. Normally, a
357decimal-point character appears in the result of these conversions
358only if a digit follows it. In addition, for ``'g'`` and ``'G'``
359conversions, trailing zeros are not removed from the result.
Eric Smithd68af8f2008-07-16 00:15:35 +0000360
Raymond Hettinger6db94702009-07-12 20:49:21 +0000361The ``','`` option signals the use of a comma for a thousands separator.
362For a locale aware separator, use the ``'n'`` integer presentation type
363instead.
364
Ezio Melottid2191e02010-07-02 23:18:51 +0000365.. versionchanged:: 3.1
366 Added the ``','`` option (see also :pep:`378`).
367
Georg Brandl4b491312007-08-31 09:22:56 +0000368*width* is a decimal integer defining the minimum field width. If not
369specified, then the field width will be determined by the content.
370
371If the *width* field is preceded by a zero (``'0'``) character, this enables
372zero-padding. This is equivalent to an *alignment* type of ``'='`` and a *fill*
373character of ``'0'``.
374
375The *precision* is a decimal number indicating how many digits should be
Georg Brandl3dbca812008-07-23 16:10:53 +0000376displayed after the decimal point for a floating point value formatted with
377``'f'`` and ``'F'``, or before and after the decimal point for a floating point
378value formatted with ``'g'`` or ``'G'``. For non-number types the field
379indicates the maximum field size - in other words, how many characters will be
Eric Smithe5fffc72009-05-07 19:38:09 +0000380used from the field content. The *precision* is not allowed for integer values.
Georg Brandl4b491312007-08-31 09:22:56 +0000381
382Finally, the *type* determines how the data should be presented.
383
Eric Smith05c07742010-02-25 14:18:57 +0000384The available string presentation types are:
385
386 +---------+----------------------------------------------------------+
387 | Type | Meaning |
388 +=========+==========================================================+
389 | ``'s'`` | String format. This is the default type for strings and |
390 | | may be omitted. |
391 +---------+----------------------------------------------------------+
392 | None | The same as ``'s'``. |
393 +---------+----------------------------------------------------------+
394
Georg Brandl4b491312007-08-31 09:22:56 +0000395The available integer presentation types are:
396
397 +---------+----------------------------------------------------------+
398 | Type | Meaning |
399 +=========+==========================================================+
Eric Smithd68af8f2008-07-16 00:15:35 +0000400 | ``'b'`` | Binary format. Outputs the number in base 2. |
Georg Brandl4b491312007-08-31 09:22:56 +0000401 +---------+----------------------------------------------------------+
402 | ``'c'`` | Character. Converts the integer to the corresponding |
403 | | unicode character before printing. |
404 +---------+----------------------------------------------------------+
405 | ``'d'`` | Decimal Integer. Outputs the number in base 10. |
406 +---------+----------------------------------------------------------+
407 | ``'o'`` | Octal format. Outputs the number in base 8. |
408 +---------+----------------------------------------------------------+
409 | ``'x'`` | Hex format. Outputs the number in base 16, using lower- |
410 | | case letters for the digits above 9. |
411 +---------+----------------------------------------------------------+
412 | ``'X'`` | Hex format. Outputs the number in base 16, using upper- |
413 | | case letters for the digits above 9. |
414 +---------+----------------------------------------------------------+
Eric Smith5e18a202008-05-12 10:01:24 +0000415 | ``'n'`` | Number. This is the same as ``'d'``, except that it uses |
416 | | the current locale setting to insert the appropriate |
417 | | number separator characters. |
418 +---------+----------------------------------------------------------+
Georg Brandl3dbca812008-07-23 16:10:53 +0000419 | None | The same as ``'d'``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000420 +---------+----------------------------------------------------------+
Georg Brandl48310cd2009-01-03 21:18:54 +0000421
Eric Smith05c07742010-02-25 14:18:57 +0000422In addition to the above presentation types, integers can be formatted
423with the floating point presentation types listed below (except
424``'n'`` and None). When doing so, :func:`float` is used to convert the
425integer to a floating point number before formatting.
426
Georg Brandl4b491312007-08-31 09:22:56 +0000427The available presentation types for floating point and decimal values are:
Georg Brandl48310cd2009-01-03 21:18:54 +0000428
Georg Brandl4b491312007-08-31 09:22:56 +0000429 +---------+----------------------------------------------------------+
430 | Type | Meaning |
431 +=========+==========================================================+
432 | ``'e'`` | Exponent notation. Prints the number in scientific |
433 | | notation using the letter 'e' to indicate the exponent. |
434 +---------+----------------------------------------------------------+
Eric Smith22b85b32008-07-17 19:18:29 +0000435 | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an |
436 | | upper case 'E' as the separator character. |
Georg Brandl4b491312007-08-31 09:22:56 +0000437 +---------+----------------------------------------------------------+
438 | ``'f'`` | Fixed point. Displays the number as a fixed-point |
439 | | number. |
440 +---------+----------------------------------------------------------+
Eric Smith741191f2009-05-06 13:08:15 +0000441 | ``'F'`` | Fixed point. Same as ``'f'``, but converts ``nan`` to |
442 | | ``NAN`` and ``inf`` to ``INF``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000443 +---------+----------------------------------------------------------+
Mark Dickinsonc70614f2009-10-08 20:05:48 +0000444 | ``'g'`` | General format. For a given precision ``p >= 1``, |
445 | | this rounds the number to ``p`` significant digits and |
446 | | then formats the result in either fixed-point format |
447 | | or in scientific notation, depending on its magnitude. |
448 | | |
449 | | The precise rules are as follows: suppose that the |
450 | | result formatted with presentation type ``'e'`` and |
451 | | precision ``p-1`` would have exponent ``exp``. Then |
452 | | if ``-4 <= exp < p``, the number is formatted |
453 | | with presentation type ``'f'`` and precision |
454 | | ``p-1-exp``. Otherwise, the number is formatted |
455 | | with presentation type ``'e'`` and precision ``p-1``. |
456 | | In both cases insignificant trailing zeros are removed |
457 | | from the significand, and the decimal point is also |
458 | | removed if there are no remaining digits following it. |
459 | | |
Benjamin Peterson73a3f2d2010-10-12 23:07:13 +0000460 | | Positive and negative infinity, positive and negative |
Mark Dickinsonc70614f2009-10-08 20:05:48 +0000461 | | zero, and nans, are formatted as ``inf``, ``-inf``, |
462 | | ``0``, ``-0`` and ``nan`` respectively, regardless of |
463 | | the precision. |
464 | | |
465 | | A precision of ``0`` is treated as equivalent to a |
466 | | precision of ``1``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000467 +---------+----------------------------------------------------------+
468 | ``'G'`` | General format. Same as ``'g'`` except switches to |
Mark Dickinsonc70614f2009-10-08 20:05:48 +0000469 | | ``'E'`` if the number gets too large. The |
470 | | representations of infinity and NaN are uppercased, too. |
Georg Brandl4b491312007-08-31 09:22:56 +0000471 +---------+----------------------------------------------------------+
472 | ``'n'`` | Number. This is the same as ``'g'``, except that it uses |
473 | | the current locale setting to insert the appropriate |
474 | | number separator characters. |
475 +---------+----------------------------------------------------------+
476 | ``'%'`` | Percentage. Multiplies the number by 100 and displays |
477 | | in fixed (``'f'``) format, followed by a percent sign. |
478 +---------+----------------------------------------------------------+
Eric Smith3bef15b2009-05-05 17:19:46 +0000479 | None | Similar to ``'g'``, except with at least one digit past |
480 | | the decimal point and a default precision of 12. This is |
481 | | intended to match :func:`str`, except you can add the |
482 | | other format modifiers. |
Georg Brandl4b491312007-08-31 09:22:56 +0000483 +---------+----------------------------------------------------------+
484
485
Ezio Melottid2191e02010-07-02 23:18:51 +0000486.. _formatexamples:
487
488Format examples
489^^^^^^^^^^^^^^^
490
491This section contains examples of the new format syntax and comparison with
492the old ``%``-formatting.
493
494In most of the cases the syntax is similar to the old ``%``-formatting, with the
495addition of the ``{}`` and with ``:`` used instead of ``%``.
496For example, ``'%03.2f'`` can be translated to ``'{:03.2f}'``.
497
498The new format syntax also supports new and different options, shown in the
499follow examples.
500
501Accessing arguments by position::
502
503 >>> '{0}, {1}, {2}'.format('a', 'b', 'c')
504 'a, b, c'
505 >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only
506 'a, b, c'
507 >>> '{2}, {1}, {0}'.format('a', 'b', 'c')
508 'c, b, a'
509 >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence
510 'c, b, a'
511 >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated
512 'abracadabra'
513
514Accessing arguments by name::
515
516 >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
517 'Coordinates: 37.24N, -115.81W'
518 >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
519 >>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
520 'Coordinates: 37.24N, -115.81W'
521
522Accessing arguments' attributes::
523
524 >>> c = 3-5j
525 >>> ('The complex number {0} is formed from the real part {0.real} '
526 ... 'and the imaginary part {0.imag}.').format(c)
527 'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
528 >>> class Point:
529 ... def __init__(self, x, y):
530 ... self.x, self.y = x, y
531 ... def __str__(self):
532 ... return 'Point({self.x}, {self.y})'.format(self=self)
533 ...
534 >>> str(Point(4, 2))
535 'Point(4, 2)'
536
537Accessing arguments' items::
538
539 >>> coord = (3, 5)
540 >>> 'X: {0[0]}; Y: {0[1]}'.format(coord)
541 'X: 3; Y: 5'
542
543Replacing ``%s`` and ``%r``::
544
545 >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
546 "repr() shows quotes: 'test1'; str() doesn't: test2"
547
548Aligning the text and specifying a width::
549
550 >>> '{:<30}'.format('left aligned')
551 'left aligned '
552 >>> '{:>30}'.format('right aligned')
553 ' right aligned'
554 >>> '{:^30}'.format('centered')
555 ' centered '
556 >>> '{:*^30}'.format('centered') # use '*' as a fill char
557 '***********centered***********'
558
559Replacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign::
560
561 >>> '{:+f}; {:+f}'.format(3.14, -3.14) # show it always
562 '+3.140000; -3.140000'
563 >>> '{: f}; {: f}'.format(3.14, -3.14) # show a space for positive numbers
564 ' 3.140000; -3.140000'
565 >>> '{:-f}; {:-f}'.format(3.14, -3.14) # show only the minus -- same as '{:f}; {:f}'
566 '3.140000; -3.140000'
567
568Replacing ``%x`` and ``%o`` and converting the value to different bases::
569
570 >>> # format also supports binary numbers
571 >>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
572 'int: 42; hex: 2a; oct: 52; bin: 101010'
573 >>> # with 0x, 0o, or 0b as prefix:
574 >>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
575 'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
576
577Using the comma as a thousands separator::
578
579 >>> '{:,}'.format(1234567890)
580 '1,234,567,890'
581
582Expressing a percentage::
583
584 >>> points = 19
585 >>> total = 22
586 >>> 'Correct answers: {:.2%}.'.format(points/total)
587 'Correct answers: 86.36%'
588
589Using type-specific formatting::
590
591 >>> import datetime
592 >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
593 >>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
594 '2010-07-04 12:15:58'
595
596Nesting arguments and more complex examples::
597
598 >>> for align, text in zip('<^>', ['left', 'center', 'right']):
Georg Brandla5770aa2011-02-07 12:10:46 +0000599 ... '{0:{fill}{align}16}'.format(text, fill=align, align=align)
Ezio Melottid2191e02010-07-02 23:18:51 +0000600 ...
601 'left<<<<<<<<<<<<'
602 '^^^^^center^^^^^'
603 '>>>>>>>>>>>right'
604 >>>
605 >>> octets = [192, 168, 0, 1]
606 >>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
607 'C0A80001'
608 >>> int(_, 16)
609 3232235521
610 >>>
611 >>> width = 5
612 >>> for num in range(5,12):
613 ... for base in 'dXob':
614 ... print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
615 ... print()
616 ...
617 5 5 5 101
618 6 6 6 110
619 7 7 7 111
620 8 8 10 1000
621 9 9 11 1001
622 10 A 12 1010
623 11 B 13 1011
624
625
626
Georg Brandl4b491312007-08-31 09:22:56 +0000627.. _template-strings:
628
Georg Brandl116aa622007-08-15 14:28:22 +0000629Template strings
630----------------
631
632Templates provide simpler string substitutions as described in :pep:`292`.
633Instead of the normal ``%``\ -based substitutions, Templates support ``$``\
634-based substitutions, using the following rules:
635
636* ``$$`` is an escape; it is replaced with a single ``$``.
637
638* ``$identifier`` names a substitution placeholder matching a mapping key of
639 ``"identifier"``. By default, ``"identifier"`` must spell a Python
640 identifier. The first non-identifier character after the ``$`` character
641 terminates this placeholder specification.
642
643* ``${identifier}`` is equivalent to ``$identifier``. It is required when valid
644 identifier characters follow the placeholder but are not part of the
645 placeholder, such as ``"${noun}ification"``.
646
647Any other appearance of ``$`` in the string will result in a :exc:`ValueError`
648being raised.
649
Georg Brandl116aa622007-08-15 14:28:22 +0000650The :mod:`string` module provides a :class:`Template` class that implements
651these rules. The methods of :class:`Template` are:
652
653
654.. class:: Template(template)
655
656 The constructor takes a single argument which is the template string.
657
658
Georg Brandl7f01a132009-09-16 15:58:14 +0000659 .. method:: substitute(mapping, **kwds)
Georg Brandl116aa622007-08-15 14:28:22 +0000660
Benjamin Petersone41251e2008-04-25 01:59:09 +0000661 Performs the template substitution, returning a new string. *mapping* is
662 any dictionary-like object with keys that match the placeholders in the
663 template. Alternatively, you can provide keyword arguments, where the
Georg Brandl7f01a132009-09-16 15:58:14 +0000664 keywords are the placeholders. When both *mapping* and *kwds* are given
665 and there are duplicates, the placeholders from *kwds* take precedence.
Georg Brandl116aa622007-08-15 14:28:22 +0000666
667
Georg Brandl7f01a132009-09-16 15:58:14 +0000668 .. method:: safe_substitute(mapping, **kwds)
Georg Brandl116aa622007-08-15 14:28:22 +0000669
Benjamin Petersone41251e2008-04-25 01:59:09 +0000670 Like :meth:`substitute`, except that if placeholders are missing from
Georg Brandl7f01a132009-09-16 15:58:14 +0000671 *mapping* and *kwds*, instead of raising a :exc:`KeyError` exception, the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000672 original placeholder will appear in the resulting string intact. Also,
673 unlike with :meth:`substitute`, any other appearances of the ``$`` will
674 simply return ``$`` instead of raising :exc:`ValueError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000675
Benjamin Petersone41251e2008-04-25 01:59:09 +0000676 While other exceptions may still occur, this method is called "safe"
677 because substitutions always tries to return a usable string instead of
678 raising an exception. In another sense, :meth:`safe_substitute` may be
679 anything other than safe, since it will silently ignore malformed
680 templates containing dangling delimiters, unmatched braces, or
681 placeholders that are not valid Python identifiers.
Georg Brandl116aa622007-08-15 14:28:22 +0000682
Benjamin Peterson20211002009-11-25 18:34:42 +0000683 :class:`Template` instances also provide one public data attribute:
Georg Brandl116aa622007-08-15 14:28:22 +0000684
Benjamin Peterson20211002009-11-25 18:34:42 +0000685 .. attribute:: template
Georg Brandl116aa622007-08-15 14:28:22 +0000686
Benjamin Peterson20211002009-11-25 18:34:42 +0000687 This is the object passed to the constructor's *template* argument. In
688 general, you shouldn't change it, but read-only access is not enforced.
Georg Brandl116aa622007-08-15 14:28:22 +0000689
Christian Heimesfe337bf2008-03-23 21:54:12 +0000690Here is an example of how to use a Template:
Georg Brandl116aa622007-08-15 14:28:22 +0000691
692 >>> from string import Template
693 >>> s = Template('$who likes $what')
694 >>> s.substitute(who='tim', what='kung pao')
695 'tim likes kung pao'
696 >>> d = dict(who='tim')
697 >>> Template('Give $who $100').substitute(d)
698 Traceback (most recent call last):
699 [...]
700 ValueError: Invalid placeholder in string: line 1, col 10
701 >>> Template('$who likes $what').substitute(d)
702 Traceback (most recent call last):
703 [...]
704 KeyError: 'what'
705 >>> Template('$who likes $what').safe_substitute(d)
706 'tim likes $what'
707
708Advanced usage: you can derive subclasses of :class:`Template` to customize the
709placeholder syntax, delimiter character, or the entire regular expression used
710to parse template strings. To do this, you can override these class attributes:
711
712* *delimiter* -- This is the literal string describing a placeholder introducing
Eli Benderskyebd48052011-08-06 09:31:09 +0300713 delimiter. The default value is ``$``. Note that this should *not* be a
714 regular expression, as the implementation will call :meth:`re.escape` on this
715 string as needed.
Georg Brandl116aa622007-08-15 14:28:22 +0000716
717* *idpattern* -- This is the regular expression describing the pattern for
718 non-braced placeholders (the braces will be added automatically as
719 appropriate). The default value is the regular expression
720 ``[_a-z][_a-z0-9]*``.
721
Georg Brandl056cb932010-07-29 17:16:10 +0000722* *flags* -- The regular expression flags that will be applied when compiling
723 the regular expression used for recognizing substitutions. The default value
724 is ``re.IGNORECASE``. Note that ``re.VERBOSE`` will always be added to the
725 flags, so custom *idpattern*\ s must follow conventions for verbose regular
726 expressions.
727
728 .. versionadded:: 3.2
729
Georg Brandl116aa622007-08-15 14:28:22 +0000730Alternatively, you can provide the entire regular expression pattern by
731overriding the class attribute *pattern*. If you do this, the value must be a
732regular expression object with four named capturing groups. The capturing
733groups correspond to the rules given above, along with the invalid placeholder
734rule:
735
736* *escaped* -- This group matches the escape sequence, e.g. ``$$``, in the
737 default pattern.
738
739* *named* -- This group matches the unbraced placeholder name; it should not
740 include the delimiter in capturing group.
741
742* *braced* -- This group matches the brace enclosed placeholder name; it should
743 not include either the delimiter or braces in the capturing group.
744
745* *invalid* -- This group matches any other delimiter pattern (usually a single
746 delimiter), and it should appear last in the regular expression.
747
748
Georg Brandlabc38772009-04-12 15:51:51 +0000749Helper functions
Georg Brandl116aa622007-08-15 14:28:22 +0000750----------------
751
Georg Brandl10430ad2009-09-26 20:59:11 +0000752.. function:: capwords(s, sep=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000753
Ezio Melottia40bdda2009-09-26 12:33:22 +0000754 Split the argument into words using :meth:`str.split`, capitalize each word
755 using :meth:`str.capitalize`, and join the capitalized words using
756 :meth:`str.join`. If the optional second argument *sep* is absent
757 or ``None``, runs of whitespace characters are replaced by a single space
758 and leading and trailing whitespace are removed, otherwise *sep* is used to
759 split and join the words.
Georg Brandl116aa622007-08-15 14:28:22 +0000760