blob: 904df29d5fc79b82380723755d87b78208ebef99 [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
Éric Araujo6e6cb8e2010-11-16 19:13:50 +00008.. seealso::
9
Georg Brandlb30f3302011-01-06 09:23:56 +000010 :ref:`typesseq`
11
12 :ref:`string-methods`
13
Raymond Hettinger10480942011-01-10 03:26:08 +000014**Source code:** :source:`Lib/string.py`
Georg Brandl116aa622007-08-15 14:28:22 +000015
16String constants
17----------------
18
19The constants defined in this module are:
20
21
22.. data:: ascii_letters
23
24 The concatenation of the :const:`ascii_lowercase` and :const:`ascii_uppercase`
25 constants described below. This value is not locale-dependent.
26
27
28.. data:: ascii_lowercase
29
30 The lowercase letters ``'abcdefghijklmnopqrstuvwxyz'``. This value is not
31 locale-dependent and will not change.
32
33
34.. data:: ascii_uppercase
35
36 The uppercase letters ``'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. This value is not
37 locale-dependent and will not change.
38
39
40.. data:: digits
41
42 The string ``'0123456789'``.
43
44
45.. data:: hexdigits
46
47 The string ``'0123456789abcdefABCDEF'``.
48
49
50.. data:: octdigits
51
52 The string ``'01234567'``.
53
54
55.. data:: punctuation
56
57 String of ASCII characters which are considered punctuation characters
58 in the ``C`` locale.
59
60
61.. data:: printable
62
63 String of ASCII characters which are considered printable. This is a
64 combination of :const:`digits`, :const:`ascii_letters`, :const:`punctuation`,
65 and :const:`whitespace`.
66
67
68.. data:: whitespace
69
Georg Brandl50767402008-11-22 08:31:09 +000070 A string containing all ASCII characters that are considered whitespace.
Georg Brandl116aa622007-08-15 14:28:22 +000071 This includes the characters space, tab, linefeed, return, formfeed, and
72 vertical tab.
73
74
Georg Brandl4b491312007-08-31 09:22:56 +000075.. _string-formatting:
76
77String Formatting
78-----------------
79
Benjamin Peterson50923f92008-05-25 19:45:17 +000080The built-in string class provides the ability to do complex variable
81substitutions and value formatting via the :func:`format` method described in
82:pep:`3101`. The :class:`Formatter` class in the :mod:`string` module allows
83you to create and customize your own string formatting behaviors using the same
84implementation as the built-in :meth:`format` method.
Georg Brandl4b491312007-08-31 09:22:56 +000085
Benjamin Peterson1baf4652009-12-31 03:11:23 +000086
Georg Brandl4b491312007-08-31 09:22:56 +000087.. class:: Formatter
88
89 The :class:`Formatter` class has the following public methods:
90
91 .. method:: format(format_string, *args, *kwargs)
92
93 :meth:`format` is the primary API method. It takes a format template
94 string, and an arbitrary set of positional and keyword argument.
95 :meth:`format` is just a wrapper that calls :meth:`vformat`.
96
97 .. method:: vformat(format_string, args, kwargs)
Georg Brandl48310cd2009-01-03 21:18:54 +000098
Georg Brandl4b491312007-08-31 09:22:56 +000099 This function does the actual work of formatting. It is exposed as a
100 separate function for cases where you want to pass in a predefined
101 dictionary of arguments, rather than unpacking and repacking the
102 dictionary as individual arguments using the ``*args`` and ``**kwds``
103 syntax. :meth:`vformat` does the work of breaking up the format template
104 string into character data and replacement fields. It calls the various
105 methods described below.
106
107 In addition, the :class:`Formatter` defines a number of methods that are
108 intended to be replaced by subclasses:
109
110 .. method:: parse(format_string)
Georg Brandl48310cd2009-01-03 21:18:54 +0000111
Georg Brandl4b491312007-08-31 09:22:56 +0000112 Loop over the format_string and return an iterable of tuples
113 (*literal_text*, *field_name*, *format_spec*, *conversion*). This is used
Georg Brandl70cd7bc2010-10-26 19:31:06 +0000114 by :meth:`vformat` to break the string into either literal text, or
Georg Brandl4b491312007-08-31 09:22:56 +0000115 replacement fields.
Georg Brandl48310cd2009-01-03 21:18:54 +0000116
Georg Brandl4b491312007-08-31 09:22:56 +0000117 The values in the tuple conceptually represent a span of literal text
118 followed by a single replacement field. If there is no literal text
119 (which can happen if two replacement fields occur consecutively), then
120 *literal_text* will be a zero-length string. If there is no replacement
121 field, then the values of *field_name*, *format_spec* and *conversion*
122 will be ``None``.
123
Eric Smith9d4ba392007-09-02 15:33:26 +0000124 .. method:: get_field(field_name, args, kwargs)
Georg Brandl4b491312007-08-31 09:22:56 +0000125
126 Given *field_name* as returned by :meth:`parse` (see above), convert it to
Georg Brandl7f13e6b2007-08-31 10:37:15 +0000127 an object to be formatted. Returns a tuple (obj, used_key). The default
128 version takes strings of the form defined in :pep:`3101`, such as
129 "0[name]" or "label.title". *args* and *kwargs* are as passed in to
130 :meth:`vformat`. The return value *used_key* has the same meaning as the
131 *key* parameter to :meth:`get_value`.
Georg Brandl4b491312007-08-31 09:22:56 +0000132
133 .. method:: get_value(key, args, kwargs)
Georg Brandl48310cd2009-01-03 21:18:54 +0000134
Georg Brandl4b491312007-08-31 09:22:56 +0000135 Retrieve a given field value. The *key* argument will be either an
136 integer or a string. If it is an integer, it represents the index of the
137 positional argument in *args*; if it is a string, then it represents a
138 named argument in *kwargs*.
139
140 The *args* parameter is set to the list of positional arguments to
141 :meth:`vformat`, and the *kwargs* parameter is set to the dictionary of
142 keyword arguments.
143
144 For compound field names, these functions are only called for the first
145 component of the field name; Subsequent components are handled through
146 normal attribute and indexing operations.
147
148 So for example, the field expression '0.name' would cause
149 :meth:`get_value` to be called with a *key* argument of 0. The ``name``
150 attribute will be looked up after :meth:`get_value` returns by calling the
151 built-in :func:`getattr` function.
152
153 If the index or keyword refers to an item that does not exist, then an
154 :exc:`IndexError` or :exc:`KeyError` should be raised.
155
156 .. method:: check_unused_args(used_args, args, kwargs)
157
158 Implement checking for unused arguments if desired. The arguments to this
159 function is the set of all argument keys that were actually referred to in
160 the format string (integers for positional arguments, and strings for
161 named arguments), and a reference to the *args* and *kwargs* that was
162 passed to vformat. The set of unused args can be calculated from these
Georg Brandl7cb13192010-08-03 12:06:29 +0000163 parameters. :meth:`check_unused_args` is assumed to raise an exception if
Georg Brandl4b491312007-08-31 09:22:56 +0000164 the check fails.
165
166 .. method:: format_field(value, format_spec)
167
168 :meth:`format_field` simply calls the global :func:`format` built-in. The
169 method is provided so that subclasses can override it.
170
171 .. method:: convert_field(value, conversion)
Georg Brandl48310cd2009-01-03 21:18:54 +0000172
Georg Brandl4b491312007-08-31 09:22:56 +0000173 Converts the value (returned by :meth:`get_field`) given a conversion type
Ezio Melottid2191e02010-07-02 23:18:51 +0000174 (as in the tuple returned by the :meth:`parse` method). The default
Georg Brandl4b491312007-08-31 09:22:56 +0000175 version understands 'r' (repr) and 's' (str) conversion types.
176
Georg Brandl4b491312007-08-31 09:22:56 +0000177
178.. _formatstrings:
179
180Format String Syntax
181--------------------
182
183The :meth:`str.format` method and the :class:`Formatter` class share the same
184syntax for format strings (although in the case of :class:`Formatter`,
Ezio Melottid2191e02010-07-02 23:18:51 +0000185subclasses can define their own format string syntax).
Georg Brandl4b491312007-08-31 09:22:56 +0000186
187Format strings contain "replacement fields" surrounded by curly braces ``{}``.
188Anything that is not contained in braces is considered literal text, which is
189copied unchanged to the output. If you need to include a brace character in the
190literal text, it can be escaped by doubling: ``{{`` and ``}}``.
191
192The grammar for a replacement field is as follows:
193
194 .. productionlist:: sf
Georg Brandl2f3ed682009-09-01 07:42:40 +0000195 replacement_field: "{" [`field_name`] ["!" `conversion`] [":" `format_spec`] "}"
Eric Smithc4cae322009-04-22 00:53:01 +0000196 field_name: arg_name ("." `attribute_name` | "[" `element_index` "]")*
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000197 arg_name: [`identifier` | `integer`]
Georg Brandl4b491312007-08-31 09:22:56 +0000198 attribute_name: `identifier`
Eric Smith2e9f2022010-02-25 14:58:13 +0000199 element_index: `integer` | `index_string`
200 index_string: <any source character except "]"> +
Benjamin Peterson065ba702008-11-09 01:43:02 +0000201 conversion: "r" | "s" | "a"
Georg Brandl4b491312007-08-31 09:22:56 +0000202 format_spec: <described in the next section>
Georg Brandl48310cd2009-01-03 21:18:54 +0000203
Georg Brandl2f3ed682009-09-01 07:42:40 +0000204In less formal terms, the replacement field can start with a *field_name* that specifies
Eric Smithc4cae322009-04-22 00:53:01 +0000205the object whose value is to be formatted and inserted
206into the output instead of the replacement field.
207The *field_name* is optionally followed by a *conversion* field, which is
Georg Brandl4b491312007-08-31 09:22:56 +0000208preceded by an exclamation point ``'!'``, and a *format_spec*, which is preceded
Eric Smithc4cae322009-04-22 00:53:01 +0000209by a colon ``':'``. These specify a non-default format for the replacement value.
Georg Brandl4b491312007-08-31 09:22:56 +0000210
Ezio Melottid2191e02010-07-02 23:18:51 +0000211See also the :ref:`formatspec` section.
212
Eric Smithc4cae322009-04-22 00:53:01 +0000213The *field_name* itself begins with an *arg_name* that is either either a number or a
214keyword. If it's a number, it refers to a positional argument, and if it's a keyword,
215it refers to a named keyword argument. If the numerical arg_names in a format string
216are 0, 1, 2, ... in sequence, they can all be omitted (not just some)
217and the numbers 0, 1, 2, ... will be automatically inserted in that order.
218The *arg_name* can be followed by any number of index or
Georg Brandl4b491312007-08-31 09:22:56 +0000219attribute expressions. An expression of the form ``'.name'`` selects the named
220attribute using :func:`getattr`, while an expression of the form ``'[index]'``
221does an index lookup using :func:`__getitem__`.
222
Ezio Melottid2191e02010-07-02 23:18:51 +0000223.. versionchanged:: 3.1
224 The positional argument specifiers can be omitted, so ``'{} {}'`` is
225 equivalent to ``'{0} {1}'``.
226
Georg Brandl4b491312007-08-31 09:22:56 +0000227Some simple format string examples::
228
229 "First, thou shalt count to {0}" # References first positional argument
Benjamin Peterson5879d412009-03-30 14:51:56 +0000230 "Bring me a {}" # Implicitly references the first positional argument
Georg Brandl2f3ed682009-09-01 07:42:40 +0000231 "From {} to {}" # Same as "From {0} to {1}"
Georg Brandl4b491312007-08-31 09:22:56 +0000232 "My quest is {name}" # References keyword argument 'name'
233 "Weight in tons {0.weight}" # 'weight' attribute of first positional arg
234 "Units destroyed: {players[0]}" # First element of keyword argument 'players'.
Georg Brandl48310cd2009-01-03 21:18:54 +0000235
Georg Brandl4b491312007-08-31 09:22:56 +0000236The *conversion* field causes a type coercion before formatting. Normally, the
237job of formatting a value is done by the :meth:`__format__` method of the value
238itself. However, in some cases it is desirable to force a type to be formatted
239as a string, overriding its own definition of formatting. By converting the
240value to a string before calling :meth:`__format__`, the normal formatting logic
241is bypassed.
242
Georg Brandl559e5d72008-06-11 18:37:52 +0000243Three conversion flags are currently supported: ``'!s'`` which calls :func:`str`
244on the value, ``'!r'`` which calls :func:`repr` and ``'!a'`` which calls
245:func:`ascii`.
Georg Brandl4b491312007-08-31 09:22:56 +0000246
247Some examples::
248
249 "Harold's a clever {0!s}" # Calls str() on the argument first
250 "Bring out the holy {name!r}" # Calls repr() on the argument first
Georg Brandl2f3ed682009-09-01 07:42:40 +0000251 "More {!a}" # Calls ascii() on the argument first
Georg Brandl4b491312007-08-31 09:22:56 +0000252
253The *format_spec* field contains a specification of how the value should be
254presented, including such details as field width, alignment, padding, decimal
Eric Smith0f7affe2010-02-15 11:57:31 +0000255precision and so on. Each value type can define its own "formatting
Georg Brandl4b491312007-08-31 09:22:56 +0000256mini-language" or interpretation of the *format_spec*.
257
258Most built-in types support a common formatting mini-language, which is
259described in the next section.
260
261A *format_spec* field can also include nested replacement fields within it.
262These nested replacement fields can contain only a field name; conversion flags
263and format specifications are not allowed. The replacement fields within the
264format_spec are substituted before the *format_spec* string is interpreted.
265This allows the formatting of a value to be dynamically specified.
266
Ezio Melottid2191e02010-07-02 23:18:51 +0000267See the :ref:`formatexamples` section for some examples.
Georg Brandl4b491312007-08-31 09:22:56 +0000268
Georg Brandl4b491312007-08-31 09:22:56 +0000269
270.. _formatspec:
271
272Format Specification Mini-Language
273^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
274
275"Format specifications" are used within replacement fields contained within a
276format string to define how individual values are presented (see
Ezio Melottid2191e02010-07-02 23:18:51 +0000277:ref:`formatstrings`). They can also be passed directly to the built-in
Georg Brandl4b491312007-08-31 09:22:56 +0000278:func:`format` function. Each formattable type may define how the format
279specification is to be interpreted.
280
281Most built-in types implement the following options for format specifications,
282although some of the formatting options are only supported by the numeric types.
283
Eric Smith05c07742010-02-25 14:18:57 +0000284A general convention is that an empty format string (``""``) produces
285the same result as if you had called :func:`str` on the value. A
286non-empty format string typically modifies the result.
Georg Brandl4b491312007-08-31 09:22:56 +0000287
288The general form of a *standard format specifier* is:
289
290.. productionlist:: sf
Raymond Hettinger6db94702009-07-12 20:49:21 +0000291 format_spec: [[`fill`]`align`][`sign`][#][0][`width`][,][.`precision`][`type`]
Georg Brandl4b491312007-08-31 09:22:56 +0000292 fill: <a character other than '}'>
293 align: "<" | ">" | "=" | "^"
294 sign: "+" | "-" | " "
295 width: `integer`
296 precision: `integer`
Eric Smith05c07742010-02-25 14:18:57 +0000297 type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
Georg Brandl48310cd2009-01-03 21:18:54 +0000298
Georg Brandlc86adb42010-09-06 06:49:07 +0000299The *fill* character can be any character other than '{' or '}'. The presence
300of a fill character is signaled by the character following it, which must be
301one of the alignment options. If the second character of *format_spec* is not
302a valid alignment option, then it is assumed that both the fill character and
303the alignment option are absent.
Georg Brandl4b491312007-08-31 09:22:56 +0000304
305The meaning of the various alignment options is as follows:
306
307 +---------+----------------------------------------------------------+
308 | Option | Meaning |
309 +=========+==========================================================+
310 | ``'<'`` | Forces the field to be left-aligned within the available |
Ezio Melottid2191e02010-07-02 23:18:51 +0000311 | | space (this is the default). |
Georg Brandl4b491312007-08-31 09:22:56 +0000312 +---------+----------------------------------------------------------+
313 | ``'>'`` | Forces the field to be right-aligned within the |
314 | | available space. |
315 +---------+----------------------------------------------------------+
316 | ``'='`` | Forces the padding to be placed after the sign (if any) |
317 | | but before the digits. This is used for printing fields |
318 | | in the form '+000000120'. This alignment option is only |
319 | | valid for numeric types. |
320 +---------+----------------------------------------------------------+
321 | ``'^'`` | Forces the field to be centered within the available |
322 | | space. |
323 +---------+----------------------------------------------------------+
324
325Note that unless a minimum field width is defined, the field width will always
326be the same size as the data to fill it, so that the alignment option has no
327meaning in this case.
328
329The *sign* option is only valid for number types, and can be one of the
330following:
331
332 +---------+----------------------------------------------------------+
333 | Option | Meaning |
334 +=========+==========================================================+
335 | ``'+'`` | indicates that a sign should be used for both |
336 | | positive as well as negative numbers. |
337 +---------+----------------------------------------------------------+
338 | ``'-'`` | indicates that a sign should be used only for negative |
339 | | numbers (this is the default behavior). |
340 +---------+----------------------------------------------------------+
341 | space | indicates that a leading space should be used on |
342 | | positive numbers, and a minus sign on negative numbers. |
343 +---------+----------------------------------------------------------+
344
Eric Smith984bb582010-11-25 16:08:06 +0000345
346The ``'#'`` option causes the "alternate form" to be used for the
347conversion. The alternate form is defined differently for different
348types. This option is only valid for integer, float, complex and
349Decimal types. For integers, when binary, octal, or hexadecimal output
350is used, this option adds the prefix respective ``'0b'``, ``'0o'``, or
351``'0x'`` to the output value. For floats, complex and Decimal the
352alternate form causes the result of the conversion to always contain a
353decimal-point character, even if no digits follow it. Normally, a
354decimal-point character appears in the result of these conversions
355only if a digit follows it. In addition, for ``'g'`` and ``'G'``
356conversions, trailing zeros are not removed from the result.
Eric Smithd68af8f2008-07-16 00:15:35 +0000357
Raymond Hettinger6db94702009-07-12 20:49:21 +0000358The ``','`` option signals the use of a comma for a thousands separator.
359For a locale aware separator, use the ``'n'`` integer presentation type
360instead.
361
Ezio Melottid2191e02010-07-02 23:18:51 +0000362.. versionchanged:: 3.1
363 Added the ``','`` option (see also :pep:`378`).
364
Georg Brandl4b491312007-08-31 09:22:56 +0000365*width* is a decimal integer defining the minimum field width. If not
366specified, then the field width will be determined by the content.
367
368If the *width* field is preceded by a zero (``'0'``) character, this enables
369zero-padding. This is equivalent to an *alignment* type of ``'='`` and a *fill*
370character of ``'0'``.
371
372The *precision* is a decimal number indicating how many digits should be
Georg Brandl3dbca812008-07-23 16:10:53 +0000373displayed after the decimal point for a floating point value formatted with
374``'f'`` and ``'F'``, or before and after the decimal point for a floating point
375value formatted with ``'g'`` or ``'G'``. For non-number types the field
376indicates the maximum field size - in other words, how many characters will be
Eric Smithe5fffc72009-05-07 19:38:09 +0000377used from the field content. The *precision* is not allowed for integer values.
Georg Brandl4b491312007-08-31 09:22:56 +0000378
379Finally, the *type* determines how the data should be presented.
380
Eric Smith05c07742010-02-25 14:18:57 +0000381The available string presentation types are:
382
383 +---------+----------------------------------------------------------+
384 | Type | Meaning |
385 +=========+==========================================================+
386 | ``'s'`` | String format. This is the default type for strings and |
387 | | may be omitted. |
388 +---------+----------------------------------------------------------+
389 | None | The same as ``'s'``. |
390 +---------+----------------------------------------------------------+
391
Georg Brandl4b491312007-08-31 09:22:56 +0000392The available integer presentation types are:
393
394 +---------+----------------------------------------------------------+
395 | Type | Meaning |
396 +=========+==========================================================+
Eric Smithd68af8f2008-07-16 00:15:35 +0000397 | ``'b'`` | Binary format. Outputs the number in base 2. |
Georg Brandl4b491312007-08-31 09:22:56 +0000398 +---------+----------------------------------------------------------+
399 | ``'c'`` | Character. Converts the integer to the corresponding |
400 | | unicode character before printing. |
401 +---------+----------------------------------------------------------+
402 | ``'d'`` | Decimal Integer. Outputs the number in base 10. |
403 +---------+----------------------------------------------------------+
404 | ``'o'`` | Octal format. Outputs the number in base 8. |
405 +---------+----------------------------------------------------------+
406 | ``'x'`` | Hex format. Outputs the number in base 16, using lower- |
407 | | case letters for the digits above 9. |
408 +---------+----------------------------------------------------------+
409 | ``'X'`` | Hex format. Outputs the number in base 16, using upper- |
410 | | case letters for the digits above 9. |
411 +---------+----------------------------------------------------------+
Eric Smith5e18a202008-05-12 10:01:24 +0000412 | ``'n'`` | Number. This is the same as ``'d'``, except that it uses |
413 | | the current locale setting to insert the appropriate |
414 | | number separator characters. |
415 +---------+----------------------------------------------------------+
Georg Brandl3dbca812008-07-23 16:10:53 +0000416 | None | The same as ``'d'``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000417 +---------+----------------------------------------------------------+
Georg Brandl48310cd2009-01-03 21:18:54 +0000418
Eric Smith05c07742010-02-25 14:18:57 +0000419In addition to the above presentation types, integers can be formatted
420with the floating point presentation types listed below (except
421``'n'`` and None). When doing so, :func:`float` is used to convert the
422integer to a floating point number before formatting.
423
Georg Brandl4b491312007-08-31 09:22:56 +0000424The available presentation types for floating point and decimal values are:
Georg Brandl48310cd2009-01-03 21:18:54 +0000425
Georg Brandl4b491312007-08-31 09:22:56 +0000426 +---------+----------------------------------------------------------+
427 | Type | Meaning |
428 +=========+==========================================================+
429 | ``'e'`` | Exponent notation. Prints the number in scientific |
430 | | notation using the letter 'e' to indicate the exponent. |
431 +---------+----------------------------------------------------------+
Eric Smith22b85b32008-07-17 19:18:29 +0000432 | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an |
433 | | upper case 'E' as the separator character. |
Georg Brandl4b491312007-08-31 09:22:56 +0000434 +---------+----------------------------------------------------------+
435 | ``'f'`` | Fixed point. Displays the number as a fixed-point |
436 | | number. |
437 +---------+----------------------------------------------------------+
Eric Smith741191f2009-05-06 13:08:15 +0000438 | ``'F'`` | Fixed point. Same as ``'f'``, but converts ``nan`` to |
439 | | ``NAN`` and ``inf`` to ``INF``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000440 +---------+----------------------------------------------------------+
Mark Dickinsonc70614f2009-10-08 20:05:48 +0000441 | ``'g'`` | General format. For a given precision ``p >= 1``, |
442 | | this rounds the number to ``p`` significant digits and |
443 | | then formats the result in either fixed-point format |
444 | | or in scientific notation, depending on its magnitude. |
445 | | |
446 | | The precise rules are as follows: suppose that the |
447 | | result formatted with presentation type ``'e'`` and |
448 | | precision ``p-1`` would have exponent ``exp``. Then |
449 | | if ``-4 <= exp < p``, the number is formatted |
450 | | with presentation type ``'f'`` and precision |
451 | | ``p-1-exp``. Otherwise, the number is formatted |
452 | | with presentation type ``'e'`` and precision ``p-1``. |
453 | | In both cases insignificant trailing zeros are removed |
454 | | from the significand, and the decimal point is also |
455 | | removed if there are no remaining digits following it. |
456 | | |
Benjamin Peterson73a3f2d2010-10-12 23:07:13 +0000457 | | Positive and negative infinity, positive and negative |
Mark Dickinsonc70614f2009-10-08 20:05:48 +0000458 | | zero, and nans, are formatted as ``inf``, ``-inf``, |
459 | | ``0``, ``-0`` and ``nan`` respectively, regardless of |
460 | | the precision. |
461 | | |
462 | | A precision of ``0`` is treated as equivalent to a |
463 | | precision of ``1``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000464 +---------+----------------------------------------------------------+
465 | ``'G'`` | General format. Same as ``'g'`` except switches to |
Mark Dickinsonc70614f2009-10-08 20:05:48 +0000466 | | ``'E'`` if the number gets too large. The |
467 | | representations of infinity and NaN are uppercased, too. |
Georg Brandl4b491312007-08-31 09:22:56 +0000468 +---------+----------------------------------------------------------+
469 | ``'n'`` | Number. This is the same as ``'g'``, except that it uses |
470 | | the current locale setting to insert the appropriate |
471 | | number separator characters. |
472 +---------+----------------------------------------------------------+
473 | ``'%'`` | Percentage. Multiplies the number by 100 and displays |
474 | | in fixed (``'f'``) format, followed by a percent sign. |
475 +---------+----------------------------------------------------------+
Eric Smith3bef15b2009-05-05 17:19:46 +0000476 | None | Similar to ``'g'``, except with at least one digit past |
477 | | the decimal point and a default precision of 12. This is |
478 | | intended to match :func:`str`, except you can add the |
479 | | other format modifiers. |
Georg Brandl4b491312007-08-31 09:22:56 +0000480 +---------+----------------------------------------------------------+
481
482
Ezio Melottid2191e02010-07-02 23:18:51 +0000483.. _formatexamples:
484
485Format examples
486^^^^^^^^^^^^^^^
487
488This section contains examples of the new format syntax and comparison with
489the old ``%``-formatting.
490
491In most of the cases the syntax is similar to the old ``%``-formatting, with the
492addition of the ``{}`` and with ``:`` used instead of ``%``.
493For example, ``'%03.2f'`` can be translated to ``'{:03.2f}'``.
494
495The new format syntax also supports new and different options, shown in the
496follow examples.
497
498Accessing arguments by position::
499
500 >>> '{0}, {1}, {2}'.format('a', 'b', 'c')
501 'a, b, c'
502 >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only
503 'a, b, c'
504 >>> '{2}, {1}, {0}'.format('a', 'b', 'c')
505 'c, b, a'
506 >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence
507 'c, b, a'
508 >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated
509 'abracadabra'
510
511Accessing arguments by name::
512
513 >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
514 'Coordinates: 37.24N, -115.81W'
515 >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
516 >>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
517 'Coordinates: 37.24N, -115.81W'
518
519Accessing arguments' attributes::
520
521 >>> c = 3-5j
522 >>> ('The complex number {0} is formed from the real part {0.real} '
523 ... 'and the imaginary part {0.imag}.').format(c)
524 'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
525 >>> class Point:
526 ... def __init__(self, x, y):
527 ... self.x, self.y = x, y
528 ... def __str__(self):
529 ... return 'Point({self.x}, {self.y})'.format(self=self)
530 ...
531 >>> str(Point(4, 2))
532 'Point(4, 2)'
533
534Accessing arguments' items::
535
536 >>> coord = (3, 5)
537 >>> 'X: {0[0]}; Y: {0[1]}'.format(coord)
538 'X: 3; Y: 5'
539
540Replacing ``%s`` and ``%r``::
541
542 >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
543 "repr() shows quotes: 'test1'; str() doesn't: test2"
544
545Aligning the text and specifying a width::
546
547 >>> '{:<30}'.format('left aligned')
548 'left aligned '
549 >>> '{:>30}'.format('right aligned')
550 ' right aligned'
551 >>> '{:^30}'.format('centered')
552 ' centered '
553 >>> '{:*^30}'.format('centered') # use '*' as a fill char
554 '***********centered***********'
555
556Replacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign::
557
558 >>> '{:+f}; {:+f}'.format(3.14, -3.14) # show it always
559 '+3.140000; -3.140000'
560 >>> '{: f}; {: f}'.format(3.14, -3.14) # show a space for positive numbers
561 ' 3.140000; -3.140000'
562 >>> '{:-f}; {:-f}'.format(3.14, -3.14) # show only the minus -- same as '{:f}; {:f}'
563 '3.140000; -3.140000'
564
565Replacing ``%x`` and ``%o`` and converting the value to different bases::
566
567 >>> # format also supports binary numbers
568 >>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
569 'int: 42; hex: 2a; oct: 52; bin: 101010'
570 >>> # with 0x, 0o, or 0b as prefix:
571 >>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
572 'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
573
574Using the comma as a thousands separator::
575
576 >>> '{:,}'.format(1234567890)
577 '1,234,567,890'
578
579Expressing a percentage::
580
581 >>> points = 19
582 >>> total = 22
583 >>> 'Correct answers: {:.2%}.'.format(points/total)
584 'Correct answers: 86.36%'
585
586Using type-specific formatting::
587
588 >>> import datetime
589 >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
590 >>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
591 '2010-07-04 12:15:58'
592
593Nesting arguments and more complex examples::
594
595 >>> for align, text in zip('<^>', ['left', 'center', 'right']):
596 ... '{0:{align}{fill}16}'.format(text, fill=align, align=align)
597 ...
598 'left<<<<<<<<<<<<'
599 '^^^^^center^^^^^'
600 '>>>>>>>>>>>right'
601 >>>
602 >>> octets = [192, 168, 0, 1]
603 >>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
604 'C0A80001'
605 >>> int(_, 16)
606 3232235521
607 >>>
608 >>> width = 5
609 >>> for num in range(5,12):
610 ... for base in 'dXob':
611 ... print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
612 ... print()
613 ...
614 5 5 5 101
615 6 6 6 110
616 7 7 7 111
617 8 8 10 1000
618 9 9 11 1001
619 10 A 12 1010
620 11 B 13 1011
621
622
623
Georg Brandl4b491312007-08-31 09:22:56 +0000624.. _template-strings:
625
Georg Brandl116aa622007-08-15 14:28:22 +0000626Template strings
627----------------
628
629Templates provide simpler string substitutions as described in :pep:`292`.
630Instead of the normal ``%``\ -based substitutions, Templates support ``$``\
631-based substitutions, using the following rules:
632
633* ``$$`` is an escape; it is replaced with a single ``$``.
634
635* ``$identifier`` names a substitution placeholder matching a mapping key of
636 ``"identifier"``. By default, ``"identifier"`` must spell a Python
637 identifier. The first non-identifier character after the ``$`` character
638 terminates this placeholder specification.
639
640* ``${identifier}`` is equivalent to ``$identifier``. It is required when valid
641 identifier characters follow the placeholder but are not part of the
642 placeholder, such as ``"${noun}ification"``.
643
644Any other appearance of ``$`` in the string will result in a :exc:`ValueError`
645being raised.
646
Georg Brandl116aa622007-08-15 14:28:22 +0000647The :mod:`string` module provides a :class:`Template` class that implements
648these rules. The methods of :class:`Template` are:
649
650
651.. class:: Template(template)
652
653 The constructor takes a single argument which is the template string.
654
655
Georg Brandl7f01a132009-09-16 15:58:14 +0000656 .. method:: substitute(mapping, **kwds)
Georg Brandl116aa622007-08-15 14:28:22 +0000657
Benjamin Petersone41251e2008-04-25 01:59:09 +0000658 Performs the template substitution, returning a new string. *mapping* is
659 any dictionary-like object with keys that match the placeholders in the
660 template. Alternatively, you can provide keyword arguments, where the
Georg Brandl7f01a132009-09-16 15:58:14 +0000661 keywords are the placeholders. When both *mapping* and *kwds* are given
662 and there are duplicates, the placeholders from *kwds* take precedence.
Georg Brandl116aa622007-08-15 14:28:22 +0000663
664
Georg Brandl7f01a132009-09-16 15:58:14 +0000665 .. method:: safe_substitute(mapping, **kwds)
Georg Brandl116aa622007-08-15 14:28:22 +0000666
Benjamin Petersone41251e2008-04-25 01:59:09 +0000667 Like :meth:`substitute`, except that if placeholders are missing from
Georg Brandl7f01a132009-09-16 15:58:14 +0000668 *mapping* and *kwds*, instead of raising a :exc:`KeyError` exception, the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000669 original placeholder will appear in the resulting string intact. Also,
670 unlike with :meth:`substitute`, any other appearances of the ``$`` will
671 simply return ``$`` instead of raising :exc:`ValueError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000672
Benjamin Petersone41251e2008-04-25 01:59:09 +0000673 While other exceptions may still occur, this method is called "safe"
674 because substitutions always tries to return a usable string instead of
675 raising an exception. In another sense, :meth:`safe_substitute` may be
676 anything other than safe, since it will silently ignore malformed
677 templates containing dangling delimiters, unmatched braces, or
678 placeholders that are not valid Python identifiers.
Georg Brandl116aa622007-08-15 14:28:22 +0000679
Benjamin Peterson20211002009-11-25 18:34:42 +0000680 :class:`Template` instances also provide one public data attribute:
Georg Brandl116aa622007-08-15 14:28:22 +0000681
Benjamin Peterson20211002009-11-25 18:34:42 +0000682 .. attribute:: template
Georg Brandl116aa622007-08-15 14:28:22 +0000683
Benjamin Peterson20211002009-11-25 18:34:42 +0000684 This is the object passed to the constructor's *template* argument. In
685 general, you shouldn't change it, but read-only access is not enforced.
Georg Brandl116aa622007-08-15 14:28:22 +0000686
Christian Heimesfe337bf2008-03-23 21:54:12 +0000687Here is an example of how to use a Template:
Georg Brandl116aa622007-08-15 14:28:22 +0000688
689 >>> from string import Template
690 >>> s = Template('$who likes $what')
691 >>> s.substitute(who='tim', what='kung pao')
692 'tim likes kung pao'
693 >>> d = dict(who='tim')
694 >>> Template('Give $who $100').substitute(d)
695 Traceback (most recent call last):
696 [...]
697 ValueError: Invalid placeholder in string: line 1, col 10
698 >>> Template('$who likes $what').substitute(d)
699 Traceback (most recent call last):
700 [...]
701 KeyError: 'what'
702 >>> Template('$who likes $what').safe_substitute(d)
703 'tim likes $what'
704
705Advanced usage: you can derive subclasses of :class:`Template` to customize the
706placeholder syntax, delimiter character, or the entire regular expression used
707to parse template strings. To do this, you can override these class attributes:
708
709* *delimiter* -- This is the literal string describing a placeholder introducing
710 delimiter. The default value ``$``. Note that this should *not* be a regular
711 expression, as the implementation will call :meth:`re.escape` on this string as
712 needed.
713
714* *idpattern* -- This is the regular expression describing the pattern for
715 non-braced placeholders (the braces will be added automatically as
716 appropriate). The default value is the regular expression
717 ``[_a-z][_a-z0-9]*``.
718
Georg Brandl056cb932010-07-29 17:16:10 +0000719* *flags* -- The regular expression flags that will be applied when compiling
720 the regular expression used for recognizing substitutions. The default value
721 is ``re.IGNORECASE``. Note that ``re.VERBOSE`` will always be added to the
722 flags, so custom *idpattern*\ s must follow conventions for verbose regular
723 expressions.
724
725 .. versionadded:: 3.2
726
Georg Brandl116aa622007-08-15 14:28:22 +0000727Alternatively, you can provide the entire regular expression pattern by
728overriding the class attribute *pattern*. If you do this, the value must be a
729regular expression object with four named capturing groups. The capturing
730groups correspond to the rules given above, along with the invalid placeholder
731rule:
732
733* *escaped* -- This group matches the escape sequence, e.g. ``$$``, in the
734 default pattern.
735
736* *named* -- This group matches the unbraced placeholder name; it should not
737 include the delimiter in capturing group.
738
739* *braced* -- This group matches the brace enclosed placeholder name; it should
740 not include either the delimiter or braces in the capturing group.
741
742* *invalid* -- This group matches any other delimiter pattern (usually a single
743 delimiter), and it should appear last in the regular expression.
744
745
Georg Brandlabc38772009-04-12 15:51:51 +0000746Helper functions
Georg Brandl116aa622007-08-15 14:28:22 +0000747----------------
748
Georg Brandl10430ad2009-09-26 20:59:11 +0000749.. function:: capwords(s, sep=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000750
Ezio Melottia40bdda2009-09-26 12:33:22 +0000751 Split the argument into words using :meth:`str.split`, capitalize each word
752 using :meth:`str.capitalize`, and join the capitalized words using
753 :meth:`str.join`. If the optional second argument *sep* is absent
754 or ``None``, runs of whitespace characters are replaced by a single space
755 and leading and trailing whitespace are removed, otherwise *sep* is used to
756 split and join the words.
Georg Brandl116aa622007-08-15 14:28:22 +0000757