blob: b2d0bbaa4da4ece1250b2f8249885958e320ecf3 [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
Georg Brandl41d08152011-01-09 08:01:46 +00008.. seealso::
Georg Brandl116aa622007-08-15 14:28:22 +00009
Georg Brandl41d08152011-01-09 08:01:46 +000010 :ref:`typesseq`
Georg Brandl116aa622007-08-15 14:28:22 +000011
Georg Brandl41d08152011-01-09 08:01:46 +000012 :ref:`string-methods`
Georg Brandl116aa622007-08-15 14:28:22 +000013
14String constants
15----------------
16
17The constants defined in this module are:
18
19
20.. data:: ascii_letters
21
22 The concatenation of the :const:`ascii_lowercase` and :const:`ascii_uppercase`
23 constants described below. This value is not locale-dependent.
24
25
26.. data:: ascii_lowercase
27
28 The lowercase letters ``'abcdefghijklmnopqrstuvwxyz'``. This value is not
29 locale-dependent and will not change.
30
31
32.. data:: ascii_uppercase
33
34 The uppercase letters ``'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. This value is not
35 locale-dependent and will not change.
36
37
38.. data:: digits
39
40 The string ``'0123456789'``.
41
42
43.. data:: hexdigits
44
45 The string ``'0123456789abcdefABCDEF'``.
46
47
48.. data:: octdigits
49
50 The string ``'01234567'``.
51
52
53.. data:: punctuation
54
55 String of ASCII characters which are considered punctuation characters
56 in the ``C`` locale.
57
58
59.. data:: printable
60
61 String of ASCII characters which are considered printable. This is a
62 combination of :const:`digits`, :const:`ascii_letters`, :const:`punctuation`,
63 and :const:`whitespace`.
64
65
66.. data:: whitespace
67
Georg Brandl50767402008-11-22 08:31:09 +000068 A string containing all ASCII characters that are considered whitespace.
Georg Brandl116aa622007-08-15 14:28:22 +000069 This includes the characters space, tab, linefeed, return, formfeed, and
70 vertical tab.
71
72
Georg Brandl4b491312007-08-31 09:22:56 +000073.. _string-formatting:
74
75String Formatting
76-----------------
77
Benjamin Peterson50923f92008-05-25 19:45:17 +000078The built-in string class provides the ability to do complex variable
79substitutions and value formatting via the :func:`format` method described in
80:pep:`3101`. The :class:`Formatter` class in the :mod:`string` module allows
81you to create and customize your own string formatting behaviors using the same
82implementation as the built-in :meth:`format` method.
Georg Brandl4b491312007-08-31 09:22:56 +000083
Benjamin Peterson68dbebc2009-12-31 03:30:26 +000084
Georg Brandl4b491312007-08-31 09:22:56 +000085.. class:: Formatter
86
87 The :class:`Formatter` class has the following public methods:
88
Georg Brandl27743102011-02-25 10:18:11 +000089 .. method:: format(format_string, *args, **kwargs)
Georg Brandl4b491312007-08-31 09:22:56 +000090
91 :meth:`format` is the primary API method. It takes a format template
92 string, and an arbitrary set of positional and keyword argument.
93 :meth:`format` is just a wrapper that calls :meth:`vformat`.
94
95 .. method:: vformat(format_string, args, kwargs)
Georg Brandl48310cd2009-01-03 21:18:54 +000096
Georg Brandl4b491312007-08-31 09:22:56 +000097 This function does the actual work of formatting. It is exposed as a
98 separate function for cases where you want to pass in a predefined
99 dictionary of arguments, rather than unpacking and repacking the
100 dictionary as individual arguments using the ``*args`` and ``**kwds``
101 syntax. :meth:`vformat` does the work of breaking up the format template
102 string into character data and replacement fields. It calls the various
103 methods described below.
104
105 In addition, the :class:`Formatter` defines a number of methods that are
106 intended to be replaced by subclasses:
107
108 .. method:: parse(format_string)
Georg Brandl48310cd2009-01-03 21:18:54 +0000109
Georg Brandl4b491312007-08-31 09:22:56 +0000110 Loop over the format_string and return an iterable of tuples
111 (*literal_text*, *field_name*, *format_spec*, *conversion*). This is used
Georg Brandlf55aa802010-11-26 08:59:40 +0000112 by :meth:`vformat` to break the string into either literal text, or
Georg Brandl4b491312007-08-31 09:22:56 +0000113 replacement fields.
Georg Brandl48310cd2009-01-03 21:18:54 +0000114
Georg Brandl4b491312007-08-31 09:22:56 +0000115 The values in the tuple conceptually represent a span of literal text
116 followed by a single replacement field. If there is no literal text
117 (which can happen if two replacement fields occur consecutively), then
118 *literal_text* will be a zero-length string. If there is no replacement
119 field, then the values of *field_name*, *format_spec* and *conversion*
120 will be ``None``.
121
Eric Smith9d4ba392007-09-02 15:33:26 +0000122 .. method:: get_field(field_name, args, kwargs)
Georg Brandl4b491312007-08-31 09:22:56 +0000123
124 Given *field_name* as returned by :meth:`parse` (see above), convert it to
Georg Brandl7f13e6b2007-08-31 10:37:15 +0000125 an object to be formatted. Returns a tuple (obj, used_key). The default
126 version takes strings of the form defined in :pep:`3101`, such as
127 "0[name]" or "label.title". *args* and *kwargs* are as passed in to
128 :meth:`vformat`. The return value *used_key* has the same meaning as the
129 *key* parameter to :meth:`get_value`.
Georg Brandl4b491312007-08-31 09:22:56 +0000130
131 .. method:: get_value(key, args, kwargs)
Georg Brandl48310cd2009-01-03 21:18:54 +0000132
Georg Brandl4b491312007-08-31 09:22:56 +0000133 Retrieve a given field value. The *key* argument will be either an
134 integer or a string. If it is an integer, it represents the index of the
135 positional argument in *args*; if it is a string, then it represents a
136 named argument in *kwargs*.
137
138 The *args* parameter is set to the list of positional arguments to
139 :meth:`vformat`, and the *kwargs* parameter is set to the dictionary of
140 keyword arguments.
141
142 For compound field names, these functions are only called for the first
143 component of the field name; Subsequent components are handled through
144 normal attribute and indexing operations.
145
146 So for example, the field expression '0.name' would cause
147 :meth:`get_value` to be called with a *key* argument of 0. The ``name``
148 attribute will be looked up after :meth:`get_value` returns by calling the
149 built-in :func:`getattr` function.
150
151 If the index or keyword refers to an item that does not exist, then an
152 :exc:`IndexError` or :exc:`KeyError` should be raised.
153
154 .. method:: check_unused_args(used_args, args, kwargs)
155
156 Implement checking for unused arguments if desired. The arguments to this
157 function is the set of all argument keys that were actually referred to in
158 the format string (integers for positional arguments, and strings for
159 named arguments), and a reference to the *args* and *kwargs* that was
160 passed to vformat. The set of unused args can be calculated from these
Georg Brandl13f959b2010-10-06 08:35:38 +0000161 parameters. :meth:`check_unused_args` is assumed to raise an exception if
Georg Brandl4b491312007-08-31 09:22:56 +0000162 the check fails.
163
164 .. method:: format_field(value, format_spec)
165
166 :meth:`format_field` simply calls the global :func:`format` built-in. The
167 method is provided so that subclasses can override it.
168
169 .. method:: convert_field(value, conversion)
Georg Brandl48310cd2009-01-03 21:18:54 +0000170
Georg Brandl4b491312007-08-31 09:22:56 +0000171 Converts the value (returned by :meth:`get_field`) given a conversion type
Ezio Melotti795b8e32010-07-02 23:22:03 +0000172 (as in the tuple returned by the :meth:`parse` method). The default
Georg Brandl4b491312007-08-31 09:22:56 +0000173 version understands 'r' (repr) and 's' (str) conversion types.
174
Georg Brandl4b491312007-08-31 09:22:56 +0000175
176.. _formatstrings:
177
178Format String Syntax
179--------------------
180
181The :meth:`str.format` method and the :class:`Formatter` class share the same
182syntax for format strings (although in the case of :class:`Formatter`,
Ezio Melotti795b8e32010-07-02 23:22:03 +0000183subclasses can define their own format string syntax).
Georg Brandl4b491312007-08-31 09:22:56 +0000184
185Format strings contain "replacement fields" surrounded by curly braces ``{}``.
186Anything that is not contained in braces is considered literal text, which is
187copied unchanged to the output. If you need to include a brace character in the
188literal text, it can be escaped by doubling: ``{{`` and ``}}``.
189
190The grammar for a replacement field is as follows:
191
192 .. productionlist:: sf
Georg Brandl7baf6252009-09-01 08:13:16 +0000193 replacement_field: "{" [`field_name`] ["!" `conversion`] [":" `format_spec`] "}"
Eric Smithc4cae322009-04-22 00:53:01 +0000194 field_name: arg_name ("." `attribute_name` | "[" `element_index` "]")*
Georg Brandlc62efa82010-07-11 10:41:07 +0000195 arg_name: [`identifier` | `integer`]
Georg Brandl4b491312007-08-31 09:22:56 +0000196 attribute_name: `identifier`
Eric Smithde755692010-02-25 14:59:39 +0000197 element_index: `integer` | `index_string`
198 index_string: <any source character except "]"> +
Benjamin Peterson065ba702008-11-09 01:43:02 +0000199 conversion: "r" | "s" | "a"
Georg Brandl4b491312007-08-31 09:22:56 +0000200 format_spec: <described in the next section>
Georg Brandl48310cd2009-01-03 21:18:54 +0000201
Georg Brandl7baf6252009-09-01 08:13:16 +0000202In less formal terms, the replacement field can start with a *field_name* that specifies
Eric Smithc4cae322009-04-22 00:53:01 +0000203the object whose value is to be formatted and inserted
204into the output instead of the replacement field.
205The *field_name* is optionally followed by a *conversion* field, which is
Georg Brandl4b491312007-08-31 09:22:56 +0000206preceded by an exclamation point ``'!'``, and a *format_spec*, which is preceded
Eric Smithc4cae322009-04-22 00:53:01 +0000207by a colon ``':'``. These specify a non-default format for the replacement value.
Georg Brandl4b491312007-08-31 09:22:56 +0000208
Ezio Melotti795b8e32010-07-02 23:22:03 +0000209See also the :ref:`formatspec` section.
210
Eric Smithc4cae322009-04-22 00:53:01 +0000211The *field_name* itself begins with an *arg_name* that is either either a number or a
212keyword. If it's a number, it refers to a positional argument, and if it's a keyword,
213it refers to a named keyword argument. If the numerical arg_names in a format string
214are 0, 1, 2, ... in sequence, they can all be omitted (not just some)
215and the numbers 0, 1, 2, ... will be automatically inserted in that order.
216The *arg_name* can be followed by any number of index or
Georg Brandl4b491312007-08-31 09:22:56 +0000217attribute expressions. An expression of the form ``'.name'`` selects the named
218attribute using :func:`getattr`, while an expression of the form ``'[index]'``
219does an index lookup using :func:`__getitem__`.
220
Ezio Melotti795b8e32010-07-02 23:22:03 +0000221.. versionchanged:: 3.1
222 The positional argument specifiers can be omitted, so ``'{} {}'`` is
223 equivalent to ``'{0} {1}'``.
224
Georg Brandl4b491312007-08-31 09:22:56 +0000225Some simple format string examples::
226
227 "First, thou shalt count to {0}" # References first positional argument
Benjamin Peterson5879d412009-03-30 14:51:56 +0000228 "Bring me a {}" # Implicitly references the first positional argument
Georg Brandl7baf6252009-09-01 08:13:16 +0000229 "From {} to {}" # Same as "From {0} to {1}"
Georg Brandl4b491312007-08-31 09:22:56 +0000230 "My quest is {name}" # References keyword argument 'name'
231 "Weight in tons {0.weight}" # 'weight' attribute of first positional arg
232 "Units destroyed: {players[0]}" # First element of keyword argument 'players'.
Georg Brandl48310cd2009-01-03 21:18:54 +0000233
Georg Brandl4b491312007-08-31 09:22:56 +0000234The *conversion* field causes a type coercion before formatting. Normally, the
235job of formatting a value is done by the :meth:`__format__` method of the value
236itself. However, in some cases it is desirable to force a type to be formatted
237as a string, overriding its own definition of formatting. By converting the
238value to a string before calling :meth:`__format__`, the normal formatting logic
239is bypassed.
240
Georg Brandl559e5d72008-06-11 18:37:52 +0000241Three conversion flags are currently supported: ``'!s'`` which calls :func:`str`
242on the value, ``'!r'`` which calls :func:`repr` and ``'!a'`` which calls
243:func:`ascii`.
Georg Brandl4b491312007-08-31 09:22:56 +0000244
245Some examples::
246
247 "Harold's a clever {0!s}" # Calls str() on the argument first
248 "Bring out the holy {name!r}" # Calls repr() on the argument first
Georg Brandl7baf6252009-09-01 08:13:16 +0000249 "More {!a}" # Calls ascii() on the argument first
Georg Brandl4b491312007-08-31 09:22:56 +0000250
251The *format_spec* field contains a specification of how the value should be
252presented, including such details as field width, alignment, padding, decimal
Eric Smithee137ff2010-02-15 11:59:37 +0000253precision and so on. Each value type can define its own "formatting
Georg Brandl4b491312007-08-31 09:22:56 +0000254mini-language" or interpretation of the *format_spec*.
255
256Most built-in types support a common formatting mini-language, which is
257described in the next section.
258
259A *format_spec* field can also include nested replacement fields within it.
260These nested replacement fields can contain only a field name; conversion flags
261and format specifications are not allowed. The replacement fields within the
262format_spec are substituted before the *format_spec* string is interpreted.
263This allows the formatting of a value to be dynamically specified.
264
Ezio Melotti795b8e32010-07-02 23:22:03 +0000265See the :ref:`formatexamples` section for some examples.
Georg Brandl4b491312007-08-31 09:22:56 +0000266
Georg Brandl4b491312007-08-31 09:22:56 +0000267
268.. _formatspec:
269
270Format Specification Mini-Language
271^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
272
273"Format specifications" are used within replacement fields contained within a
274format string to define how individual values are presented (see
Ezio Melotti795b8e32010-07-02 23:22:03 +0000275:ref:`formatstrings`). They can also be passed directly to the built-in
Georg Brandl4b491312007-08-31 09:22:56 +0000276:func:`format` function. Each formattable type may define how the format
277specification is to be interpreted.
278
279Most built-in types implement the following options for format specifications,
280although some of the formatting options are only supported by the numeric types.
281
Eric Smithea2e7892010-02-25 14:20:36 +0000282A general convention is that an empty format string (``""``) produces
283the same result as if you had called :func:`str` on the value. A
284non-empty format string typically modifies the result.
Georg Brandl4b491312007-08-31 09:22:56 +0000285
286The general form of a *standard format specifier* is:
287
288.. productionlist:: sf
Raymond Hettinger868aa062009-07-12 20:47:13 +0000289 format_spec: [[`fill`]`align`][`sign`][#][0][`width`][,][.`precision`][`type`]
Georg Brandl4b491312007-08-31 09:22:56 +0000290 fill: <a character other than '}'>
291 align: "<" | ">" | "=" | "^"
292 sign: "+" | "-" | " "
293 width: `integer`
294 precision: `integer`
Eric Smithea2e7892010-02-25 14:20:36 +0000295 type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
Georg Brandl48310cd2009-01-03 21:18:54 +0000296
Georg Brandl57a5e3f2010-10-06 08:54:16 +0000297The *fill* character can be any character other than '{' or '}'. The presence
298of a fill character is signaled by the character following it, which must be
299one of the alignment options. If the second character of *format_spec* is not
300a valid alignment option, then it is assumed that both the fill character and
301the alignment option are absent.
Georg Brandl4b491312007-08-31 09:22:56 +0000302
303The meaning of the various alignment options is as follows:
304
305 +---------+----------------------------------------------------------+
306 | Option | Meaning |
307 +=========+==========================================================+
308 | ``'<'`` | Forces the field to be left-aligned within the available |
Georg Brandl27743102011-02-25 10:18:11 +0000309 | | space (this is the default for most objects). |
Georg Brandl4b491312007-08-31 09:22:56 +0000310 +---------+----------------------------------------------------------+
311 | ``'>'`` | Forces the field to be right-aligned within the |
Georg Brandl27743102011-02-25 10:18:11 +0000312 | | available space (this is the default for numbers). |
Georg Brandl4b491312007-08-31 09:22:56 +0000313 +---------+----------------------------------------------------------+
314 | ``'='`` | Forces the padding to be placed after the sign (if any) |
315 | | but before the digits. This is used for printing fields |
316 | | in the form '+000000120'. This alignment option is only |
317 | | valid for numeric types. |
318 +---------+----------------------------------------------------------+
319 | ``'^'`` | Forces the field to be centered within the available |
320 | | space. |
321 +---------+----------------------------------------------------------+
322
323Note that unless a minimum field width is defined, the field width will always
324be the same size as the data to fill it, so that the alignment option has no
325meaning in this case.
326
327The *sign* option is only valid for number types, and can be one of the
328following:
329
330 +---------+----------------------------------------------------------+
331 | Option | Meaning |
332 +=========+==========================================================+
333 | ``'+'`` | indicates that a sign should be used for both |
334 | | positive as well as negative numbers. |
335 +---------+----------------------------------------------------------+
336 | ``'-'`` | indicates that a sign should be used only for negative |
337 | | numbers (this is the default behavior). |
338 +---------+----------------------------------------------------------+
339 | space | indicates that a leading space should be used on |
340 | | positive numbers, and a minus sign on negative numbers. |
341 +---------+----------------------------------------------------------+
342
Benjamin Petersond7b03282008-09-13 15:58:53 +0000343The ``'#'`` option is only valid for integers, and only for binary, octal, or
344hexadecimal output. If present, it specifies that the output will be prefixed
345by ``'0b'``, ``'0o'``, or ``'0x'``, respectively.
Eric Smithd68af8f2008-07-16 00:15:35 +0000346
Raymond Hettinger868aa062009-07-12 20:47:13 +0000347The ``','`` option signals the use of a comma for a thousands separator.
348For a locale aware separator, use the ``'n'`` integer presentation type
349instead.
350
Ezio Melotti795b8e32010-07-02 23:22:03 +0000351.. versionchanged:: 3.1
352 Added the ``','`` option (see also :pep:`378`).
353
Georg Brandl4b491312007-08-31 09:22:56 +0000354*width* is a decimal integer defining the minimum field width. If not
355specified, then the field width will be determined by the content.
356
357If the *width* field is preceded by a zero (``'0'``) character, this enables
358zero-padding. This is equivalent to an *alignment* type of ``'='`` and a *fill*
359character of ``'0'``.
360
361The *precision* is a decimal number indicating how many digits should be
Georg Brandl3dbca812008-07-23 16:10:53 +0000362displayed after the decimal point for a floating point value formatted with
363``'f'`` and ``'F'``, or before and after the decimal point for a floating point
364value formatted with ``'g'`` or ``'G'``. For non-number types the field
365indicates the maximum field size - in other words, how many characters will be
Eric Smithe5fffc72009-05-07 19:38:09 +0000366used from the field content. The *precision* is not allowed for integer values.
Georg Brandl4b491312007-08-31 09:22:56 +0000367
368Finally, the *type* determines how the data should be presented.
369
Eric Smithea2e7892010-02-25 14:20:36 +0000370The available string presentation types are:
371
372 +---------+----------------------------------------------------------+
373 | Type | Meaning |
374 +=========+==========================================================+
375 | ``'s'`` | String format. This is the default type for strings and |
376 | | may be omitted. |
377 +---------+----------------------------------------------------------+
378 | None | The same as ``'s'``. |
379 +---------+----------------------------------------------------------+
380
Georg Brandl4b491312007-08-31 09:22:56 +0000381The available integer presentation types are:
382
383 +---------+----------------------------------------------------------+
384 | Type | Meaning |
385 +=========+==========================================================+
Eric Smithd68af8f2008-07-16 00:15:35 +0000386 | ``'b'`` | Binary format. Outputs the number in base 2. |
Georg Brandl4b491312007-08-31 09:22:56 +0000387 +---------+----------------------------------------------------------+
388 | ``'c'`` | Character. Converts the integer to the corresponding |
389 | | unicode character before printing. |
390 +---------+----------------------------------------------------------+
391 | ``'d'`` | Decimal Integer. Outputs the number in base 10. |
392 +---------+----------------------------------------------------------+
393 | ``'o'`` | Octal format. Outputs the number in base 8. |
394 +---------+----------------------------------------------------------+
395 | ``'x'`` | Hex format. Outputs the number in base 16, using lower- |
396 | | case letters for the digits above 9. |
397 +---------+----------------------------------------------------------+
398 | ``'X'`` | Hex format. Outputs the number in base 16, using upper- |
399 | | case letters for the digits above 9. |
400 +---------+----------------------------------------------------------+
Eric Smith5e18a202008-05-12 10:01:24 +0000401 | ``'n'`` | Number. This is the same as ``'d'``, except that it uses |
402 | | the current locale setting to insert the appropriate |
403 | | number separator characters. |
404 +---------+----------------------------------------------------------+
Georg Brandl3dbca812008-07-23 16:10:53 +0000405 | None | The same as ``'d'``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000406 +---------+----------------------------------------------------------+
Georg Brandl48310cd2009-01-03 21:18:54 +0000407
Eric Smithea2e7892010-02-25 14:20:36 +0000408In addition to the above presentation types, integers can be formatted
409with the floating point presentation types listed below (except
410``'n'`` and None). When doing so, :func:`float` is used to convert the
411integer to a floating point number before formatting.
412
Georg Brandl4b491312007-08-31 09:22:56 +0000413The available presentation types for floating point and decimal values are:
Georg Brandl48310cd2009-01-03 21:18:54 +0000414
Georg Brandl4b491312007-08-31 09:22:56 +0000415 +---------+----------------------------------------------------------+
416 | Type | Meaning |
417 +=========+==========================================================+
418 | ``'e'`` | Exponent notation. Prints the number in scientific |
419 | | notation using the letter 'e' to indicate the exponent. |
420 +---------+----------------------------------------------------------+
Eric Smith22b85b32008-07-17 19:18:29 +0000421 | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an |
422 | | upper case 'E' as the separator character. |
Georg Brandl4b491312007-08-31 09:22:56 +0000423 +---------+----------------------------------------------------------+
424 | ``'f'`` | Fixed point. Displays the number as a fixed-point |
425 | | number. |
426 +---------+----------------------------------------------------------+
Eric Smith741191f2009-05-06 13:08:15 +0000427 | ``'F'`` | Fixed point. Same as ``'f'``, but converts ``nan`` to |
428 | | ``NAN`` and ``inf`` to ``INF``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000429 +---------+----------------------------------------------------------+
Mark Dickinson7b5c8262009-10-08 20:06:27 +0000430 | ``'g'`` | General format. For a given precision ``p >= 1``, |
431 | | this rounds the number to ``p`` significant digits and |
432 | | then formats the result in either fixed-point format |
433 | | or in scientific notation, depending on its magnitude. |
434 | | |
435 | | The precise rules are as follows: suppose that the |
436 | | result formatted with presentation type ``'e'`` and |
437 | | precision ``p-1`` would have exponent ``exp``. Then |
438 | | if ``-4 <= exp < p``, the number is formatted |
439 | | with presentation type ``'f'`` and precision |
440 | | ``p-1-exp``. Otherwise, the number is formatted |
441 | | with presentation type ``'e'`` and precision ``p-1``. |
442 | | In both cases insignificant trailing zeros are removed |
443 | | from the significand, and the decimal point is also |
444 | | removed if there are no remaining digits following it. |
445 | | |
Benjamin Petersona3562712010-10-12 23:10:04 +0000446 | | Positive and negative infinity, positive and negative |
Mark Dickinson7b5c8262009-10-08 20:06:27 +0000447 | | zero, and nans, are formatted as ``inf``, ``-inf``, |
448 | | ``0``, ``-0`` and ``nan`` respectively, regardless of |
449 | | the precision. |
450 | | |
451 | | A precision of ``0`` is treated as equivalent to a |
452 | | precision of ``1``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000453 +---------+----------------------------------------------------------+
454 | ``'G'`` | General format. Same as ``'g'`` except switches to |
Mark Dickinson7b5c8262009-10-08 20:06:27 +0000455 | | ``'E'`` if the number gets too large. The |
456 | | representations of infinity and NaN are uppercased, too. |
Georg Brandl4b491312007-08-31 09:22:56 +0000457 +---------+----------------------------------------------------------+
458 | ``'n'`` | Number. This is the same as ``'g'``, except that it uses |
459 | | the current locale setting to insert the appropriate |
460 | | number separator characters. |
461 +---------+----------------------------------------------------------+
462 | ``'%'`` | Percentage. Multiplies the number by 100 and displays |
463 | | in fixed (``'f'``) format, followed by a percent sign. |
464 +---------+----------------------------------------------------------+
Eric Smith3bef15b2009-05-05 17:19:46 +0000465 | None | Similar to ``'g'``, except with at least one digit past |
466 | | the decimal point and a default precision of 12. This is |
467 | | intended to match :func:`str`, except you can add the |
468 | | other format modifiers. |
Georg Brandl4b491312007-08-31 09:22:56 +0000469 +---------+----------------------------------------------------------+
470
471
Ezio Melotti795b8e32010-07-02 23:22:03 +0000472.. _formatexamples:
473
474Format examples
475^^^^^^^^^^^^^^^
476
477This section contains examples of the new format syntax and comparison with
478the old ``%``-formatting.
479
480In most of the cases the syntax is similar to the old ``%``-formatting, with the
481addition of the ``{}`` and with ``:`` used instead of ``%``.
482For example, ``'%03.2f'`` can be translated to ``'{:03.2f}'``.
483
484The new format syntax also supports new and different options, shown in the
485follow examples.
486
487Accessing arguments by position::
488
489 >>> '{0}, {1}, {2}'.format('a', 'b', 'c')
490 'a, b, c'
491 >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only
492 'a, b, c'
493 >>> '{2}, {1}, {0}'.format('a', 'b', 'c')
494 'c, b, a'
495 >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence
496 'c, b, a'
497 >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated
498 'abracadabra'
499
500Accessing arguments by name::
501
502 >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
503 'Coordinates: 37.24N, -115.81W'
504 >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
505 >>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
506 'Coordinates: 37.24N, -115.81W'
507
508Accessing arguments' attributes::
509
510 >>> c = 3-5j
511 >>> ('The complex number {0} is formed from the real part {0.real} '
512 ... 'and the imaginary part {0.imag}.').format(c)
513 'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
514 >>> class Point:
515 ... def __init__(self, x, y):
516 ... self.x, self.y = x, y
517 ... def __str__(self):
518 ... return 'Point({self.x}, {self.y})'.format(self=self)
519 ...
520 >>> str(Point(4, 2))
521 'Point(4, 2)'
522
523Accessing arguments' items::
524
525 >>> coord = (3, 5)
526 >>> 'X: {0[0]}; Y: {0[1]}'.format(coord)
527 'X: 3; Y: 5'
528
529Replacing ``%s`` and ``%r``::
530
531 >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
532 "repr() shows quotes: 'test1'; str() doesn't: test2"
533
534Aligning the text and specifying a width::
535
536 >>> '{:<30}'.format('left aligned')
537 'left aligned '
538 >>> '{:>30}'.format('right aligned')
539 ' right aligned'
540 >>> '{:^30}'.format('centered')
541 ' centered '
542 >>> '{:*^30}'.format('centered') # use '*' as a fill char
543 '***********centered***********'
544
545Replacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign::
546
547 >>> '{:+f}; {:+f}'.format(3.14, -3.14) # show it always
548 '+3.140000; -3.140000'
549 >>> '{: f}; {: f}'.format(3.14, -3.14) # show a space for positive numbers
550 ' 3.140000; -3.140000'
551 >>> '{:-f}; {:-f}'.format(3.14, -3.14) # show only the minus -- same as '{:f}; {:f}'
552 '3.140000; -3.140000'
553
554Replacing ``%x`` and ``%o`` and converting the value to different bases::
555
556 >>> # format also supports binary numbers
557 >>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
558 'int: 42; hex: 2a; oct: 52; bin: 101010'
559 >>> # with 0x, 0o, or 0b as prefix:
560 >>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
561 'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
562
563Using the comma as a thousands separator::
564
565 >>> '{:,}'.format(1234567890)
566 '1,234,567,890'
567
568Expressing a percentage::
569
570 >>> points = 19
571 >>> total = 22
572 >>> 'Correct answers: {:.2%}.'.format(points/total)
573 'Correct answers: 86.36%'
574
575Using type-specific formatting::
576
577 >>> import datetime
578 >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
579 >>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
580 '2010-07-04 12:15:58'
581
582Nesting arguments and more complex examples::
583
584 >>> for align, text in zip('<^>', ['left', 'center', 'right']):
Georg Brandl27743102011-02-25 10:18:11 +0000585 ... '{0:{fill}{align}16}'.format(text, fill=align, align=align)
Ezio Melotti795b8e32010-07-02 23:22:03 +0000586 ...
587 'left<<<<<<<<<<<<'
588 '^^^^^center^^^^^'
589 '>>>>>>>>>>>right'
590 >>>
591 >>> octets = [192, 168, 0, 1]
592 >>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
593 'C0A80001'
594 >>> int(_, 16)
595 3232235521
596 >>>
597 >>> width = 5
598 >>> for num in range(5,12):
599 ... for base in 'dXob':
600 ... print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
601 ... print()
602 ...
603 5 5 5 101
604 6 6 6 110
605 7 7 7 111
606 8 8 10 1000
607 9 9 11 1001
608 10 A 12 1010
609 11 B 13 1011
610
611
612
Georg Brandl4b491312007-08-31 09:22:56 +0000613.. _template-strings:
614
Georg Brandl116aa622007-08-15 14:28:22 +0000615Template strings
616----------------
617
618Templates provide simpler string substitutions as described in :pep:`292`.
619Instead of the normal ``%``\ -based substitutions, Templates support ``$``\
620-based substitutions, using the following rules:
621
622* ``$$`` is an escape; it is replaced with a single ``$``.
623
624* ``$identifier`` names a substitution placeholder matching a mapping key of
625 ``"identifier"``. By default, ``"identifier"`` must spell a Python
626 identifier. The first non-identifier character after the ``$`` character
627 terminates this placeholder specification.
628
629* ``${identifier}`` is equivalent to ``$identifier``. It is required when valid
630 identifier characters follow the placeholder but are not part of the
631 placeholder, such as ``"${noun}ification"``.
632
633Any other appearance of ``$`` in the string will result in a :exc:`ValueError`
634being raised.
635
Georg Brandl116aa622007-08-15 14:28:22 +0000636The :mod:`string` module provides a :class:`Template` class that implements
637these rules. The methods of :class:`Template` are:
638
639
640.. class:: Template(template)
641
642 The constructor takes a single argument which is the template string.
643
644
Georg Brandlb044b2a2009-09-16 16:05:59 +0000645 .. method:: substitute(mapping, **kwds)
Georg Brandl116aa622007-08-15 14:28:22 +0000646
Benjamin Petersone41251e2008-04-25 01:59:09 +0000647 Performs the template substitution, returning a new string. *mapping* is
648 any dictionary-like object with keys that match the placeholders in the
649 template. Alternatively, you can provide keyword arguments, where the
Georg Brandlb044b2a2009-09-16 16:05:59 +0000650 keywords are the placeholders. When both *mapping* and *kwds* are given
651 and there are duplicates, the placeholders from *kwds* take precedence.
Georg Brandl116aa622007-08-15 14:28:22 +0000652
653
Georg Brandlb044b2a2009-09-16 16:05:59 +0000654 .. method:: safe_substitute(mapping, **kwds)
Georg Brandl116aa622007-08-15 14:28:22 +0000655
Benjamin Petersone41251e2008-04-25 01:59:09 +0000656 Like :meth:`substitute`, except that if placeholders are missing from
Georg Brandlb044b2a2009-09-16 16:05:59 +0000657 *mapping* and *kwds*, instead of raising a :exc:`KeyError` exception, the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000658 original placeholder will appear in the resulting string intact. Also,
659 unlike with :meth:`substitute`, any other appearances of the ``$`` will
660 simply return ``$`` instead of raising :exc:`ValueError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000661
Benjamin Petersone41251e2008-04-25 01:59:09 +0000662 While other exceptions may still occur, this method is called "safe"
663 because substitutions always tries to return a usable string instead of
664 raising an exception. In another sense, :meth:`safe_substitute` may be
665 anything other than safe, since it will silently ignore malformed
666 templates containing dangling delimiters, unmatched braces, or
667 placeholders that are not valid Python identifiers.
Georg Brandl116aa622007-08-15 14:28:22 +0000668
Benjamin Peterson39778f62009-11-25 18:37:12 +0000669 :class:`Template` instances also provide one public data attribute:
Georg Brandl116aa622007-08-15 14:28:22 +0000670
Benjamin Peterson39778f62009-11-25 18:37:12 +0000671 .. attribute:: template
Georg Brandl116aa622007-08-15 14:28:22 +0000672
Benjamin Peterson39778f62009-11-25 18:37:12 +0000673 This is the object passed to the constructor's *template* argument. In
674 general, you shouldn't change it, but read-only access is not enforced.
Georg Brandl116aa622007-08-15 14:28:22 +0000675
Christian Heimesfe337bf2008-03-23 21:54:12 +0000676Here is an example of how to use a Template:
Georg Brandl116aa622007-08-15 14:28:22 +0000677
678 >>> from string import Template
679 >>> s = Template('$who likes $what')
680 >>> s.substitute(who='tim', what='kung pao')
681 'tim likes kung pao'
682 >>> d = dict(who='tim')
683 >>> Template('Give $who $100').substitute(d)
684 Traceback (most recent call last):
685 [...]
686 ValueError: Invalid placeholder in string: line 1, col 10
687 >>> Template('$who likes $what').substitute(d)
688 Traceback (most recent call last):
689 [...]
690 KeyError: 'what'
691 >>> Template('$who likes $what').safe_substitute(d)
692 'tim likes $what'
693
694Advanced usage: you can derive subclasses of :class:`Template` to customize the
695placeholder syntax, delimiter character, or the entire regular expression used
696to parse template strings. To do this, you can override these class attributes:
697
698* *delimiter* -- This is the literal string describing a placeholder introducing
699 delimiter. The default value ``$``. Note that this should *not* be a regular
700 expression, as the implementation will call :meth:`re.escape` on this string as
701 needed.
702
703* *idpattern* -- This is the regular expression describing the pattern for
704 non-braced placeholders (the braces will be added automatically as
705 appropriate). The default value is the regular expression
706 ``[_a-z][_a-z0-9]*``.
707
708Alternatively, you can provide the entire regular expression pattern by
709overriding the class attribute *pattern*. If you do this, the value must be a
710regular expression object with four named capturing groups. The capturing
711groups correspond to the rules given above, along with the invalid placeholder
712rule:
713
714* *escaped* -- This group matches the escape sequence, e.g. ``$$``, in the
715 default pattern.
716
717* *named* -- This group matches the unbraced placeholder name; it should not
718 include the delimiter in capturing group.
719
720* *braced* -- This group matches the brace enclosed placeholder name; it should
721 not include either the delimiter or braces in the capturing group.
722
723* *invalid* -- This group matches any other delimiter pattern (usually a single
724 delimiter), and it should appear last in the regular expression.
725
726
Georg Brandlabc38772009-04-12 15:51:51 +0000727Helper functions
Georg Brandl116aa622007-08-15 14:28:22 +0000728----------------
729
Ezio Melotti029625c2009-09-26 12:35:01 +0000730.. function:: capwords(s[, sep])
Georg Brandl116aa622007-08-15 14:28:22 +0000731
Ezio Melotti029625c2009-09-26 12:35:01 +0000732 Split the argument into words using :meth:`str.split`, capitalize each word
733 using :meth:`str.capitalize`, and join the capitalized words using
734 :meth:`str.join`. If the optional second argument *sep* is absent
735 or ``None``, runs of whitespace characters are replaced by a single space
736 and leading and trailing whitespace are removed, otherwise *sep* is used to
737 split and join the words.
Georg Brandl116aa622007-08-15 14:28:22 +0000738
739
Georg Brandl7f13e6b2007-08-31 10:37:15 +0000740.. function:: maketrans(frm, to)
Georg Brandl116aa622007-08-15 14:28:22 +0000741
Georg Brandl7f13e6b2007-08-31 10:37:15 +0000742 Return a translation table suitable for passing to :meth:`bytes.translate`,
743 that will map each character in *from* into the character at the same
744 position in *to*; *from* and *to* must have the same length.
Georg Brandlabc38772009-04-12 15:51:51 +0000745
746 .. deprecated:: 3.1
747 Use the :meth:`bytes.maketrans` static method instead.