blob: 1bdad616bd891f490b39b1709a266a6318e9b551 [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`
202 element_index: `integer`
Benjamin Peterson065ba702008-11-09 01:43:02 +0000203 conversion: "r" | "s" | "a"
Georg Brandl4b491312007-08-31 09:22:56 +0000204 format_spec: <described in the next section>
Georg Brandl48310cd2009-01-03 21:18:54 +0000205
Georg Brandl2f3ed682009-09-01 07:42:40 +0000206In less formal terms, the replacement field can start with a *field_name* that specifies
Eric Smithc4cae322009-04-22 00:53:01 +0000207the object whose value is to be formatted and inserted
208into the output instead of the replacement field.
209The *field_name* is optionally followed by a *conversion* field, which is
Georg Brandl4b491312007-08-31 09:22:56 +0000210preceded by an exclamation point ``'!'``, and a *format_spec*, which is preceded
Eric Smithc4cae322009-04-22 00:53:01 +0000211by a colon ``':'``. These specify a non-default format for the replacement value.
Georg Brandl4b491312007-08-31 09:22:56 +0000212
Eric Smithc4cae322009-04-22 00:53:01 +0000213The *field_name* itself begins with an *arg_name* that is either either a number or a
214keyword. If it's a number, it refers to a positional argument, and if it's a keyword,
215it refers to a named keyword argument. If the numerical arg_names in a format string
216are 0, 1, 2, ... in sequence, they can all be omitted (not just some)
217and the numbers 0, 1, 2, ... will be automatically inserted in that order.
218The *arg_name* can be followed by any number of index or
Georg Brandl4b491312007-08-31 09:22:56 +0000219attribute expressions. An expression of the form ``'.name'`` selects the named
220attribute using :func:`getattr`, while an expression of the form ``'[index]'``
221does an index lookup using :func:`__getitem__`.
222
223Some simple format string examples::
224
225 "First, thou shalt count to {0}" # References first positional argument
Benjamin Peterson5879d412009-03-30 14:51:56 +0000226 "Bring me a {}" # Implicitly references the first positional argument
Georg Brandl2f3ed682009-09-01 07:42:40 +0000227 "From {} to {}" # Same as "From {0} to {1}"
Georg Brandl4b491312007-08-31 09:22:56 +0000228 "My quest is {name}" # References keyword argument 'name'
229 "Weight in tons {0.weight}" # 'weight' attribute of first positional arg
230 "Units destroyed: {players[0]}" # First element of keyword argument 'players'.
Georg Brandl48310cd2009-01-03 21:18:54 +0000231
Georg Brandl4b491312007-08-31 09:22:56 +0000232The *conversion* field causes a type coercion before formatting. Normally, the
233job of formatting a value is done by the :meth:`__format__` method of the value
234itself. However, in some cases it is desirable to force a type to be formatted
235as a string, overriding its own definition of formatting. By converting the
236value to a string before calling :meth:`__format__`, the normal formatting logic
237is bypassed.
238
Georg Brandl559e5d72008-06-11 18:37:52 +0000239Three conversion flags are currently supported: ``'!s'`` which calls :func:`str`
240on the value, ``'!r'`` which calls :func:`repr` and ``'!a'`` which calls
241:func:`ascii`.
Georg Brandl4b491312007-08-31 09:22:56 +0000242
243Some examples::
244
245 "Harold's a clever {0!s}" # Calls str() on the argument first
246 "Bring out the holy {name!r}" # Calls repr() on the argument first
Georg Brandl2f3ed682009-09-01 07:42:40 +0000247 "More {!a}" # Calls ascii() on the argument first
Georg Brandl4b491312007-08-31 09:22:56 +0000248
249The *format_spec* field contains a specification of how the value should be
250presented, including such details as field width, alignment, padding, decimal
Eric Smith0f7affe2010-02-15 11:57:31 +0000251precision and so on. Each value type can define its own "formatting
Georg Brandl4b491312007-08-31 09:22:56 +0000252mini-language" or interpretation of the *format_spec*.
253
254Most built-in types support a common formatting mini-language, which is
255described in the next section.
256
257A *format_spec* field can also include nested replacement fields within it.
258These nested replacement fields can contain only a field name; conversion flags
259and format specifications are not allowed. The replacement fields within the
260format_spec are substituted before the *format_spec* string is interpreted.
261This allows the formatting of a value to be dynamically specified.
262
263For example, suppose you wanted to have a replacement field whose field width is
264determined by another variable::
265
266 "A man with two {0:{1}}".format("noses", 10)
267
268This would first evaluate the inner replacement field, making the format string
269effectively::
270
271 "A man with two {0:10}"
272
273Then the outer replacement field would be evaluated, producing::
274
275 "noses "
Georg Brandl48310cd2009-01-03 21:18:54 +0000276
Georg Brandl2ee470f2008-07-16 12:55:28 +0000277Which is substituted into the string, yielding::
Georg Brandl48310cd2009-01-03 21:18:54 +0000278
Georg Brandl4b491312007-08-31 09:22:56 +0000279 "A man with two noses "
Georg Brandl48310cd2009-01-03 21:18:54 +0000280
Georg Brandl4b491312007-08-31 09:22:56 +0000281(The extra space is because we specified a field width of 10, and because left
282alignment is the default for strings.)
283
Georg Brandl4b491312007-08-31 09:22:56 +0000284
285.. _formatspec:
286
287Format Specification Mini-Language
288^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
289
290"Format specifications" are used within replacement fields contained within a
291format string to define how individual values are presented (see
Georg Brandl22b34312009-07-26 14:54:51 +0000292:ref:`formatstrings`.) They can also be passed directly to the built-in
Georg Brandl4b491312007-08-31 09:22:56 +0000293:func:`format` function. Each formattable type may define how the format
294specification is to be interpreted.
295
296Most built-in types implement the following options for format specifications,
297although some of the formatting options are only supported by the numeric types.
298
299A general convention is that an empty format string (``""``) produces the same
Georg Brandl222e1272008-01-11 12:58:40 +0000300result as if you had called :func:`str` on the value.
Georg Brandl4b491312007-08-31 09:22:56 +0000301
302The general form of a *standard format specifier* is:
303
304.. productionlist:: sf
Raymond Hettinger6db94702009-07-12 20:49:21 +0000305 format_spec: [[`fill`]`align`][`sign`][#][0][`width`][,][.`precision`][`type`]
Georg Brandl4b491312007-08-31 09:22:56 +0000306 fill: <a character other than '}'>
307 align: "<" | ">" | "=" | "^"
308 sign: "+" | "-" | " "
309 width: `integer`
310 precision: `integer`
311 type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "x" | "X" | "%"
Georg Brandl48310cd2009-01-03 21:18:54 +0000312
Georg Brandl4b491312007-08-31 09:22:56 +0000313The *fill* character can be any character other than '}' (which signifies the
314end of the field). The presence of a fill character is signaled by the *next*
315character, which must be one of the alignment options. If the second character
316of *format_spec* is not a valid alignment option, then it is assumed that both
317the fill character and the alignment option are absent.
318
319The meaning of the various alignment options is as follows:
320
321 +---------+----------------------------------------------------------+
322 | Option | Meaning |
323 +=========+==========================================================+
324 | ``'<'`` | Forces the field to be left-aligned within the available |
325 | | space (This is the default.) |
326 +---------+----------------------------------------------------------+
327 | ``'>'`` | Forces the field to be right-aligned within the |
328 | | available space. |
329 +---------+----------------------------------------------------------+
330 | ``'='`` | Forces the padding to be placed after the sign (if any) |
331 | | but before the digits. This is used for printing fields |
332 | | in the form '+000000120'. This alignment option is only |
333 | | valid for numeric types. |
334 +---------+----------------------------------------------------------+
335 | ``'^'`` | Forces the field to be centered within the available |
336 | | space. |
337 +---------+----------------------------------------------------------+
338
339Note that unless a minimum field width is defined, the field width will always
340be the same size as the data to fill it, so that the alignment option has no
341meaning in this case.
342
343The *sign* option is only valid for number types, and can be one of the
344following:
345
346 +---------+----------------------------------------------------------+
347 | Option | Meaning |
348 +=========+==========================================================+
349 | ``'+'`` | indicates that a sign should be used for both |
350 | | positive as well as negative numbers. |
351 +---------+----------------------------------------------------------+
352 | ``'-'`` | indicates that a sign should be used only for negative |
353 | | numbers (this is the default behavior). |
354 +---------+----------------------------------------------------------+
355 | space | indicates that a leading space should be used on |
356 | | positive numbers, and a minus sign on negative numbers. |
357 +---------+----------------------------------------------------------+
358
Benjamin Petersond7b03282008-09-13 15:58:53 +0000359The ``'#'`` option is only valid for integers, and only for binary, octal, or
360hexadecimal output. If present, it specifies that the output will be prefixed
361by ``'0b'``, ``'0o'``, or ``'0x'``, respectively.
Eric Smithd68af8f2008-07-16 00:15:35 +0000362
Raymond Hettinger6db94702009-07-12 20:49:21 +0000363The ``','`` option signals the use of a comma for a thousands separator.
364For a locale aware separator, use the ``'n'`` integer presentation type
365instead.
366
Georg Brandl4b491312007-08-31 09:22:56 +0000367*width* is a decimal integer defining the minimum field width. If not
368specified, then the field width will be determined by the content.
369
370If the *width* field is preceded by a zero (``'0'``) character, this enables
371zero-padding. This is equivalent to an *alignment* type of ``'='`` and a *fill*
372character of ``'0'``.
373
374The *precision* is a decimal number indicating how many digits should be
Georg Brandl3dbca812008-07-23 16:10:53 +0000375displayed after the decimal point for a floating point value formatted with
376``'f'`` and ``'F'``, or before and after the decimal point for a floating point
377value formatted with ``'g'`` or ``'G'``. For non-number types the field
378indicates the maximum field size - in other words, how many characters will be
Eric Smithe5fffc72009-05-07 19:38:09 +0000379used from the field content. The *precision* is not allowed for integer values.
Georg Brandl4b491312007-08-31 09:22:56 +0000380
381Finally, the *type* determines how the data should be presented.
382
383The available integer presentation types are:
384
385 +---------+----------------------------------------------------------+
386 | Type | Meaning |
387 +=========+==========================================================+
Eric Smithd68af8f2008-07-16 00:15:35 +0000388 | ``'b'`` | Binary format. Outputs the number in base 2. |
Georg Brandl4b491312007-08-31 09:22:56 +0000389 +---------+----------------------------------------------------------+
390 | ``'c'`` | Character. Converts the integer to the corresponding |
391 | | unicode character before printing. |
392 +---------+----------------------------------------------------------+
393 | ``'d'`` | Decimal Integer. Outputs the number in base 10. |
394 +---------+----------------------------------------------------------+
395 | ``'o'`` | Octal format. Outputs the number in base 8. |
396 +---------+----------------------------------------------------------+
397 | ``'x'`` | Hex format. Outputs the number in base 16, using lower- |
398 | | case letters for the digits above 9. |
399 +---------+----------------------------------------------------------+
400 | ``'X'`` | Hex format. Outputs the number in base 16, using upper- |
401 | | case letters for the digits above 9. |
402 +---------+----------------------------------------------------------+
Eric Smith5e18a202008-05-12 10:01:24 +0000403 | ``'n'`` | Number. This is the same as ``'d'``, except that it uses |
404 | | the current locale setting to insert the appropriate |
405 | | number separator characters. |
406 +---------+----------------------------------------------------------+
Georg Brandl3dbca812008-07-23 16:10:53 +0000407 | None | The same as ``'d'``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000408 +---------+----------------------------------------------------------+
Georg Brandl48310cd2009-01-03 21:18:54 +0000409
Georg Brandl4b491312007-08-31 09:22:56 +0000410The available presentation types for floating point and decimal values are:
Georg Brandl48310cd2009-01-03 21:18:54 +0000411
Georg Brandl4b491312007-08-31 09:22:56 +0000412 +---------+----------------------------------------------------------+
413 | Type | Meaning |
414 +=========+==========================================================+
415 | ``'e'`` | Exponent notation. Prints the number in scientific |
416 | | notation using the letter 'e' to indicate the exponent. |
417 +---------+----------------------------------------------------------+
Eric Smith22b85b32008-07-17 19:18:29 +0000418 | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an |
419 | | upper case 'E' as the separator character. |
Georg Brandl4b491312007-08-31 09:22:56 +0000420 +---------+----------------------------------------------------------+
421 | ``'f'`` | Fixed point. Displays the number as a fixed-point |
422 | | number. |
423 +---------+----------------------------------------------------------+
Eric Smith741191f2009-05-06 13:08:15 +0000424 | ``'F'`` | Fixed point. Same as ``'f'``, but converts ``nan`` to |
425 | | ``NAN`` and ``inf`` to ``INF``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000426 +---------+----------------------------------------------------------+
Mark Dickinsonc70614f2009-10-08 20:05:48 +0000427 | ``'g'`` | General format. For a given precision ``p >= 1``, |
428 | | this rounds the number to ``p`` significant digits and |
429 | | then formats the result in either fixed-point format |
430 | | or in scientific notation, depending on its magnitude. |
431 | | |
432 | | The precise rules are as follows: suppose that the |
433 | | result formatted with presentation type ``'e'`` and |
434 | | precision ``p-1`` would have exponent ``exp``. Then |
435 | | if ``-4 <= exp < p``, the number is formatted |
436 | | with presentation type ``'f'`` and precision |
437 | | ``p-1-exp``. Otherwise, the number is formatted |
438 | | with presentation type ``'e'`` and precision ``p-1``. |
439 | | In both cases insignificant trailing zeros are removed |
440 | | from the significand, and the decimal point is also |
441 | | removed if there are no remaining digits following it. |
442 | | |
443 | | Postive and negative infinity, positive and negative |
444 | | zero, and nans, are formatted as ``inf``, ``-inf``, |
445 | | ``0``, ``-0`` and ``nan`` respectively, regardless of |
446 | | the precision. |
447 | | |
448 | | A precision of ``0`` is treated as equivalent to a |
449 | | precision of ``1``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000450 +---------+----------------------------------------------------------+
451 | ``'G'`` | General format. Same as ``'g'`` except switches to |
Mark Dickinsonc70614f2009-10-08 20:05:48 +0000452 | | ``'E'`` if the number gets too large. The |
453 | | representations of infinity and NaN are uppercased, too. |
Georg Brandl4b491312007-08-31 09:22:56 +0000454 +---------+----------------------------------------------------------+
455 | ``'n'`` | Number. This is the same as ``'g'``, except that it uses |
456 | | the current locale setting to insert the appropriate |
457 | | number separator characters. |
458 +---------+----------------------------------------------------------+
459 | ``'%'`` | Percentage. Multiplies the number by 100 and displays |
460 | | in fixed (``'f'``) format, followed by a percent sign. |
461 +---------+----------------------------------------------------------+
Eric Smith3bef15b2009-05-05 17:19:46 +0000462 | None | Similar to ``'g'``, except with at least one digit past |
463 | | the decimal point and a default precision of 12. This is |
464 | | intended to match :func:`str`, except you can add the |
465 | | other format modifiers. |
Georg Brandl4b491312007-08-31 09:22:56 +0000466 +---------+----------------------------------------------------------+
467
468
469.. _template-strings:
470
Georg Brandl116aa622007-08-15 14:28:22 +0000471Template strings
472----------------
473
474Templates provide simpler string substitutions as described in :pep:`292`.
475Instead of the normal ``%``\ -based substitutions, Templates support ``$``\
476-based substitutions, using the following rules:
477
478* ``$$`` is an escape; it is replaced with a single ``$``.
479
480* ``$identifier`` names a substitution placeholder matching a mapping key of
481 ``"identifier"``. By default, ``"identifier"`` must spell a Python
482 identifier. The first non-identifier character after the ``$`` character
483 terminates this placeholder specification.
484
485* ``${identifier}`` is equivalent to ``$identifier``. It is required when valid
486 identifier characters follow the placeholder but are not part of the
487 placeholder, such as ``"${noun}ification"``.
488
489Any other appearance of ``$`` in the string will result in a :exc:`ValueError`
490being raised.
491
Georg Brandl116aa622007-08-15 14:28:22 +0000492The :mod:`string` module provides a :class:`Template` class that implements
493these rules. The methods of :class:`Template` are:
494
495
496.. class:: Template(template)
497
498 The constructor takes a single argument which is the template string.
499
500
Georg Brandl7f01a132009-09-16 15:58:14 +0000501 .. method:: substitute(mapping, **kwds)
Georg Brandl116aa622007-08-15 14:28:22 +0000502
Benjamin Petersone41251e2008-04-25 01:59:09 +0000503 Performs the template substitution, returning a new string. *mapping* is
504 any dictionary-like object with keys that match the placeholders in the
505 template. Alternatively, you can provide keyword arguments, where the
Georg Brandl7f01a132009-09-16 15:58:14 +0000506 keywords are the placeholders. When both *mapping* and *kwds* are given
507 and there are duplicates, the placeholders from *kwds* take precedence.
Georg Brandl116aa622007-08-15 14:28:22 +0000508
509
Georg Brandl7f01a132009-09-16 15:58:14 +0000510 .. method:: safe_substitute(mapping, **kwds)
Georg Brandl116aa622007-08-15 14:28:22 +0000511
Benjamin Petersone41251e2008-04-25 01:59:09 +0000512 Like :meth:`substitute`, except that if placeholders are missing from
Georg Brandl7f01a132009-09-16 15:58:14 +0000513 *mapping* and *kwds*, instead of raising a :exc:`KeyError` exception, the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000514 original placeholder will appear in the resulting string intact. Also,
515 unlike with :meth:`substitute`, any other appearances of the ``$`` will
516 simply return ``$`` instead of raising :exc:`ValueError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000517
Benjamin Petersone41251e2008-04-25 01:59:09 +0000518 While other exceptions may still occur, this method is called "safe"
519 because substitutions always tries to return a usable string instead of
520 raising an exception. In another sense, :meth:`safe_substitute` may be
521 anything other than safe, since it will silently ignore malformed
522 templates containing dangling delimiters, unmatched braces, or
523 placeholders that are not valid Python identifiers.
Georg Brandl116aa622007-08-15 14:28:22 +0000524
Benjamin Peterson20211002009-11-25 18:34:42 +0000525 :class:`Template` instances also provide one public data attribute:
Georg Brandl116aa622007-08-15 14:28:22 +0000526
Benjamin Peterson20211002009-11-25 18:34:42 +0000527 .. attribute:: template
Georg Brandl116aa622007-08-15 14:28:22 +0000528
Benjamin Peterson20211002009-11-25 18:34:42 +0000529 This is the object passed to the constructor's *template* argument. In
530 general, you shouldn't change it, but read-only access is not enforced.
Georg Brandl116aa622007-08-15 14:28:22 +0000531
Christian Heimesfe337bf2008-03-23 21:54:12 +0000532Here is an example of how to use a Template:
Georg Brandl116aa622007-08-15 14:28:22 +0000533
534 >>> from string import Template
535 >>> s = Template('$who likes $what')
536 >>> s.substitute(who='tim', what='kung pao')
537 'tim likes kung pao'
538 >>> d = dict(who='tim')
539 >>> Template('Give $who $100').substitute(d)
540 Traceback (most recent call last):
541 [...]
542 ValueError: Invalid placeholder in string: line 1, col 10
543 >>> Template('$who likes $what').substitute(d)
544 Traceback (most recent call last):
545 [...]
546 KeyError: 'what'
547 >>> Template('$who likes $what').safe_substitute(d)
548 'tim likes $what'
549
550Advanced usage: you can derive subclasses of :class:`Template` to customize the
551placeholder syntax, delimiter character, or the entire regular expression used
552to parse template strings. To do this, you can override these class attributes:
553
554* *delimiter* -- This is the literal string describing a placeholder introducing
555 delimiter. The default value ``$``. Note that this should *not* be a regular
556 expression, as the implementation will call :meth:`re.escape` on this string as
557 needed.
558
559* *idpattern* -- This is the regular expression describing the pattern for
560 non-braced placeholders (the braces will be added automatically as
561 appropriate). The default value is the regular expression
562 ``[_a-z][_a-z0-9]*``.
563
564Alternatively, you can provide the entire regular expression pattern by
565overriding the class attribute *pattern*. If you do this, the value must be a
566regular expression object with four named capturing groups. The capturing
567groups correspond to the rules given above, along with the invalid placeholder
568rule:
569
570* *escaped* -- This group matches the escape sequence, e.g. ``$$``, in the
571 default pattern.
572
573* *named* -- This group matches the unbraced placeholder name; it should not
574 include the delimiter in capturing group.
575
576* *braced* -- This group matches the brace enclosed placeholder name; it should
577 not include either the delimiter or braces in the capturing group.
578
579* *invalid* -- This group matches any other delimiter pattern (usually a single
580 delimiter), and it should appear last in the regular expression.
581
582
Georg Brandlabc38772009-04-12 15:51:51 +0000583Helper functions
Georg Brandl116aa622007-08-15 14:28:22 +0000584----------------
585
Georg Brandl10430ad2009-09-26 20:59:11 +0000586.. function:: capwords(s, sep=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000587
Ezio Melottia40bdda2009-09-26 12:33:22 +0000588 Split the argument into words using :meth:`str.split`, capitalize each word
589 using :meth:`str.capitalize`, and join the capitalized words using
590 :meth:`str.join`. If the optional second argument *sep* is absent
591 or ``None``, runs of whitespace characters are replaced by a single space
592 and leading and trailing whitespace are removed, otherwise *sep* is used to
593 split and join the words.
Georg Brandl116aa622007-08-15 14:28:22 +0000594