blob: ea4b5dad7df7e49eaf114b50f4d2234aaa8d59e4 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`string` --- Common string operations
2==========================================
3
4.. module:: string
5 :synopsis: Common string operations.
6
7
8.. index:: module: re
9
Georg Brandl4b491312007-08-31 09:22:56 +000010The :mod:`string` module contains a number of useful constants and classes, as
11well as some deprecated legacy functions that are also available as methods on
12strings. In addition, Python's built-in string classes support the sequence type
13methods described in the :ref:`typesseq` section, and also the string-specific
14methods described in the :ref:`string-methods` section. To output formatted
15strings, see the :ref:`string-formatting` section. Also, see the :mod:`re`
16module for string functions based on regular expressions.
Georg Brandl116aa622007-08-15 14:28:22 +000017
18
19String constants
20----------------
21
22The constants defined in this module are:
23
24
25.. data:: ascii_letters
26
27 The concatenation of the :const:`ascii_lowercase` and :const:`ascii_uppercase`
28 constants described below. This value is not locale-dependent.
29
30
31.. data:: ascii_lowercase
32
33 The lowercase letters ``'abcdefghijklmnopqrstuvwxyz'``. This value is not
34 locale-dependent and will not change.
35
36
37.. data:: ascii_uppercase
38
39 The uppercase letters ``'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. This value is not
40 locale-dependent and will not change.
41
42
43.. data:: digits
44
45 The string ``'0123456789'``.
46
47
48.. data:: hexdigits
49
50 The string ``'0123456789abcdefABCDEF'``.
51
52
53.. data:: octdigits
54
55 The string ``'01234567'``.
56
57
58.. data:: punctuation
59
60 String of ASCII characters which are considered punctuation characters
61 in the ``C`` locale.
62
63
64.. data:: printable
65
66 String of ASCII characters which are considered printable. This is a
67 combination of :const:`digits`, :const:`ascii_letters`, :const:`punctuation`,
68 and :const:`whitespace`.
69
70
71.. data:: whitespace
72
Georg Brandl50767402008-11-22 08:31:09 +000073 A string containing all ASCII characters that are considered whitespace.
Georg Brandl116aa622007-08-15 14:28:22 +000074 This includes the characters space, tab, linefeed, return, formfeed, and
75 vertical tab.
76
77
Georg Brandl4b491312007-08-31 09:22:56 +000078.. _string-formatting:
79
80String Formatting
81-----------------
82
Benjamin Peterson50923f92008-05-25 19:45:17 +000083The built-in string class provides the ability to do complex variable
84substitutions and value formatting via the :func:`format` method described in
85:pep:`3101`. The :class:`Formatter` class in the :mod:`string` module allows
86you to create and customize your own string formatting behaviors using the same
87implementation as the built-in :meth:`format` method.
Georg Brandl4b491312007-08-31 09:22:56 +000088
Benjamin Peterson1baf4652009-12-31 03:11:23 +000089
Georg Brandl4b491312007-08-31 09:22:56 +000090.. class:: Formatter
91
92 The :class:`Formatter` class has the following public methods:
93
94 .. method:: format(format_string, *args, *kwargs)
95
96 :meth:`format` is the primary API method. It takes a format template
97 string, and an arbitrary set of positional and keyword argument.
98 :meth:`format` is just a wrapper that calls :meth:`vformat`.
99
100 .. method:: vformat(format_string, args, kwargs)
Georg Brandl48310cd2009-01-03 21:18:54 +0000101
Georg Brandl4b491312007-08-31 09:22:56 +0000102 This function does the actual work of formatting. It is exposed as a
103 separate function for cases where you want to pass in a predefined
104 dictionary of arguments, rather than unpacking and repacking the
105 dictionary as individual arguments using the ``*args`` and ``**kwds``
106 syntax. :meth:`vformat` does the work of breaking up the format template
107 string into character data and replacement fields. It calls the various
108 methods described below.
109
110 In addition, the :class:`Formatter` defines a number of methods that are
111 intended to be replaced by subclasses:
112
113 .. method:: parse(format_string)
Georg Brandl48310cd2009-01-03 21:18:54 +0000114
Georg Brandl4b491312007-08-31 09:22:56 +0000115 Loop over the format_string and return an iterable of tuples
116 (*literal_text*, *field_name*, *format_spec*, *conversion*). This is used
117 by :meth:`vformat` to break the string in to either literal text, or
118 replacement fields.
Georg Brandl48310cd2009-01-03 21:18:54 +0000119
Georg Brandl4b491312007-08-31 09:22:56 +0000120 The values in the tuple conceptually represent a span of literal text
121 followed by a single replacement field. If there is no literal text
122 (which can happen if two replacement fields occur consecutively), then
123 *literal_text* will be a zero-length string. If there is no replacement
124 field, then the values of *field_name*, *format_spec* and *conversion*
125 will be ``None``.
126
Eric Smith9d4ba392007-09-02 15:33:26 +0000127 .. method:: get_field(field_name, args, kwargs)
Georg Brandl4b491312007-08-31 09:22:56 +0000128
129 Given *field_name* as returned by :meth:`parse` (see above), convert it to
Georg Brandl7f13e6b2007-08-31 10:37:15 +0000130 an object to be formatted. Returns a tuple (obj, used_key). The default
131 version takes strings of the form defined in :pep:`3101`, such as
132 "0[name]" or "label.title". *args* and *kwargs* are as passed in to
133 :meth:`vformat`. The return value *used_key* has the same meaning as the
134 *key* parameter to :meth:`get_value`.
Georg Brandl4b491312007-08-31 09:22:56 +0000135
136 .. method:: get_value(key, args, kwargs)
Georg Brandl48310cd2009-01-03 21:18:54 +0000137
Georg Brandl4b491312007-08-31 09:22:56 +0000138 Retrieve a given field value. The *key* argument will be either an
139 integer or a string. If it is an integer, it represents the index of the
140 positional argument in *args*; if it is a string, then it represents a
141 named argument in *kwargs*.
142
143 The *args* parameter is set to the list of positional arguments to
144 :meth:`vformat`, and the *kwargs* parameter is set to the dictionary of
145 keyword arguments.
146
147 For compound field names, these functions are only called for the first
148 component of the field name; Subsequent components are handled through
149 normal attribute and indexing operations.
150
151 So for example, the field expression '0.name' would cause
152 :meth:`get_value` to be called with a *key* argument of 0. The ``name``
153 attribute will be looked up after :meth:`get_value` returns by calling the
154 built-in :func:`getattr` function.
155
156 If the index or keyword refers to an item that does not exist, then an
157 :exc:`IndexError` or :exc:`KeyError` should be raised.
158
159 .. method:: check_unused_args(used_args, args, kwargs)
160
161 Implement checking for unused arguments if desired. The arguments to this
162 function is the set of all argument keys that were actually referred to in
163 the format string (integers for positional arguments, and strings for
164 named arguments), and a reference to the *args* and *kwargs* that was
165 passed to vformat. The set of unused args can be calculated from these
166 parameters. :meth:`check_unused_args` is assumed to throw an exception if
167 the check fails.
168
169 .. method:: format_field(value, format_spec)
170
171 :meth:`format_field` simply calls the global :func:`format` built-in. The
172 method is provided so that subclasses can override it.
173
174 .. method:: convert_field(value, conversion)
Georg Brandl48310cd2009-01-03 21:18:54 +0000175
Georg Brandl4b491312007-08-31 09:22:56 +0000176 Converts the value (returned by :meth:`get_field`) given a conversion type
177 (as in the tuple returned by the :meth:`parse` method.) The default
178 version understands 'r' (repr) and 's' (str) conversion types.
179
Georg Brandl4b491312007-08-31 09:22:56 +0000180
181.. _formatstrings:
182
183Format String Syntax
184--------------------
185
186The :meth:`str.format` method and the :class:`Formatter` class share the same
187syntax for format strings (although in the case of :class:`Formatter`,
188subclasses can define their own format string syntax.)
189
190Format strings contain "replacement fields" surrounded by curly braces ``{}``.
191Anything that is not contained in braces is considered literal text, which is
192copied unchanged to the output. If you need to include a brace character in the
193literal text, it can be escaped by doubling: ``{{`` and ``}}``.
194
195The grammar for a replacement field is as follows:
196
197 .. productionlist:: sf
Georg Brandl2f3ed682009-09-01 07:42:40 +0000198 replacement_field: "{" [`field_name`] ["!" `conversion`] [":" `format_spec`] "}"
Eric Smithc4cae322009-04-22 00:53:01 +0000199 field_name: arg_name ("." `attribute_name` | "[" `element_index` "]")*
200 arg_name: (`identifier` | `integer`)?
Georg Brandl4b491312007-08-31 09:22:56 +0000201 attribute_name: `identifier`
Eric Smith2e9f2022010-02-25 14:58:13 +0000202 element_index: `integer` | `index_string`
203 index_string: <any source character except "]"> +
Benjamin Peterson065ba702008-11-09 01:43:02 +0000204 conversion: "r" | "s" | "a"
Georg Brandl4b491312007-08-31 09:22:56 +0000205 format_spec: <described in the next section>
Georg Brandl48310cd2009-01-03 21:18:54 +0000206
Georg Brandl2f3ed682009-09-01 07:42:40 +0000207In less formal terms, the replacement field can start with a *field_name* that specifies
Eric Smithc4cae322009-04-22 00:53:01 +0000208the object whose value is to be formatted and inserted
209into the output instead of the replacement field.
210The *field_name* is optionally followed by a *conversion* field, which is
Georg Brandl4b491312007-08-31 09:22:56 +0000211preceded by an exclamation point ``'!'``, and a *format_spec*, which is preceded
Eric Smithc4cae322009-04-22 00:53:01 +0000212by a colon ``':'``. These specify a non-default format for the replacement value.
Georg Brandl4b491312007-08-31 09:22:56 +0000213
Eric Smithc4cae322009-04-22 00:53:01 +0000214The *field_name* itself begins with an *arg_name* that is either either a number or a
215keyword. If it's a number, it refers to a positional argument, and if it's a keyword,
216it refers to a named keyword argument. If the numerical arg_names in a format string
217are 0, 1, 2, ... in sequence, they can all be omitted (not just some)
218and the numbers 0, 1, 2, ... will be automatically inserted in that order.
219The *arg_name* can be followed by any number of index or
Georg Brandl4b491312007-08-31 09:22:56 +0000220attribute expressions. An expression of the form ``'.name'`` selects the named
221attribute using :func:`getattr`, while an expression of the form ``'[index]'``
222does an index lookup using :func:`__getitem__`.
223
224Some simple format string examples::
225
226 "First, thou shalt count to {0}" # References first positional argument
Benjamin Peterson5879d412009-03-30 14:51:56 +0000227 "Bring me a {}" # Implicitly references the first positional argument
Georg Brandl2f3ed682009-09-01 07:42:40 +0000228 "From {} to {}" # Same as "From {0} to {1}"
Georg Brandl4b491312007-08-31 09:22:56 +0000229 "My quest is {name}" # References keyword argument 'name'
230 "Weight in tons {0.weight}" # 'weight' attribute of first positional arg
231 "Units destroyed: {players[0]}" # First element of keyword argument 'players'.
Georg Brandl48310cd2009-01-03 21:18:54 +0000232
Georg Brandl4b491312007-08-31 09:22:56 +0000233The *conversion* field causes a type coercion before formatting. Normally, the
234job of formatting a value is done by the :meth:`__format__` method of the value
235itself. However, in some cases it is desirable to force a type to be formatted
236as a string, overriding its own definition of formatting. By converting the
237value to a string before calling :meth:`__format__`, the normal formatting logic
238is bypassed.
239
Georg Brandl559e5d72008-06-11 18:37:52 +0000240Three conversion flags are currently supported: ``'!s'`` which calls :func:`str`
241on the value, ``'!r'`` which calls :func:`repr` and ``'!a'`` which calls
242:func:`ascii`.
Georg Brandl4b491312007-08-31 09:22:56 +0000243
244Some examples::
245
246 "Harold's a clever {0!s}" # Calls str() on the argument first
247 "Bring out the holy {name!r}" # Calls repr() on the argument first
Georg Brandl2f3ed682009-09-01 07:42:40 +0000248 "More {!a}" # Calls ascii() on the argument first
Georg Brandl4b491312007-08-31 09:22:56 +0000249
250The *format_spec* field contains a specification of how the value should be
251presented, including such details as field width, alignment, padding, decimal
Eric Smith0f7affe2010-02-15 11:57:31 +0000252precision and so on. Each value type can define its own "formatting
Georg Brandl4b491312007-08-31 09:22:56 +0000253mini-language" or interpretation of the *format_spec*.
254
255Most built-in types support a common formatting mini-language, which is
256described in the next section.
257
258A *format_spec* field can also include nested replacement fields within it.
259These nested replacement fields can contain only a field name; conversion flags
260and format specifications are not allowed. The replacement fields within the
261format_spec are substituted before the *format_spec* string is interpreted.
262This allows the formatting of a value to be dynamically specified.
263
264For example, suppose you wanted to have a replacement field whose field width is
265determined by another variable::
266
267 "A man with two {0:{1}}".format("noses", 10)
268
269This would first evaluate the inner replacement field, making the format string
270effectively::
271
272 "A man with two {0:10}"
273
274Then the outer replacement field would be evaluated, producing::
275
276 "noses "
Georg Brandl48310cd2009-01-03 21:18:54 +0000277
Georg Brandl2ee470f2008-07-16 12:55:28 +0000278Which is substituted into the string, yielding::
Georg Brandl48310cd2009-01-03 21:18:54 +0000279
Georg Brandl4b491312007-08-31 09:22:56 +0000280 "A man with two noses "
Georg Brandl48310cd2009-01-03 21:18:54 +0000281
Georg Brandl4b491312007-08-31 09:22:56 +0000282(The extra space is because we specified a field width of 10, and because left
283alignment is the default for strings.)
284
Georg Brandl4b491312007-08-31 09:22:56 +0000285
286.. _formatspec:
287
288Format Specification Mini-Language
289^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
290
291"Format specifications" are used within replacement fields contained within a
292format string to define how individual values are presented (see
Georg Brandl22b34312009-07-26 14:54:51 +0000293:ref:`formatstrings`.) They can also be passed directly to the built-in
Georg Brandl4b491312007-08-31 09:22:56 +0000294:func:`format` function. Each formattable type may define how the format
295specification is to be interpreted.
296
297Most built-in types implement the following options for format specifications,
298although some of the formatting options are only supported by the numeric types.
299
Eric Smith05c07742010-02-25 14:18:57 +0000300A general convention is that an empty format string (``""``) produces
301the same result as if you had called :func:`str` on the value. A
302non-empty format string typically modifies the result.
Georg Brandl4b491312007-08-31 09:22:56 +0000303
304The general form of a *standard format specifier* is:
305
306.. productionlist:: sf
Raymond Hettinger6db94702009-07-12 20:49:21 +0000307 format_spec: [[`fill`]`align`][`sign`][#][0][`width`][,][.`precision`][`type`]
Georg Brandl4b491312007-08-31 09:22:56 +0000308 fill: <a character other than '}'>
309 align: "<" | ">" | "=" | "^"
310 sign: "+" | "-" | " "
311 width: `integer`
312 precision: `integer`
Eric Smith05c07742010-02-25 14:18:57 +0000313 type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
Georg Brandl48310cd2009-01-03 21:18:54 +0000314
Georg Brandl4b491312007-08-31 09:22:56 +0000315The *fill* character can be any character other than '}' (which signifies the
316end of the field). The presence of a fill character is signaled by the *next*
317character, which must be one of the alignment options. If the second character
318of *format_spec* is not a valid alignment option, then it is assumed that both
319the fill character and the alignment option are absent.
320
321The meaning of the various alignment options is as follows:
322
323 +---------+----------------------------------------------------------+
324 | Option | Meaning |
325 +=========+==========================================================+
326 | ``'<'`` | Forces the field to be left-aligned within the available |
327 | | space (This is the default.) |
328 +---------+----------------------------------------------------------+
329 | ``'>'`` | Forces the field to be right-aligned within the |
330 | | available space. |
331 +---------+----------------------------------------------------------+
332 | ``'='`` | Forces the padding to be placed after the sign (if any) |
333 | | but before the digits. This is used for printing fields |
334 | | in the form '+000000120'. This alignment option is only |
335 | | valid for numeric types. |
336 +---------+----------------------------------------------------------+
337 | ``'^'`` | Forces the field to be centered within the available |
338 | | space. |
339 +---------+----------------------------------------------------------+
340
341Note that unless a minimum field width is defined, the field width will always
342be the same size as the data to fill it, so that the alignment option has no
343meaning in this case.
344
345The *sign* option is only valid for number types, and can be one of the
346following:
347
348 +---------+----------------------------------------------------------+
349 | Option | Meaning |
350 +=========+==========================================================+
351 | ``'+'`` | indicates that a sign should be used for both |
352 | | positive as well as negative numbers. |
353 +---------+----------------------------------------------------------+
354 | ``'-'`` | indicates that a sign should be used only for negative |
355 | | numbers (this is the default behavior). |
356 +---------+----------------------------------------------------------+
357 | space | indicates that a leading space should be used on |
358 | | positive numbers, and a minus sign on negative numbers. |
359 +---------+----------------------------------------------------------+
360
Benjamin Petersond7b03282008-09-13 15:58:53 +0000361The ``'#'`` option is only valid for integers, and only for binary, octal, or
362hexadecimal output. If present, it specifies that the output will be prefixed
363by ``'0b'``, ``'0o'``, or ``'0x'``, respectively.
Eric Smithd68af8f2008-07-16 00:15:35 +0000364
Raymond Hettinger6db94702009-07-12 20:49:21 +0000365The ``','`` option signals the use of a comma for a thousands separator.
366For a locale aware separator, use the ``'n'`` integer presentation type
367instead.
368
Georg Brandl4b491312007-08-31 09:22:56 +0000369*width* is a decimal integer defining the minimum field width. If not
370specified, then the field width will be determined by the content.
371
372If the *width* field is preceded by a zero (``'0'``) character, this enables
373zero-padding. This is equivalent to an *alignment* type of ``'='`` and a *fill*
374character of ``'0'``.
375
376The *precision* is a decimal number indicating how many digits should be
Georg Brandl3dbca812008-07-23 16:10:53 +0000377displayed after the decimal point for a floating point value formatted with
378``'f'`` and ``'F'``, or before and after the decimal point for a floating point
379value formatted with ``'g'`` or ``'G'``. For non-number types the field
380indicates the maximum field size - in other words, how many characters will be
Eric Smithe5fffc72009-05-07 19:38:09 +0000381used from the field content. The *precision* is not allowed for integer values.
Georg Brandl4b491312007-08-31 09:22:56 +0000382
383Finally, the *type* determines how the data should be presented.
384
Eric Smith05c07742010-02-25 14:18:57 +0000385The available string presentation types are:
386
387 +---------+----------------------------------------------------------+
388 | Type | Meaning |
389 +=========+==========================================================+
390 | ``'s'`` | String format. This is the default type for strings and |
391 | | may be omitted. |
392 +---------+----------------------------------------------------------+
393 | None | The same as ``'s'``. |
394 +---------+----------------------------------------------------------+
395
Georg Brandl4b491312007-08-31 09:22:56 +0000396The available integer presentation types are:
397
398 +---------+----------------------------------------------------------+
399 | Type | Meaning |
400 +=========+==========================================================+
Eric Smithd68af8f2008-07-16 00:15:35 +0000401 | ``'b'`` | Binary format. Outputs the number in base 2. |
Georg Brandl4b491312007-08-31 09:22:56 +0000402 +---------+----------------------------------------------------------+
403 | ``'c'`` | Character. Converts the integer to the corresponding |
404 | | unicode character before printing. |
405 +---------+----------------------------------------------------------+
406 | ``'d'`` | Decimal Integer. Outputs the number in base 10. |
407 +---------+----------------------------------------------------------+
408 | ``'o'`` | Octal format. Outputs the number in base 8. |
409 +---------+----------------------------------------------------------+
410 | ``'x'`` | Hex format. Outputs the number in base 16, using lower- |
411 | | case letters for the digits above 9. |
412 +---------+----------------------------------------------------------+
413 | ``'X'`` | Hex format. Outputs the number in base 16, using upper- |
414 | | case letters for the digits above 9. |
415 +---------+----------------------------------------------------------+
Eric Smith5e18a202008-05-12 10:01:24 +0000416 | ``'n'`` | Number. This is the same as ``'d'``, except that it uses |
417 | | the current locale setting to insert the appropriate |
418 | | number separator characters. |
419 +---------+----------------------------------------------------------+
Georg Brandl3dbca812008-07-23 16:10:53 +0000420 | None | The same as ``'d'``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000421 +---------+----------------------------------------------------------+
Georg Brandl48310cd2009-01-03 21:18:54 +0000422
Eric Smith05c07742010-02-25 14:18:57 +0000423In addition to the above presentation types, integers can be formatted
424with the floating point presentation types listed below (except
425``'n'`` and None). When doing so, :func:`float` is used to convert the
426integer to a floating point number before formatting.
427
Georg Brandl4b491312007-08-31 09:22:56 +0000428The available presentation types for floating point and decimal values are:
Georg Brandl48310cd2009-01-03 21:18:54 +0000429
Georg Brandl4b491312007-08-31 09:22:56 +0000430 +---------+----------------------------------------------------------+
431 | Type | Meaning |
432 +=========+==========================================================+
433 | ``'e'`` | Exponent notation. Prints the number in scientific |
434 | | notation using the letter 'e' to indicate the exponent. |
435 +---------+----------------------------------------------------------+
Eric Smith22b85b32008-07-17 19:18:29 +0000436 | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an |
437 | | upper case 'E' as the separator character. |
Georg Brandl4b491312007-08-31 09:22:56 +0000438 +---------+----------------------------------------------------------+
439 | ``'f'`` | Fixed point. Displays the number as a fixed-point |
440 | | number. |
441 +---------+----------------------------------------------------------+
Eric Smith741191f2009-05-06 13:08:15 +0000442 | ``'F'`` | Fixed point. Same as ``'f'``, but converts ``nan`` to |
443 | | ``NAN`` and ``inf`` to ``INF``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000444 +---------+----------------------------------------------------------+
Mark Dickinsonc70614f2009-10-08 20:05:48 +0000445 | ``'g'`` | General format. For a given precision ``p >= 1``, |
446 | | this rounds the number to ``p`` significant digits and |
447 | | then formats the result in either fixed-point format |
448 | | or in scientific notation, depending on its magnitude. |
449 | | |
450 | | The precise rules are as follows: suppose that the |
451 | | result formatted with presentation type ``'e'`` and |
452 | | precision ``p-1`` would have exponent ``exp``. Then |
453 | | if ``-4 <= exp < p``, the number is formatted |
454 | | with presentation type ``'f'`` and precision |
455 | | ``p-1-exp``. Otherwise, the number is formatted |
456 | | with presentation type ``'e'`` and precision ``p-1``. |
457 | | In both cases insignificant trailing zeros are removed |
458 | | from the significand, and the decimal point is also |
459 | | removed if there are no remaining digits following it. |
460 | | |
461 | | Postive and negative infinity, positive and negative |
462 | | zero, and nans, are formatted as ``inf``, ``-inf``, |
463 | | ``0``, ``-0`` and ``nan`` respectively, regardless of |
464 | | the precision. |
465 | | |
466 | | A precision of ``0`` is treated as equivalent to a |
467 | | precision of ``1``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000468 +---------+----------------------------------------------------------+
469 | ``'G'`` | General format. Same as ``'g'`` except switches to |
Mark Dickinsonc70614f2009-10-08 20:05:48 +0000470 | | ``'E'`` if the number gets too large. The |
471 | | representations of infinity and NaN are uppercased, too. |
Georg Brandl4b491312007-08-31 09:22:56 +0000472 +---------+----------------------------------------------------------+
473 | ``'n'`` | Number. This is the same as ``'g'``, except that it uses |
474 | | the current locale setting to insert the appropriate |
475 | | number separator characters. |
476 +---------+----------------------------------------------------------+
477 | ``'%'`` | Percentage. Multiplies the number by 100 and displays |
478 | | in fixed (``'f'``) format, followed by a percent sign. |
479 +---------+----------------------------------------------------------+
Eric Smith3bef15b2009-05-05 17:19:46 +0000480 | None | Similar to ``'g'``, except with at least one digit past |
481 | | the decimal point and a default precision of 12. This is |
482 | | intended to match :func:`str`, except you can add the |
483 | | other format modifiers. |
Georg Brandl4b491312007-08-31 09:22:56 +0000484 +---------+----------------------------------------------------------+
485
486
487.. _template-strings:
488
Georg Brandl116aa622007-08-15 14:28:22 +0000489Template strings
490----------------
491
492Templates provide simpler string substitutions as described in :pep:`292`.
493Instead of the normal ``%``\ -based substitutions, Templates support ``$``\
494-based substitutions, using the following rules:
495
496* ``$$`` is an escape; it is replaced with a single ``$``.
497
498* ``$identifier`` names a substitution placeholder matching a mapping key of
499 ``"identifier"``. By default, ``"identifier"`` must spell a Python
500 identifier. The first non-identifier character after the ``$`` character
501 terminates this placeholder specification.
502
503* ``${identifier}`` is equivalent to ``$identifier``. It is required when valid
504 identifier characters follow the placeholder but are not part of the
505 placeholder, such as ``"${noun}ification"``.
506
507Any other appearance of ``$`` in the string will result in a :exc:`ValueError`
508being raised.
509
Georg Brandl116aa622007-08-15 14:28:22 +0000510The :mod:`string` module provides a :class:`Template` class that implements
511these rules. The methods of :class:`Template` are:
512
513
514.. class:: Template(template)
515
516 The constructor takes a single argument which is the template string.
517
518
Georg Brandl7f01a132009-09-16 15:58:14 +0000519 .. method:: substitute(mapping, **kwds)
Georg Brandl116aa622007-08-15 14:28:22 +0000520
Benjamin Petersone41251e2008-04-25 01:59:09 +0000521 Performs the template substitution, returning a new string. *mapping* is
522 any dictionary-like object with keys that match the placeholders in the
523 template. Alternatively, you can provide keyword arguments, where the
Georg Brandl7f01a132009-09-16 15:58:14 +0000524 keywords are the placeholders. When both *mapping* and *kwds* are given
525 and there are duplicates, the placeholders from *kwds* take precedence.
Georg Brandl116aa622007-08-15 14:28:22 +0000526
527
Georg Brandl7f01a132009-09-16 15:58:14 +0000528 .. method:: safe_substitute(mapping, **kwds)
Georg Brandl116aa622007-08-15 14:28:22 +0000529
Benjamin Petersone41251e2008-04-25 01:59:09 +0000530 Like :meth:`substitute`, except that if placeholders are missing from
Georg Brandl7f01a132009-09-16 15:58:14 +0000531 *mapping* and *kwds*, instead of raising a :exc:`KeyError` exception, the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000532 original placeholder will appear in the resulting string intact. Also,
533 unlike with :meth:`substitute`, any other appearances of the ``$`` will
534 simply return ``$`` instead of raising :exc:`ValueError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000535
Benjamin Petersone41251e2008-04-25 01:59:09 +0000536 While other exceptions may still occur, this method is called "safe"
537 because substitutions always tries to return a usable string instead of
538 raising an exception. In another sense, :meth:`safe_substitute` may be
539 anything other than safe, since it will silently ignore malformed
540 templates containing dangling delimiters, unmatched braces, or
541 placeholders that are not valid Python identifiers.
Georg Brandl116aa622007-08-15 14:28:22 +0000542
Benjamin Peterson20211002009-11-25 18:34:42 +0000543 :class:`Template` instances also provide one public data attribute:
Georg Brandl116aa622007-08-15 14:28:22 +0000544
Benjamin Peterson20211002009-11-25 18:34:42 +0000545 .. attribute:: template
Georg Brandl116aa622007-08-15 14:28:22 +0000546
Benjamin Peterson20211002009-11-25 18:34:42 +0000547 This is the object passed to the constructor's *template* argument. In
548 general, you shouldn't change it, but read-only access is not enforced.
Georg Brandl116aa622007-08-15 14:28:22 +0000549
Christian Heimesfe337bf2008-03-23 21:54:12 +0000550Here is an example of how to use a Template:
Georg Brandl116aa622007-08-15 14:28:22 +0000551
552 >>> from string import Template
553 >>> s = Template('$who likes $what')
554 >>> s.substitute(who='tim', what='kung pao')
555 'tim likes kung pao'
556 >>> d = dict(who='tim')
557 >>> Template('Give $who $100').substitute(d)
558 Traceback (most recent call last):
559 [...]
560 ValueError: Invalid placeholder in string: line 1, col 10
561 >>> Template('$who likes $what').substitute(d)
562 Traceback (most recent call last):
563 [...]
564 KeyError: 'what'
565 >>> Template('$who likes $what').safe_substitute(d)
566 'tim likes $what'
567
568Advanced usage: you can derive subclasses of :class:`Template` to customize the
569placeholder syntax, delimiter character, or the entire regular expression used
570to parse template strings. To do this, you can override these class attributes:
571
572* *delimiter* -- This is the literal string describing a placeholder introducing
573 delimiter. The default value ``$``. Note that this should *not* be a regular
574 expression, as the implementation will call :meth:`re.escape` on this string as
575 needed.
576
577* *idpattern* -- This is the regular expression describing the pattern for
578 non-braced placeholders (the braces will be added automatically as
579 appropriate). The default value is the regular expression
580 ``[_a-z][_a-z0-9]*``.
581
582Alternatively, you can provide the entire regular expression pattern by
583overriding the class attribute *pattern*. If you do this, the value must be a
584regular expression object with four named capturing groups. The capturing
585groups correspond to the rules given above, along with the invalid placeholder
586rule:
587
588* *escaped* -- This group matches the escape sequence, e.g. ``$$``, in the
589 default pattern.
590
591* *named* -- This group matches the unbraced placeholder name; it should not
592 include the delimiter in capturing group.
593
594* *braced* -- This group matches the brace enclosed placeholder name; it should
595 not include either the delimiter or braces in the capturing group.
596
597* *invalid* -- This group matches any other delimiter pattern (usually a single
598 delimiter), and it should appear last in the regular expression.
599
600
Georg Brandlabc38772009-04-12 15:51:51 +0000601Helper functions
Georg Brandl116aa622007-08-15 14:28:22 +0000602----------------
603
Georg Brandl10430ad2009-09-26 20:59:11 +0000604.. function:: capwords(s, sep=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000605
Ezio Melottia40bdda2009-09-26 12:33:22 +0000606 Split the argument into words using :meth:`str.split`, capitalize each word
607 using :meth:`str.capitalize`, and join the capitalized words using
608 :meth:`str.join`. If the optional second argument *sep* is absent
609 or ``None``, runs of whitespace characters are replaced by a single space
610 and leading and trailing whitespace are removed, otherwise *sep* is used to
611 split and join the words.
Georg Brandl116aa622007-08-15 14:28:22 +0000612