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