blob: 9ee81b596cb31b09cdbc69c1c3291e0b70b2e221 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001:mod:`string` --- Common string operations
2==========================================
3
4.. module:: string
5 :synopsis: Common string operations.
6
7
8.. index:: module: re
9
Éric Araujo29a0b572011-08-19 02:14:03 +020010**Source code:** :source:`Lib/string.py`
11
12--------------
13
Georg Brandl8ec7f652007-08-15 14:28:01 +000014The :mod:`string` module contains a number of useful constants and
15classes, as well as some deprecated legacy functions that are also
16available as methods on strings. In addition, Python's built-in string
17classes support the sequence type methods described in the
18:ref:`typesseq` section, and also the string-specific methods described
19in the :ref:`string-methods` section. To output formatted strings use
20template strings or the ``%`` operator described in the
21:ref:`string-formatting` section. Also, see the :mod:`re` module for
22string functions based on regular expressions.
23
Georg Brandl8ec7f652007-08-15 14:28:01 +000024String constants
25----------------
26
27The constants defined in this module are:
28
29
30.. data:: ascii_letters
31
32 The concatenation of the :const:`ascii_lowercase` and :const:`ascii_uppercase`
33 constants described below. This value is not locale-dependent.
34
35
36.. data:: ascii_lowercase
37
38 The lowercase letters ``'abcdefghijklmnopqrstuvwxyz'``. This value is not
39 locale-dependent and will not change.
40
41
42.. data:: ascii_uppercase
43
44 The uppercase letters ``'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. This value is not
45 locale-dependent and will not change.
46
47
48.. data:: digits
49
50 The string ``'0123456789'``.
51
52
53.. data:: hexdigits
54
55 The string ``'0123456789abcdefABCDEF'``.
56
57
58.. data:: letters
59
60 The concatenation of the strings :const:`lowercase` and :const:`uppercase`
61 described below. The specific value is locale-dependent, and will be updated
62 when :func:`locale.setlocale` is called.
63
64
65.. data:: lowercase
66
67 A string containing all the characters that are considered lowercase letters.
Georg Brandld5ad6da2009-03-04 18:24:41 +000068 On most systems this is the string ``'abcdefghijklmnopqrstuvwxyz'``. The
69 specific value is locale-dependent, and will be updated when
70 :func:`locale.setlocale` is called.
Georg Brandl8ec7f652007-08-15 14:28:01 +000071
72
73.. data:: octdigits
74
75 The string ``'01234567'``.
76
77
78.. data:: punctuation
79
80 String of ASCII characters which are considered punctuation characters in the
81 ``C`` locale.
82
83
84.. data:: printable
85
86 String of characters which are considered printable. This is a combination of
87 :const:`digits`, :const:`letters`, :const:`punctuation`, and
88 :const:`whitespace`.
89
90
91.. data:: uppercase
92
93 A string containing all the characters that are considered uppercase letters.
Georg Brandld5ad6da2009-03-04 18:24:41 +000094 On most systems this is the string ``'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. The
95 specific value is locale-dependent, and will be updated when
96 :func:`locale.setlocale` is called.
Georg Brandl8ec7f652007-08-15 14:28:01 +000097
98
99.. data:: whitespace
100
101 A string containing all characters that are considered whitespace. On most
102 systems this includes the characters space, tab, linefeed, return, formfeed, and
Georg Brandld5ad6da2009-03-04 18:24:41 +0000103 vertical tab.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000104
105
Benjamin Petersonc15205e2008-05-25 20:05:52 +0000106.. _new-string-formatting:
Georg Brandle321c2f2008-05-12 16:45:43 +0000107
108String Formatting
109-----------------
110
Georg Brandl8b10f132009-12-19 17:30:28 +0000111.. versionadded:: 2.6
112
113The built-in str and unicode classes provide the ability
Benjamin Petersonc15205e2008-05-25 20:05:52 +0000114to do complex variable substitutions and value formatting via the
115:meth:`str.format` method described in :pep:`3101`. The :class:`Formatter`
116class in the :mod:`string` module allows you to create and customize your own
117string formatting behaviors using the same implementation as the built-in
Georg Brandle321c2f2008-05-12 16:45:43 +0000118:meth:`format` method.
119
120.. class:: Formatter
121
122 The :class:`Formatter` class has the following public methods:
123
Georg Brandl28046022011-02-25 11:01:04 +0000124 .. method:: format(format_string, *args, **kwargs)
Georg Brandle321c2f2008-05-12 16:45:43 +0000125
126 :meth:`format` is the primary API method. It takes a format template
127 string, and an arbitrary set of positional and keyword argument.
128 :meth:`format` is just a wrapper that calls :meth:`vformat`.
129
130 .. method:: vformat(format_string, args, kwargs)
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000131
Georg Brandle321c2f2008-05-12 16:45:43 +0000132 This function does the actual work of formatting. It is exposed as a
133 separate function for cases where you want to pass in a predefined
134 dictionary of arguments, rather than unpacking and repacking the
135 dictionary as individual arguments using the ``*args`` and ``**kwds``
136 syntax. :meth:`vformat` does the work of breaking up the format template
137 string into character data and replacement fields. It calls the various
138 methods described below.
139
140 In addition, the :class:`Formatter` defines a number of methods that are
141 intended to be replaced by subclasses:
142
143 .. method:: parse(format_string)
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000144
Georg Brandle321c2f2008-05-12 16:45:43 +0000145 Loop over the format_string and return an iterable of tuples
146 (*literal_text*, *field_name*, *format_spec*, *conversion*). This is used
Georg Brandl3b85b9b2010-11-26 08:20:18 +0000147 by :meth:`vformat` to break the string into either literal text, or
Georg Brandle321c2f2008-05-12 16:45:43 +0000148 replacement fields.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000149
Georg Brandle321c2f2008-05-12 16:45:43 +0000150 The values in the tuple conceptually represent a span of literal text
151 followed by a single replacement field. If there is no literal text
152 (which can happen if two replacement fields occur consecutively), then
153 *literal_text* will be a zero-length string. If there is no replacement
154 field, then the values of *field_name*, *format_spec* and *conversion*
155 will be ``None``.
156
157 .. method:: get_field(field_name, args, kwargs)
158
159 Given *field_name* as returned by :meth:`parse` (see above), convert it to
160 an object to be formatted. Returns a tuple (obj, used_key). The default
161 version takes strings of the form defined in :pep:`3101`, such as
162 "0[name]" or "label.title". *args* and *kwargs* are as passed in to
163 :meth:`vformat`. The return value *used_key* has the same meaning as the
164 *key* parameter to :meth:`get_value`.
165
166 .. method:: get_value(key, args, kwargs)
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000167
Georg Brandle321c2f2008-05-12 16:45:43 +0000168 Retrieve a given field value. The *key* argument will be either an
169 integer or a string. If it is an integer, it represents the index of the
170 positional argument in *args*; if it is a string, then it represents a
171 named argument in *kwargs*.
172
173 The *args* parameter is set to the list of positional arguments to
174 :meth:`vformat`, and the *kwargs* parameter is set to the dictionary of
175 keyword arguments.
176
177 For compound field names, these functions are only called for the first
178 component of the field name; Subsequent components are handled through
179 normal attribute and indexing operations.
180
181 So for example, the field expression '0.name' would cause
182 :meth:`get_value` to be called with a *key* argument of 0. The ``name``
183 attribute will be looked up after :meth:`get_value` returns by calling the
184 built-in :func:`getattr` function.
185
186 If the index or keyword refers to an item that does not exist, then an
187 :exc:`IndexError` or :exc:`KeyError` should be raised.
188
189 .. method:: check_unused_args(used_args, args, kwargs)
190
191 Implement checking for unused arguments if desired. The arguments to this
192 function is the set of all argument keys that were actually referred to in
193 the format string (integers for positional arguments, and strings for
194 named arguments), and a reference to the *args* and *kwargs* that was
195 passed to vformat. The set of unused args can be calculated from these
Georg Brandl21946af2010-10-06 09:28:45 +0000196 parameters. :meth:`check_unused_args` is assumed to raise an exception if
Georg Brandle321c2f2008-05-12 16:45:43 +0000197 the check fails.
198
199 .. method:: format_field(value, format_spec)
200
201 :meth:`format_field` simply calls the global :func:`format` built-in. The
202 method is provided so that subclasses can override it.
203
204 .. method:: convert_field(value, conversion)
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000205
Georg Brandle321c2f2008-05-12 16:45:43 +0000206 Converts the value (returned by :meth:`get_field`) given a conversion type
Ezio Melottie11690a2010-07-02 22:17:29 +0000207 (as in the tuple returned by the :meth:`parse` method). The default
Georg Brandle321c2f2008-05-12 16:45:43 +0000208 version understands 'r' (repr) and 's' (str) conversion types.
209
210
211.. _formatstrings:
212
213Format String Syntax
214--------------------
215
216The :meth:`str.format` method and the :class:`Formatter` class share the same
217syntax for format strings (although in the case of :class:`Formatter`,
Eric Smith68f59412010-07-02 21:44:16 +0000218subclasses can define their own format string syntax).
Georg Brandle321c2f2008-05-12 16:45:43 +0000219
220Format strings contain "replacement fields" surrounded by curly braces ``{}``.
221Anything that is not contained in braces is considered literal text, which is
222copied unchanged to the output. If you need to include a brace character in the
223literal text, it can be escaped by doubling: ``{{`` and ``}}``.
224
225The grammar for a replacement field is as follows:
226
227 .. productionlist:: sf
Georg Brandl254c17c2009-09-01 07:40:54 +0000228 replacement_field: "{" [`field_name`] ["!" `conversion`] [":" `format_spec`] "}"
Eric Smith4c074382009-04-22 00:47:00 +0000229 field_name: arg_name ("." `attribute_name` | "[" `element_index` "]")*
Georg Brandl817d9182010-06-27 10:49:23 +0000230 arg_name: [`identifier` | `integer`]
Georg Brandle321c2f2008-05-12 16:45:43 +0000231 attribute_name: `identifier`
Eric Smith271b7e12010-02-25 14:26:33 +0000232 element_index: `integer` | `index_string`
233 index_string: <any source character except "]"> +
Georg Brandle321c2f2008-05-12 16:45:43 +0000234 conversion: "r" | "s"
235 format_spec: <described in the next section>
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000236
Georg Brandl254c17c2009-09-01 07:40:54 +0000237In less formal terms, the replacement field can start with a *field_name* that specifies
Eric Smith4c074382009-04-22 00:47:00 +0000238the object whose value is to be formatted and inserted
239into the output instead of the replacement field.
240The *field_name* is optionally followed by a *conversion* field, which is
Georg Brandle321c2f2008-05-12 16:45:43 +0000241preceded by an exclamation point ``'!'``, and a *format_spec*, which is preceded
Eric Smith4c074382009-04-22 00:47:00 +0000242by a colon ``':'``. These specify a non-default format for the replacement value.
Georg Brandle321c2f2008-05-12 16:45:43 +0000243
Ezio Melottie11690a2010-07-02 22:17:29 +0000244See also the :ref:`formatspec` section.
245
Eric Smith4c074382009-04-22 00:47:00 +0000246The *field_name* itself begins with an *arg_name* that is either either a number or a
247keyword. If it's a number, it refers to a positional argument, and if it's a keyword,
248it refers to a named keyword argument. If the numerical arg_names in a format string
249are 0, 1, 2, ... in sequence, they can all be omitted (not just some)
250and the numbers 0, 1, 2, ... will be automatically inserted in that order.
251The *arg_name* can be followed by any number of index or
Georg Brandle321c2f2008-05-12 16:45:43 +0000252attribute expressions. An expression of the form ``'.name'`` selects the named
253attribute using :func:`getattr`, while an expression of the form ``'[index]'``
254does an index lookup using :func:`__getitem__`.
255
Ezio Melottie11690a2010-07-02 22:17:29 +0000256.. versionchanged:: 2.7
257 The positional argument specifiers can be omitted, so ``'{} {}'`` is
258 equivalent to ``'{0} {1}'``.
259
Georg Brandle321c2f2008-05-12 16:45:43 +0000260Some simple format string examples::
261
262 "First, thou shalt count to {0}" # References first positional argument
Benjamin Peterson0e928582009-03-28 19:16:10 +0000263 "Bring me a {}" # Implicitly references the first positional argument
Georg Brandl254c17c2009-09-01 07:40:54 +0000264 "From {} to {}" # Same as "From {0} to {1}"
Georg Brandle321c2f2008-05-12 16:45:43 +0000265 "My quest is {name}" # References keyword argument 'name'
266 "Weight in tons {0.weight}" # 'weight' attribute of first positional arg
267 "Units destroyed: {players[0]}" # First element of keyword argument 'players'.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000268
Georg Brandle321c2f2008-05-12 16:45:43 +0000269The *conversion* field causes a type coercion before formatting. Normally, the
270job of formatting a value is done by the :meth:`__format__` method of the value
271itself. However, in some cases it is desirable to force a type to be formatted
272as a string, overriding its own definition of formatting. By converting the
273value to a string before calling :meth:`__format__`, the normal formatting logic
274is bypassed.
275
276Two conversion flags are currently supported: ``'!s'`` which calls :func:`str`
277on the value, and ``'!r'`` which calls :func:`repr`.
278
279Some examples::
280
281 "Harold's a clever {0!s}" # Calls str() on the argument first
282 "Bring out the holy {name!r}" # Calls repr() on the argument first
283
284The *format_spec* field contains a specification of how the value should be
285presented, including such details as field width, alignment, padding, decimal
Eric Smithcef34092010-02-15 11:55:38 +0000286precision and so on. Each value type can define its own "formatting
Georg Brandle321c2f2008-05-12 16:45:43 +0000287mini-language" or interpretation of the *format_spec*.
288
289Most built-in types support a common formatting mini-language, which is
290described in the next section.
291
292A *format_spec* field can also include nested replacement fields within it.
293These nested replacement fields can contain only a field name; conversion flags
294and format specifications are not allowed. The replacement fields within the
295format_spec are substituted before the *format_spec* string is interpreted.
296This allows the formatting of a value to be dynamically specified.
297
Ezio Melottie11690a2010-07-02 22:17:29 +0000298See the :ref:`formatexamples` section for some examples.
Georg Brandle321c2f2008-05-12 16:45:43 +0000299
300
301.. _formatspec:
302
303Format Specification Mini-Language
304^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
305
306"Format specifications" are used within replacement fields contained within a
307format string to define how individual values are presented (see
Ezio Melottie11690a2010-07-02 22:17:29 +0000308:ref:`formatstrings`). They can also be passed directly to the built-in
Georg Brandle321c2f2008-05-12 16:45:43 +0000309:func:`format` function. Each formattable type may define how the format
310specification is to be interpreted.
311
312Most built-in types implement the following options for format specifications,
313although some of the formatting options are only supported by the numeric types.
314
Eric Smithde8b2ac2010-02-25 14:14:35 +0000315A general convention is that an empty format string (``""``) produces
316the same result as if you had called :func:`str` on the value. A
317non-empty format string typically modifies the result.
Georg Brandle321c2f2008-05-12 16:45:43 +0000318
319The general form of a *standard format specifier* is:
320
321.. productionlist:: sf
Andrew M. Kuchlingfa6a4272009-10-05 22:42:56 +0000322 format_spec: [[`fill`]`align`][`sign`][#][0][`width`][,][.`precision`][`type`]
Georg Brandle321c2f2008-05-12 16:45:43 +0000323 fill: <a character other than '}'>
324 align: "<" | ">" | "=" | "^"
325 sign: "+" | "-" | " "
326 width: `integer`
327 precision: `integer`
Eric Smithde8b2ac2010-02-25 14:14:35 +0000328 type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000329
Georg Brandl21946af2010-10-06 09:28:45 +0000330The *fill* character can be any character other than '{' or '}'. The presence
331of a fill character is signaled by the character following it, which must be
332one of the alignment options. If the second character of *format_spec* is not
333a valid alignment option, then it is assumed that both the fill character and
334the alignment option are absent.
Georg Brandle321c2f2008-05-12 16:45:43 +0000335
336The meaning of the various alignment options is as follows:
337
338 +---------+----------------------------------------------------------+
339 | Option | Meaning |
340 +=========+==========================================================+
341 | ``'<'`` | Forces the field to be left-aligned within the available |
Georg Brandl28046022011-02-25 11:01:04 +0000342 | | space (this is the default for most objects). |
Georg Brandle321c2f2008-05-12 16:45:43 +0000343 +---------+----------------------------------------------------------+
344 | ``'>'`` | Forces the field to be right-aligned within the |
Georg Brandl28046022011-02-25 11:01:04 +0000345 | | available space (this is the default for numbers). |
Georg Brandle321c2f2008-05-12 16:45:43 +0000346 +---------+----------------------------------------------------------+
347 | ``'='`` | Forces the padding to be placed after the sign (if any) |
348 | | but before the digits. This is used for printing fields |
349 | | in the form '+000000120'. This alignment option is only |
350 | | valid for numeric types. |
351 +---------+----------------------------------------------------------+
352 | ``'^'`` | Forces the field to be centered within the available |
353 | | space. |
354 +---------+----------------------------------------------------------+
355
356Note that unless a minimum field width is defined, the field width will always
357be the same size as the data to fill it, so that the alignment option has no
358meaning in this case.
359
360The *sign* option is only valid for number types, and can be one of the
361following:
362
363 +---------+----------------------------------------------------------+
364 | Option | Meaning |
365 +=========+==========================================================+
366 | ``'+'`` | indicates that a sign should be used for both |
367 | | positive as well as negative numbers. |
368 +---------+----------------------------------------------------------+
369 | ``'-'`` | indicates that a sign should be used only for negative |
370 | | numbers (this is the default behavior). |
371 +---------+----------------------------------------------------------+
372 | space | indicates that a leading space should be used on |
373 | | positive numbers, and a minus sign on negative numbers. |
374 +---------+----------------------------------------------------------+
375
Benjamin Petersonb535d322008-09-11 22:04:02 +0000376The ``'#'`` option is only valid for integers, and only for binary, octal, or
377hexadecimal output. If present, it specifies that the output will be prefixed
378by ``'0b'``, ``'0o'``, or ``'0x'``, respectively.
Eric Smitha5fa5a22008-07-16 00:11:49 +0000379
Andrew M. Kuchlingfa6a4272009-10-05 22:42:56 +0000380The ``','`` option signals the use of a comma for a thousands separator.
381For a locale aware separator, use the ``'n'`` integer presentation type
382instead.
383
Ezio Melottif5e81d62010-07-02 22:50:39 +0000384.. versionchanged:: 2.7
385 Added the ``','`` option (see also :pep:`378`).
386
Georg Brandle321c2f2008-05-12 16:45:43 +0000387*width* is a decimal integer defining the minimum field width. If not
388specified, then the field width will be determined by the content.
389
390If the *width* field is preceded by a zero (``'0'``) character, this enables
391zero-padding. This is equivalent to an *alignment* type of ``'='`` and a *fill*
392character of ``'0'``.
393
394The *precision* is a decimal number indicating how many digits should be
Georg Brandlbf899812008-07-18 11:15:06 +0000395displayed after the decimal point for a floating point value formatted with
396``'f'`` and ``'F'``, or before and after the decimal point for a floating point
397value formatted with ``'g'`` or ``'G'``. For non-number types the field
398indicates the maximum field size - in other words, how many characters will be
Eric Smith75232342009-05-07 19:36:09 +0000399used from the field content. The *precision* is not allowed for integer values.
Georg Brandle321c2f2008-05-12 16:45:43 +0000400
401Finally, the *type* determines how the data should be presented.
402
Eric Smithde8b2ac2010-02-25 14:14:35 +0000403The available string presentation types are:
404
405 +---------+----------------------------------------------------------+
406 | Type | Meaning |
407 +=========+==========================================================+
408 | ``'s'`` | String format. This is the default type for strings and |
409 | | may be omitted. |
410 +---------+----------------------------------------------------------+
411 | None | The same as ``'s'``. |
412 +---------+----------------------------------------------------------+
413
Georg Brandle321c2f2008-05-12 16:45:43 +0000414The available integer presentation types are:
415
416 +---------+----------------------------------------------------------+
417 | Type | Meaning |
418 +=========+==========================================================+
Eric Smitha5fa5a22008-07-16 00:11:49 +0000419 | ``'b'`` | Binary format. Outputs the number in base 2. |
Georg Brandle321c2f2008-05-12 16:45:43 +0000420 +---------+----------------------------------------------------------+
421 | ``'c'`` | Character. Converts the integer to the corresponding |
422 | | unicode character before printing. |
423 +---------+----------------------------------------------------------+
424 | ``'d'`` | Decimal Integer. Outputs the number in base 10. |
425 +---------+----------------------------------------------------------+
426 | ``'o'`` | Octal format. Outputs the number in base 8. |
427 +---------+----------------------------------------------------------+
428 | ``'x'`` | Hex format. Outputs the number in base 16, using lower- |
429 | | case letters for the digits above 9. |
430 +---------+----------------------------------------------------------+
431 | ``'X'`` | Hex format. Outputs the number in base 16, using upper- |
432 | | case letters for the digits above 9. |
433 +---------+----------------------------------------------------------+
434 | ``'n'`` | Number. This is the same as ``'d'``, except that it uses |
435 | | the current locale setting to insert the appropriate |
436 | | number separator characters. |
437 +---------+----------------------------------------------------------+
Georg Brandlbf899812008-07-18 11:15:06 +0000438 | None | The same as ``'d'``. |
Georg Brandle321c2f2008-05-12 16:45:43 +0000439 +---------+----------------------------------------------------------+
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000440
Eric Smithde8b2ac2010-02-25 14:14:35 +0000441In addition to the above presentation types, integers can be formatted
442with the floating point presentation types listed below (except
443``'n'`` and None). When doing so, :func:`float` is used to convert the
444integer to a floating point number before formatting.
445
Georg Brandle321c2f2008-05-12 16:45:43 +0000446The available presentation types for floating point and decimal values are:
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000447
Georg Brandle321c2f2008-05-12 16:45:43 +0000448 +---------+----------------------------------------------------------+
449 | Type | Meaning |
450 +=========+==========================================================+
451 | ``'e'`` | Exponent notation. Prints the number in scientific |
452 | | notation using the letter 'e' to indicate the exponent. |
453 +---------+----------------------------------------------------------+
Eric Smithd6c393a2008-07-17 19:49:47 +0000454 | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an |
455 | | upper case 'E' as the separator character. |
Georg Brandle321c2f2008-05-12 16:45:43 +0000456 +---------+----------------------------------------------------------+
457 | ``'f'`` | Fixed point. Displays the number as a fixed-point |
458 | | number. |
459 +---------+----------------------------------------------------------+
Eric Smithd6c393a2008-07-17 19:49:47 +0000460 | ``'F'`` | Fixed point. Same as ``'f'``. |
Georg Brandle321c2f2008-05-12 16:45:43 +0000461 +---------+----------------------------------------------------------+
Mark Dickinsond5a713e2009-10-08 20:02:25 +0000462 | ``'g'`` | General format. For a given precision ``p >= 1``, |
463 | | this rounds the number to ``p`` significant digits and |
464 | | then formats the result in either fixed-point format |
465 | | or in scientific notation, depending on its magnitude. |
466 | | |
467 | | The precise rules are as follows: suppose that the |
468 | | result formatted with presentation type ``'e'`` and |
469 | | precision ``p-1`` would have exponent ``exp``. Then |
470 | | if ``-4 <= exp < p``, the number is formatted |
471 | | with presentation type ``'f'`` and precision |
472 | | ``p-1-exp``. Otherwise, the number is formatted |
473 | | with presentation type ``'e'`` and precision ``p-1``. |
474 | | In both cases insignificant trailing zeros are removed |
475 | | from the significand, and the decimal point is also |
476 | | removed if there are no remaining digits following it. |
477 | | |
Benjamin Peterson1e1a8c72010-10-12 23:12:45 +0000478 | | Positive and negative infinity, positive and negative |
Mark Dickinsond5a713e2009-10-08 20:02:25 +0000479 | | zero, and nans, are formatted as ``inf``, ``-inf``, |
480 | | ``0``, ``-0`` and ``nan`` respectively, regardless of |
481 | | the precision. |
482 | | |
483 | | A precision of ``0`` is treated as equivalent to a |
484 | | precision of ``1``. |
Georg Brandle321c2f2008-05-12 16:45:43 +0000485 +---------+----------------------------------------------------------+
486 | ``'G'`` | General format. Same as ``'g'`` except switches to |
Mark Dickinsond5a713e2009-10-08 20:02:25 +0000487 | | ``'E'`` if the number gets too large. The |
488 | | representations of infinity and NaN are uppercased, too. |
Georg Brandle321c2f2008-05-12 16:45:43 +0000489 +---------+----------------------------------------------------------+
490 | ``'n'`` | Number. This is the same as ``'g'``, except that it uses |
491 | | the current locale setting to insert the appropriate |
492 | | number separator characters. |
493 +---------+----------------------------------------------------------+
494 | ``'%'`` | Percentage. Multiplies the number by 100 and displays |
495 | | in fixed (``'f'``) format, followed by a percent sign. |
496 +---------+----------------------------------------------------------+
Georg Brandlbf899812008-07-18 11:15:06 +0000497 | None | The same as ``'g'``. |
Georg Brandle321c2f2008-05-12 16:45:43 +0000498 +---------+----------------------------------------------------------+
499
500
Ezio Melottie11690a2010-07-02 22:17:29 +0000501
502.. _formatexamples:
503
504Format examples
505^^^^^^^^^^^^^^^
506
507This section contains examples of the new format syntax and comparison with
508the old ``%``-formatting.
509
510In most of the cases the syntax is similar to the old ``%``-formatting, with the
511addition of the ``{}`` and with ``:`` used instead of ``%``.
512For example, ``'%03.2f'`` can be translated to ``'{:03.2f}'``.
513
514The new format syntax also supports new and different options, shown in the
515follow examples.
516
517Accessing arguments by position::
518
519 >>> '{0}, {1}, {2}'.format('a', 'b', 'c')
520 'a, b, c'
521 >>> '{}, {}, {}'.format('a', 'b', 'c') # 2.7+ only
522 'a, b, c'
523 >>> '{2}, {1}, {0}'.format('a', 'b', 'c')
524 'c, b, a'
525 >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence
526 'c, b, a'
527 >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated
528 'abracadabra'
529
530Accessing arguments by name::
531
532 >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
533 'Coordinates: 37.24N, -115.81W'
534 >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
535 >>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
536 'Coordinates: 37.24N, -115.81W'
537
538Accessing arguments' attributes::
539
Ezio Melottif5e81d62010-07-02 22:50:39 +0000540 >>> c = 3-5j
Ezio Melottie11690a2010-07-02 22:17:29 +0000541 >>> ('The complex number {0} is formed from the real part {0.real} '
542 ... 'and the imaginary part {0.imag}.').format(c)
543 'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
544 >>> class Point(object):
545 ... def __init__(self, x, y):
546 ... self.x, self.y = x, y
547 ... def __str__(self):
548 ... return 'Point({self.x}, {self.y})'.format(self=self)
549 ...
550 >>> str(Point(4, 2))
551 'Point(4, 2)'
552
553
554Accessing arguments' items::
555
556 >>> coord = (3, 5)
557 >>> 'X: {0[0]}; Y: {0[1]}'.format(coord)
558 'X: 3; Y: 5'
559
560Replacing ``%s`` and ``%r``::
561
562 >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
563 "repr() shows quotes: 'test1'; str() doesn't: test2"
564
565Aligning the text and specifying a width::
566
567 >>> '{:<30}'.format('left aligned')
568 'left aligned '
569 >>> '{:>30}'.format('right aligned')
570 ' right aligned'
571 >>> '{:^30}'.format('centered')
572 ' centered '
573 >>> '{:*^30}'.format('centered') # use '*' as a fill char
574 '***********centered***********'
575
576Replacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign::
577
578 >>> '{:+f}; {:+f}'.format(3.14, -3.14) # show it always
579 '+3.140000; -3.140000'
580 >>> '{: f}; {: f}'.format(3.14, -3.14) # show a space for positive numbers
581 ' 3.140000; -3.140000'
582 >>> '{:-f}; {:-f}'.format(3.14, -3.14) # show only the minus -- same as '{:f}; {:f}'
583 '3.140000; -3.140000'
584
585Replacing ``%x`` and ``%o`` and converting the value to different bases::
586
587 >>> # format also supports binary numbers
588 >>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
589 'int: 42; hex: 2a; oct: 52; bin: 101010'
590 >>> # with 0x, 0o, or 0b as prefix:
591 >>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
592 'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
593
594Using the comma as a thousands separator::
595
596 >>> '{:,}'.format(1234567890)
597 '1,234,567,890'
598
599Expressing a percentage::
600
601 >>> points = 19.5
602 >>> total = 22
603 >>> 'Correct answers: {:.2%}.'.format(points/total)
604 'Correct answers: 88.64%'
605
606Using type-specific formatting::
607
608 >>> import datetime
609 >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
610 >>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
611 '2010-07-04 12:15:58'
612
613Nesting arguments and more complex examples::
614
615 >>> for align, text in zip('<^>', ['left', 'center', 'right']):
Georg Brandl28046022011-02-25 11:01:04 +0000616 ... '{0:{fill}{align}16}'.format(text, fill=align, align=align)
Ezio Melottie11690a2010-07-02 22:17:29 +0000617 ...
618 'left<<<<<<<<<<<<'
619 '^^^^^center^^^^^'
620 '>>>>>>>>>>>right'
621 >>>
622 >>> octets = [192, 168, 0, 1]
623 >>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
624 'C0A80001'
625 >>> int(_, 16)
626 3232235521
627 >>>
628 >>> width = 5
629 >>> for num in range(5,12):
630 ... for base in 'dXob':
631 ... print '{0:{width}{base}}'.format(num, base=base, width=width),
632 ... print
633 ...
634 5 5 5 101
635 6 6 6 110
636 7 7 7 111
637 8 8 10 1000
638 9 9 11 1001
639 10 A 12 1010
640 11 B 13 1011
641
642
643
Georg Brandl8ec7f652007-08-15 14:28:01 +0000644Template strings
645----------------
646
Georg Brandl8b10f132009-12-19 17:30:28 +0000647.. versionadded:: 2.4
648
Georg Brandl8ec7f652007-08-15 14:28:01 +0000649Templates provide simpler string substitutions as described in :pep:`292`.
650Instead of the normal ``%``\ -based substitutions, Templates support ``$``\
651-based substitutions, using the following rules:
652
653* ``$$`` is an escape; it is replaced with a single ``$``.
654
655* ``$identifier`` names a substitution placeholder matching a mapping key of
656 ``"identifier"``. By default, ``"identifier"`` must spell a Python
657 identifier. The first non-identifier character after the ``$`` character
658 terminates this placeholder specification.
659
660* ``${identifier}`` is equivalent to ``$identifier``. It is required when valid
661 identifier characters follow the placeholder but are not part of the
662 placeholder, such as ``"${noun}ification"``.
663
664Any other appearance of ``$`` in the string will result in a :exc:`ValueError`
665being raised.
666
Georg Brandl8ec7f652007-08-15 14:28:01 +0000667The :mod:`string` module provides a :class:`Template` class that implements
668these rules. The methods of :class:`Template` are:
669
670
671.. class:: Template(template)
672
673 The constructor takes a single argument which is the template string.
674
675
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000676 .. method:: substitute(mapping[, **kws])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000677
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000678 Performs the template substitution, returning a new string. *mapping* is
679 any dictionary-like object with keys that match the placeholders in the
680 template. Alternatively, you can provide keyword arguments, where the
681 keywords are the placeholders. When both *mapping* and *kws* are given
682 and there are duplicates, the placeholders from *kws* take precedence.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000683
684
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000685 .. method:: safe_substitute(mapping[, **kws])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000686
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000687 Like :meth:`substitute`, except that if placeholders are missing from
688 *mapping* and *kws*, instead of raising a :exc:`KeyError` exception, the
689 original placeholder will appear in the resulting string intact. Also,
690 unlike with :meth:`substitute`, any other appearances of the ``$`` will
691 simply return ``$`` instead of raising :exc:`ValueError`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000692
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000693 While other exceptions may still occur, this method is called "safe"
694 because substitutions always tries to return a usable string instead of
695 raising an exception. In another sense, :meth:`safe_substitute` may be
696 anything other than safe, since it will silently ignore malformed
697 templates containing dangling delimiters, unmatched braces, or
698 placeholders that are not valid Python identifiers.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000699
Georg Brandl1136ff52009-11-18 20:05:15 +0000700 :class:`Template` instances also provide one public data attribute:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000701
Georg Brandl1136ff52009-11-18 20:05:15 +0000702 .. attribute:: template
Georg Brandl8ec7f652007-08-15 14:28:01 +0000703
Georg Brandl1136ff52009-11-18 20:05:15 +0000704 This is the object passed to the constructor's *template* argument. In
705 general, you shouldn't change it, but read-only access is not enforced.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000706
Georg Brandle8f1b002008-03-22 22:04:10 +0000707Here is an example of how to use a Template:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000708
709 >>> from string import Template
710 >>> s = Template('$who likes $what')
711 >>> s.substitute(who='tim', what='kung pao')
712 'tim likes kung pao'
713 >>> d = dict(who='tim')
714 >>> Template('Give $who $100').substitute(d)
715 Traceback (most recent call last):
716 [...]
717 ValueError: Invalid placeholder in string: line 1, col 10
718 >>> Template('$who likes $what').substitute(d)
719 Traceback (most recent call last):
720 [...]
721 KeyError: 'what'
722 >>> Template('$who likes $what').safe_substitute(d)
723 'tim likes $what'
724
725Advanced usage: you can derive subclasses of :class:`Template` to customize the
726placeholder syntax, delimiter character, or the entire regular expression used
727to parse template strings. To do this, you can override these class attributes:
728
729* *delimiter* -- This is the literal string describing a placeholder introducing
Eli Benderskye11af592011-08-06 09:29:12 +0300730 delimiter. The default value is ``$``. Note that this should *not* be a
731 regular expression, as the implementation will call :meth:`re.escape` on this
732 string as needed.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000733
734* *idpattern* -- This is the regular expression describing the pattern for
735 non-braced placeholders (the braces will be added automatically as
736 appropriate). The default value is the regular expression
737 ``[_a-z][_a-z0-9]*``.
738
739Alternatively, you can provide the entire regular expression pattern by
740overriding the class attribute *pattern*. If you do this, the value must be a
741regular expression object with four named capturing groups. The capturing
742groups correspond to the rules given above, along with the invalid placeholder
743rule:
744
745* *escaped* -- This group matches the escape sequence, e.g. ``$$``, in the
746 default pattern.
747
748* *named* -- This group matches the unbraced placeholder name; it should not
749 include the delimiter in capturing group.
750
751* *braced* -- This group matches the brace enclosed placeholder name; it should
752 not include either the delimiter or braces in the capturing group.
753
754* *invalid* -- This group matches any other delimiter pattern (usually a single
755 delimiter), and it should appear last in the regular expression.
756
757
758String functions
759----------------
760
761The following functions are available to operate on string and Unicode objects.
762They are not available as string methods.
763
764
Ezio Melotti9aac2452009-09-26 11:20:53 +0000765.. function:: capwords(s[, sep])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000766
Ezio Melotti9aac2452009-09-26 11:20:53 +0000767 Split the argument into words using :meth:`str.split`, capitalize each word
768 using :meth:`str.capitalize`, and join the capitalized words using
769 :meth:`str.join`. If the optional second argument *sep* is absent
770 or ``None``, runs of whitespace characters are replaced by a single space
771 and leading and trailing whitespace are removed, otherwise *sep* is used to
772 split and join the words.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000773
774
775.. function:: maketrans(from, to)
776
777 Return a translation table suitable for passing to :func:`translate`, that will
778 map each character in *from* into the character at the same position in *to*;
779 *from* and *to* must have the same length.
780
Georg Brandl16a57f62009-04-27 15:29:09 +0000781 .. note::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000782
783 Don't use strings derived from :const:`lowercase` and :const:`uppercase` as
784 arguments; in some locales, these don't have the same length. For case
Georg Brandld5ad6da2009-03-04 18:24:41 +0000785 conversions, always use :meth:`str.lower` and :meth:`str.upper`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000786
787
788Deprecated string functions
789---------------------------
790
791The following list of functions are also defined as methods of string and
792Unicode objects; see section :ref:`string-methods` for more information on
793those. You should consider these functions as deprecated, although they will
794not be removed until Python 3.0. The functions defined in this module are:
795
796
797.. function:: atof(s)
798
799 .. deprecated:: 2.0
800 Use the :func:`float` built-in function.
801
802 .. index:: builtin: float
803
804 Convert a string to a floating point number. The string must have the standard
805 syntax for a floating point literal in Python, optionally preceded by a sign
806 (``+`` or ``-``). Note that this behaves identical to the built-in function
807 :func:`float` when passed a string.
808
809 .. note::
810
811 .. index::
812 single: NaN
813 single: Infinity
814
815 When passing in a string, values for NaN and Infinity may be returned, depending
816 on the underlying C library. The specific set of strings accepted which cause
817 these values to be returned depends entirely on the C library and is known to
818 vary.
819
820
821.. function:: atoi(s[, base])
822
823 .. deprecated:: 2.0
824 Use the :func:`int` built-in function.
825
826 .. index:: builtin: eval
827
828 Convert string *s* to an integer in the given *base*. The string must consist
829 of one or more digits, optionally preceded by a sign (``+`` or ``-``). The
830 *base* defaults to 10. If it is 0, a default base is chosen depending on the
831 leading characters of the string (after stripping the sign): ``0x`` or ``0X``
832 means 16, ``0`` means 8, anything else means 10. If *base* is 16, a leading
833 ``0x`` or ``0X`` is always accepted, though not required. This behaves
834 identically to the built-in function :func:`int` when passed a string. (Also
835 note: for a more flexible interpretation of numeric literals, use the built-in
836 function :func:`eval`.)
837
838
839.. function:: atol(s[, base])
840
841 .. deprecated:: 2.0
842 Use the :func:`long` built-in function.
843
844 .. index:: builtin: long
845
846 Convert string *s* to a long integer in the given *base*. The string must
847 consist of one or more digits, optionally preceded by a sign (``+`` or ``-``).
848 The *base* argument has the same meaning as for :func:`atoi`. A trailing ``l``
849 or ``L`` is not allowed, except if the base is 0. Note that when invoked
850 without *base* or with *base* set to 10, this behaves identical to the built-in
851 function :func:`long` when passed a string.
852
853
854.. function:: capitalize(word)
855
856 Return a copy of *word* with only its first character capitalized.
857
858
859.. function:: expandtabs(s[, tabsize])
860
861 Expand tabs in a string replacing them by one or more spaces, depending on the
862 current column and the given tab size. The column number is reset to zero after
863 each newline occurring in the string. This doesn't understand other non-printing
864 characters or escape sequences. The tab size defaults to 8.
865
866
867.. function:: find(s, sub[, start[,end]])
868
869 Return the lowest index in *s* where the substring *sub* is found such that
870 *sub* is wholly contained in ``s[start:end]``. Return ``-1`` on failure.
871 Defaults for *start* and *end* and interpretation of negative values is the same
872 as for slices.
873
874
875.. function:: rfind(s, sub[, start[, end]])
876
877 Like :func:`find` but find the highest index.
878
879
880.. function:: index(s, sub[, start[, end]])
881
882 Like :func:`find` but raise :exc:`ValueError` when the substring is not found.
883
884
885.. function:: rindex(s, sub[, start[, end]])
886
887 Like :func:`rfind` but raise :exc:`ValueError` when the substring is not found.
888
889
890.. function:: count(s, sub[, start[, end]])
891
892 Return the number of (non-overlapping) occurrences of substring *sub* in string
893 ``s[start:end]``. Defaults for *start* and *end* and interpretation of negative
894 values are the same as for slices.
895
896
897.. function:: lower(s)
898
899 Return a copy of *s*, but with upper case letters converted to lower case.
900
901
902.. function:: split(s[, sep[, maxsplit]])
903
904 Return a list of the words of the string *s*. If the optional second argument
905 *sep* is absent or ``None``, the words are separated by arbitrary strings of
906 whitespace characters (space, tab, newline, return, formfeed). If the second
907 argument *sep* is present and not ``None``, it specifies a string to be used as
908 the word separator. The returned list will then have one more item than the
909 number of non-overlapping occurrences of the separator in the string. The
910 optional third argument *maxsplit* defaults to 0. If it is nonzero, at most
911 *maxsplit* number of splits occur, and the remainder of the string is returned
912 as the final element of the list (thus, the list will have at most
913 ``maxsplit+1`` elements).
914
915 The behavior of split on an empty string depends on the value of *sep*. If *sep*
916 is not specified, or specified as ``None``, the result will be an empty list.
917 If *sep* is specified as any string, the result will be a list containing one
918 element which is an empty string.
919
920
921.. function:: rsplit(s[, sep[, maxsplit]])
922
923 Return a list of the words of the string *s*, scanning *s* from the end. To all
924 intents and purposes, the resulting list of words is the same as returned by
925 :func:`split`, except when the optional third argument *maxsplit* is explicitly
926 specified and nonzero. When *maxsplit* is nonzero, at most *maxsplit* number of
927 splits -- the *rightmost* ones -- occur, and the remainder of the string is
928 returned as the first element of the list (thus, the list will have at most
929 ``maxsplit+1`` elements).
930
931 .. versionadded:: 2.4
932
933
934.. function:: splitfields(s[, sep[, maxsplit]])
935
936 This function behaves identically to :func:`split`. (In the past, :func:`split`
937 was only used with one argument, while :func:`splitfields` was only used with
938 two arguments.)
939
940
941.. function:: join(words[, sep])
942
943 Concatenate a list or tuple of words with intervening occurrences of *sep*.
944 The default value for *sep* is a single space character. It is always true that
945 ``string.join(string.split(s, sep), sep)`` equals *s*.
946
947
948.. function:: joinfields(words[, sep])
949
950 This function behaves identically to :func:`join`. (In the past, :func:`join`
951 was only used with one argument, while :func:`joinfields` was only used with two
952 arguments.) Note that there is no :meth:`joinfields` method on string objects;
953 use the :meth:`join` method instead.
954
955
956.. function:: lstrip(s[, chars])
957
958 Return a copy of the string with leading characters removed. If *chars* is
959 omitted or ``None``, whitespace characters are removed. If given and not
960 ``None``, *chars* must be a string; the characters in the string will be
961 stripped from the beginning of the string this method is called on.
962
963 .. versionchanged:: 2.2.3
964 The *chars* parameter was added. The *chars* parameter cannot be passed in
965 earlier 2.2 versions.
966
967
968.. function:: rstrip(s[, chars])
969
970 Return a copy of the string with trailing characters removed. If *chars* is
971 omitted or ``None``, whitespace characters are removed. If given and not
972 ``None``, *chars* must be a string; the characters in the string will be
973 stripped from the end of the string this method is called on.
974
975 .. versionchanged:: 2.2.3
976 The *chars* parameter was added. The *chars* parameter cannot be passed in
977 earlier 2.2 versions.
978
979
980.. function:: strip(s[, chars])
981
982 Return a copy of the string with leading and trailing characters removed. If
983 *chars* is omitted or ``None``, whitespace characters are removed. If given and
984 not ``None``, *chars* must be a string; the characters in the string will be
985 stripped from the both ends of the string this method is called on.
986
987 .. versionchanged:: 2.2.3
988 The *chars* parameter was added. The *chars* parameter cannot be passed in
989 earlier 2.2 versions.
990
991
992.. function:: swapcase(s)
993
994 Return a copy of *s*, but with lower case letters converted to upper case and
995 vice versa.
996
997
998.. function:: translate(s, table[, deletechars])
999
1000 Delete all characters from *s* that are in *deletechars* (if present), and then
1001 translate the characters using *table*, which must be a 256-character string
1002 giving the translation for each character value, indexed by its ordinal. If
1003 *table* is ``None``, then only the character deletion step is performed.
1004
1005
1006.. function:: upper(s)
1007
1008 Return a copy of *s*, but with lower case letters converted to upper case.
1009
1010
Georg Brandl2cc39ad2009-06-08 16:03:41 +00001011.. function:: ljust(s, width[, fillchar])
1012 rjust(s, width[, fillchar])
1013 center(s, width[, fillchar])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001014
1015 These functions respectively left-justify, right-justify and center a string in
1016 a field of given width. They return a string that is at least *width*
Georg Brandl2cc39ad2009-06-08 16:03:41 +00001017 characters wide, created by padding the string *s* with the character *fillchar*
1018 (default is a space) until the given width on the right, left or both sides.
1019 The string is never truncated.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001020
1021
1022.. function:: zfill(s, width)
1023
1024 Pad a numeric string on the left with zero digits until the given width is
1025 reached. Strings starting with a sign are handled correctly.
1026
1027
1028.. function:: replace(str, old, new[, maxreplace])
1029
1030 Return a copy of string *str* with all occurrences of substring *old* replaced
1031 by *new*. If the optional argument *maxreplace* is given, the first
1032 *maxreplace* occurrences are replaced.
1033