blob: 759de42424ed65203cb905951b178f86ae8076a2 [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
89.. class:: Formatter
90
91 The :class:`Formatter` class has the following public methods:
92
93 .. method:: format(format_string, *args, *kwargs)
94
95 :meth:`format` is the primary API method. It takes a format template
96 string, and an arbitrary set of positional and keyword argument.
97 :meth:`format` is just a wrapper that calls :meth:`vformat`.
98
99 .. method:: vformat(format_string, args, kwargs)
Georg Brandl48310cd2009-01-03 21:18:54 +0000100
Georg Brandl4b491312007-08-31 09:22:56 +0000101 This function does the actual work of formatting. It is exposed as a
102 separate function for cases where you want to pass in a predefined
103 dictionary of arguments, rather than unpacking and repacking the
104 dictionary as individual arguments using the ``*args`` and ``**kwds``
105 syntax. :meth:`vformat` does the work of breaking up the format template
106 string into character data and replacement fields. It calls the various
107 methods described below.
108
109 In addition, the :class:`Formatter` defines a number of methods that are
110 intended to be replaced by subclasses:
111
112 .. method:: parse(format_string)
Georg Brandl48310cd2009-01-03 21:18:54 +0000113
Georg Brandl4b491312007-08-31 09:22:56 +0000114 Loop over the format_string and return an iterable of tuples
115 (*literal_text*, *field_name*, *format_spec*, *conversion*). This is used
116 by :meth:`vformat` to break the string in to either literal text, or
117 replacement fields.
Georg Brandl48310cd2009-01-03 21:18:54 +0000118
Georg Brandl4b491312007-08-31 09:22:56 +0000119 The values in the tuple conceptually represent a span of literal text
120 followed by a single replacement field. If there is no literal text
121 (which can happen if two replacement fields occur consecutively), then
122 *literal_text* will be a zero-length string. If there is no replacement
123 field, then the values of *field_name*, *format_spec* and *conversion*
124 will be ``None``.
125
Eric Smith9d4ba392007-09-02 15:33:26 +0000126 .. method:: get_field(field_name, args, kwargs)
Georg Brandl4b491312007-08-31 09:22:56 +0000127
128 Given *field_name* as returned by :meth:`parse` (see above), convert it to
Georg Brandl7f13e6b2007-08-31 10:37:15 +0000129 an object to be formatted. Returns a tuple (obj, used_key). The default
130 version takes strings of the form defined in :pep:`3101`, such as
131 "0[name]" or "label.title". *args* and *kwargs* are as passed in to
132 :meth:`vformat`. The return value *used_key* has the same meaning as the
133 *key* parameter to :meth:`get_value`.
Georg Brandl4b491312007-08-31 09:22:56 +0000134
135 .. method:: get_value(key, args, kwargs)
Georg Brandl48310cd2009-01-03 21:18:54 +0000136
Georg Brandl4b491312007-08-31 09:22:56 +0000137 Retrieve a given field value. The *key* argument will be either an
138 integer or a string. If it is an integer, it represents the index of the
139 positional argument in *args*; if it is a string, then it represents a
140 named argument in *kwargs*.
141
142 The *args* parameter is set to the list of positional arguments to
143 :meth:`vformat`, and the *kwargs* parameter is set to the dictionary of
144 keyword arguments.
145
146 For compound field names, these functions are only called for the first
147 component of the field name; Subsequent components are handled through
148 normal attribute and indexing operations.
149
150 So for example, the field expression '0.name' would cause
151 :meth:`get_value` to be called with a *key* argument of 0. The ``name``
152 attribute will be looked up after :meth:`get_value` returns by calling the
153 built-in :func:`getattr` function.
154
155 If the index or keyword refers to an item that does not exist, then an
156 :exc:`IndexError` or :exc:`KeyError` should be raised.
157
158 .. method:: check_unused_args(used_args, args, kwargs)
159
160 Implement checking for unused arguments if desired. The arguments to this
161 function is the set of all argument keys that were actually referred to in
162 the format string (integers for positional arguments, and strings for
163 named arguments), and a reference to the *args* and *kwargs* that was
164 passed to vformat. The set of unused args can be calculated from these
165 parameters. :meth:`check_unused_args` is assumed to throw an exception if
166 the check fails.
167
168 .. method:: format_field(value, format_spec)
169
170 :meth:`format_field` simply calls the global :func:`format` built-in. The
171 method is provided so that subclasses can override it.
172
173 .. method:: convert_field(value, conversion)
Georg Brandl48310cd2009-01-03 21:18:54 +0000174
Georg Brandl4b491312007-08-31 09:22:56 +0000175 Converts the value (returned by :meth:`get_field`) given a conversion type
176 (as in the tuple returned by the :meth:`parse` method.) The default
177 version understands 'r' (repr) and 's' (str) conversion types.
178
Georg Brandl4b491312007-08-31 09:22:56 +0000179
180.. _formatstrings:
181
182Format String Syntax
183--------------------
184
185The :meth:`str.format` method and the :class:`Formatter` class share the same
186syntax for format strings (although in the case of :class:`Formatter`,
187subclasses can define their own format string syntax.)
188
189Format strings contain "replacement fields" surrounded by curly braces ``{}``.
190Anything that is not contained in braces is considered literal text, which is
191copied unchanged to the output. If you need to include a brace character in the
192literal text, it can be escaped by doubling: ``{{`` and ``}}``.
193
194The grammar for a replacement field is as follows:
195
196 .. productionlist:: sf
Georg Brandl2f3ed682009-09-01 07:42:40 +0000197 replacement_field: "{" [`field_name`] ["!" `conversion`] [":" `format_spec`] "}"
Eric Smithc4cae322009-04-22 00:53:01 +0000198 field_name: arg_name ("." `attribute_name` | "[" `element_index` "]")*
199 arg_name: (`identifier` | `integer`)?
Georg Brandl4b491312007-08-31 09:22:56 +0000200 attribute_name: `identifier`
201 element_index: `integer`
Benjamin Peterson065ba702008-11-09 01:43:02 +0000202 conversion: "r" | "s" | "a"
Georg Brandl4b491312007-08-31 09:22:56 +0000203 format_spec: <described in the next section>
Georg Brandl48310cd2009-01-03 21:18:54 +0000204
Georg Brandl2f3ed682009-09-01 07:42:40 +0000205In less formal terms, the replacement field can start with a *field_name* that specifies
Eric Smithc4cae322009-04-22 00:53:01 +0000206the object whose value is to be formatted and inserted
207into the output instead of the replacement field.
208The *field_name* is optionally followed by a *conversion* field, which is
Georg Brandl4b491312007-08-31 09:22:56 +0000209preceded by an exclamation point ``'!'``, and a *format_spec*, which is preceded
Eric Smithc4cae322009-04-22 00:53:01 +0000210by a colon ``':'``. These specify a non-default format for the replacement value.
Georg Brandl4b491312007-08-31 09:22:56 +0000211
Eric Smithc4cae322009-04-22 00:53:01 +0000212The *field_name* itself begins with an *arg_name* that is either either a number or a
213keyword. If it's a number, it refers to a positional argument, and if it's a keyword,
214it refers to a named keyword argument. If the numerical arg_names in a format string
215are 0, 1, 2, ... in sequence, they can all be omitted (not just some)
216and the numbers 0, 1, 2, ... will be automatically inserted in that order.
217The *arg_name* can be followed by any number of index or
Georg Brandl4b491312007-08-31 09:22:56 +0000218attribute expressions. An expression of the form ``'.name'`` selects the named
219attribute using :func:`getattr`, while an expression of the form ``'[index]'``
220does an index lookup using :func:`__getitem__`.
221
222Some simple format string examples::
223
224 "First, thou shalt count to {0}" # References first positional argument
Benjamin Peterson5879d412009-03-30 14:51:56 +0000225 "Bring me a {}" # Implicitly references the first positional argument
Georg Brandl2f3ed682009-09-01 07:42:40 +0000226 "From {} to {}" # Same as "From {0} to {1}"
Georg Brandl4b491312007-08-31 09:22:56 +0000227 "My quest is {name}" # References keyword argument 'name'
228 "Weight in tons {0.weight}" # 'weight' attribute of first positional arg
229 "Units destroyed: {players[0]}" # First element of keyword argument 'players'.
Georg Brandl48310cd2009-01-03 21:18:54 +0000230
Georg Brandl4b491312007-08-31 09:22:56 +0000231The *conversion* field causes a type coercion before formatting. Normally, the
232job of formatting a value is done by the :meth:`__format__` method of the value
233itself. However, in some cases it is desirable to force a type to be formatted
234as a string, overriding its own definition of formatting. By converting the
235value to a string before calling :meth:`__format__`, the normal formatting logic
236is bypassed.
237
Georg Brandl559e5d72008-06-11 18:37:52 +0000238Three conversion flags are currently supported: ``'!s'`` which calls :func:`str`
239on the value, ``'!r'`` which calls :func:`repr` and ``'!a'`` which calls
240:func:`ascii`.
Georg Brandl4b491312007-08-31 09:22:56 +0000241
242Some examples::
243
244 "Harold's a clever {0!s}" # Calls str() on the argument first
245 "Bring out the holy {name!r}" # Calls repr() on the argument first
Georg Brandl2f3ed682009-09-01 07:42:40 +0000246 "More {!a}" # Calls ascii() on the argument first
Georg Brandl4b491312007-08-31 09:22:56 +0000247
248The *format_spec* field contains a specification of how the value should be
249presented, including such details as field width, alignment, padding, decimal
250precision and so on. Each value type can define it's own "formatting
251mini-language" or interpretation of the *format_spec*.
252
253Most built-in types support a common formatting mini-language, which is
254described in the next section.
255
256A *format_spec* field can also include nested replacement fields within it.
257These nested replacement fields can contain only a field name; conversion flags
258and format specifications are not allowed. The replacement fields within the
259format_spec are substituted before the *format_spec* string is interpreted.
260This allows the formatting of a value to be dynamically specified.
261
262For example, suppose you wanted to have a replacement field whose field width is
263determined by another variable::
264
265 "A man with two {0:{1}}".format("noses", 10)
266
267This would first evaluate the inner replacement field, making the format string
268effectively::
269
270 "A man with two {0:10}"
271
272Then the outer replacement field would be evaluated, producing::
273
274 "noses "
Georg Brandl48310cd2009-01-03 21:18:54 +0000275
Georg Brandl2ee470f2008-07-16 12:55:28 +0000276Which is substituted into the string, yielding::
Georg Brandl48310cd2009-01-03 21:18:54 +0000277
Georg Brandl4b491312007-08-31 09:22:56 +0000278 "A man with two noses "
Georg Brandl48310cd2009-01-03 21:18:54 +0000279
Georg Brandl4b491312007-08-31 09:22:56 +0000280(The extra space is because we specified a field width of 10, and because left
281alignment is the default for strings.)
282
Georg Brandl4b491312007-08-31 09:22:56 +0000283
284.. _formatspec:
285
286Format Specification Mini-Language
287^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
288
289"Format specifications" are used within replacement fields contained within a
290format string to define how individual values are presented (see
Georg Brandl22b34312009-07-26 14:54:51 +0000291:ref:`formatstrings`.) They can also be passed directly to the built-in
Georg Brandl4b491312007-08-31 09:22:56 +0000292:func:`format` function. Each formattable type may define how the format
293specification is to be interpreted.
294
295Most built-in types implement the following options for format specifications,
296although some of the formatting options are only supported by the numeric types.
297
298A general convention is that an empty format string (``""``) produces the same
Georg Brandl222e1272008-01-11 12:58:40 +0000299result as if you had called :func:`str` on the value.
Georg Brandl4b491312007-08-31 09:22:56 +0000300
301The general form of a *standard format specifier* is:
302
303.. productionlist:: sf
Raymond Hettinger6db94702009-07-12 20:49:21 +0000304 format_spec: [[`fill`]`align`][`sign`][#][0][`width`][,][.`precision`][`type`]
Georg Brandl4b491312007-08-31 09:22:56 +0000305 fill: <a character other than '}'>
306 align: "<" | ">" | "=" | "^"
307 sign: "+" | "-" | " "
308 width: `integer`
309 precision: `integer`
310 type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "x" | "X" | "%"
Georg Brandl48310cd2009-01-03 21:18:54 +0000311
Georg Brandl4b491312007-08-31 09:22:56 +0000312The *fill* character can be any character other than '}' (which signifies the
313end of the field). The presence of a fill character is signaled by the *next*
314character, which must be one of the alignment options. If the second character
315of *format_spec* is not a valid alignment option, then it is assumed that both
316the fill character and the alignment option are absent.
317
318The meaning of the various alignment options is as follows:
319
320 +---------+----------------------------------------------------------+
321 | Option | Meaning |
322 +=========+==========================================================+
323 | ``'<'`` | Forces the field to be left-aligned within the available |
324 | | space (This is the default.) |
325 +---------+----------------------------------------------------------+
326 | ``'>'`` | Forces the field to be right-aligned within the |
327 | | available space. |
328 +---------+----------------------------------------------------------+
329 | ``'='`` | Forces the padding to be placed after the sign (if any) |
330 | | but before the digits. This is used for printing fields |
331 | | in the form '+000000120'. This alignment option is only |
332 | | valid for numeric types. |
333 +---------+----------------------------------------------------------+
334 | ``'^'`` | Forces the field to be centered within the available |
335 | | space. |
336 +---------+----------------------------------------------------------+
337
338Note that unless a minimum field width is defined, the field width will always
339be the same size as the data to fill it, so that the alignment option has no
340meaning in this case.
341
342The *sign* option is only valid for number types, and can be one of the
343following:
344
345 +---------+----------------------------------------------------------+
346 | Option | Meaning |
347 +=========+==========================================================+
348 | ``'+'`` | indicates that a sign should be used for both |
349 | | positive as well as negative numbers. |
350 +---------+----------------------------------------------------------+
351 | ``'-'`` | indicates that a sign should be used only for negative |
352 | | numbers (this is the default behavior). |
353 +---------+----------------------------------------------------------+
354 | space | indicates that a leading space should be used on |
355 | | positive numbers, and a minus sign on negative numbers. |
356 +---------+----------------------------------------------------------+
357
Benjamin Petersond7b03282008-09-13 15:58:53 +0000358The ``'#'`` option is only valid for integers, and only for binary, octal, or
359hexadecimal output. If present, it specifies that the output will be prefixed
360by ``'0b'``, ``'0o'``, or ``'0x'``, respectively.
Eric Smithd68af8f2008-07-16 00:15:35 +0000361
Raymond Hettinger6db94702009-07-12 20:49:21 +0000362The ``','`` option signals the use of a comma for a thousands separator.
363For a locale aware separator, use the ``'n'`` integer presentation type
364instead.
365
Georg Brandl4b491312007-08-31 09:22:56 +0000366*width* is a decimal integer defining the minimum field width. If not
367specified, then the field width will be determined by the content.
368
369If the *width* field is preceded by a zero (``'0'``) character, this enables
370zero-padding. This is equivalent to an *alignment* type of ``'='`` and a *fill*
371character of ``'0'``.
372
373The *precision* is a decimal number indicating how many digits should be
Georg Brandl3dbca812008-07-23 16:10:53 +0000374displayed after the decimal point for a floating point value formatted with
375``'f'`` and ``'F'``, or before and after the decimal point for a floating point
376value formatted with ``'g'`` or ``'G'``. For non-number types the field
377indicates the maximum field size - in other words, how many characters will be
Eric Smithe5fffc72009-05-07 19:38:09 +0000378used from the field content. The *precision* is not allowed for integer values.
Georg Brandl4b491312007-08-31 09:22:56 +0000379
380Finally, the *type* determines how the data should be presented.
381
382The available integer presentation types are:
383
384 +---------+----------------------------------------------------------+
385 | Type | Meaning |
386 +=========+==========================================================+
Eric Smithd68af8f2008-07-16 00:15:35 +0000387 | ``'b'`` | Binary format. Outputs the number in base 2. |
Georg Brandl4b491312007-08-31 09:22:56 +0000388 +---------+----------------------------------------------------------+
389 | ``'c'`` | Character. Converts the integer to the corresponding |
390 | | unicode character before printing. |
391 +---------+----------------------------------------------------------+
392 | ``'d'`` | Decimal Integer. Outputs the number in base 10. |
393 +---------+----------------------------------------------------------+
394 | ``'o'`` | Octal format. Outputs the number in base 8. |
395 +---------+----------------------------------------------------------+
396 | ``'x'`` | Hex format. Outputs the number in base 16, using lower- |
397 | | case letters for the digits above 9. |
398 +---------+----------------------------------------------------------+
399 | ``'X'`` | Hex format. Outputs the number in base 16, using upper- |
400 | | case letters for the digits above 9. |
401 +---------+----------------------------------------------------------+
Eric Smith5e18a202008-05-12 10:01:24 +0000402 | ``'n'`` | Number. This is the same as ``'d'``, except that it uses |
403 | | the current locale setting to insert the appropriate |
404 | | number separator characters. |
405 +---------+----------------------------------------------------------+
Georg Brandl3dbca812008-07-23 16:10:53 +0000406 | None | The same as ``'d'``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000407 +---------+----------------------------------------------------------+
Georg Brandl48310cd2009-01-03 21:18:54 +0000408
Georg Brandl4b491312007-08-31 09:22:56 +0000409The available presentation types for floating point and decimal values are:
Georg Brandl48310cd2009-01-03 21:18:54 +0000410
Georg Brandl4b491312007-08-31 09:22:56 +0000411 +---------+----------------------------------------------------------+
412 | Type | Meaning |
413 +=========+==========================================================+
414 | ``'e'`` | Exponent notation. Prints the number in scientific |
415 | | notation using the letter 'e' to indicate the exponent. |
416 +---------+----------------------------------------------------------+
Eric Smith22b85b32008-07-17 19:18:29 +0000417 | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an |
418 | | upper case 'E' as the separator character. |
Georg Brandl4b491312007-08-31 09:22:56 +0000419 +---------+----------------------------------------------------------+
420 | ``'f'`` | Fixed point. Displays the number as a fixed-point |
421 | | number. |
422 +---------+----------------------------------------------------------+
Eric Smith741191f2009-05-06 13:08:15 +0000423 | ``'F'`` | Fixed point. Same as ``'f'``, but converts ``nan`` to |
424 | | ``NAN`` and ``inf`` to ``INF``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000425 +---------+----------------------------------------------------------+
Mark Dickinsonc70614f2009-10-08 20:05:48 +0000426 | ``'g'`` | General format. For a given precision ``p >= 1``, |
427 | | this rounds the number to ``p`` significant digits and |
428 | | then formats the result in either fixed-point format |
429 | | or in scientific notation, depending on its magnitude. |
430 | | |
431 | | The precise rules are as follows: suppose that the |
432 | | result formatted with presentation type ``'e'`` and |
433 | | precision ``p-1`` would have exponent ``exp``. Then |
434 | | if ``-4 <= exp < p``, the number is formatted |
435 | | with presentation type ``'f'`` and precision |
436 | | ``p-1-exp``. Otherwise, the number is formatted |
437 | | with presentation type ``'e'`` and precision ``p-1``. |
438 | | In both cases insignificant trailing zeros are removed |
439 | | from the significand, and the decimal point is also |
440 | | removed if there are no remaining digits following it. |
441 | | |
442 | | Postive and negative infinity, positive and negative |
443 | | zero, and nans, are formatted as ``inf``, ``-inf``, |
444 | | ``0``, ``-0`` and ``nan`` respectively, regardless of |
445 | | the precision. |
446 | | |
447 | | A precision of ``0`` is treated as equivalent to a |
448 | | precision of ``1``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000449 +---------+----------------------------------------------------------+
450 | ``'G'`` | General format. Same as ``'g'`` except switches to |
Mark Dickinsonc70614f2009-10-08 20:05:48 +0000451 | | ``'E'`` if the number gets too large. The |
452 | | representations of infinity and NaN are uppercased, too. |
Georg Brandl4b491312007-08-31 09:22:56 +0000453 +---------+----------------------------------------------------------+
454 | ``'n'`` | Number. This is the same as ``'g'``, except that it uses |
455 | | the current locale setting to insert the appropriate |
456 | | number separator characters. |
457 +---------+----------------------------------------------------------+
458 | ``'%'`` | Percentage. Multiplies the number by 100 and displays |
459 | | in fixed (``'f'``) format, followed by a percent sign. |
460 +---------+----------------------------------------------------------+
Eric Smith3bef15b2009-05-05 17:19:46 +0000461 | None | Similar to ``'g'``, except with at least one digit past |
462 | | the decimal point and a default precision of 12. This is |
463 | | intended to match :func:`str`, except you can add the |
464 | | other format modifiers. |
Georg Brandl4b491312007-08-31 09:22:56 +0000465 +---------+----------------------------------------------------------+
466
467
468.. _template-strings:
469
Georg Brandl116aa622007-08-15 14:28:22 +0000470Template strings
471----------------
472
473Templates provide simpler string substitutions as described in :pep:`292`.
474Instead of the normal ``%``\ -based substitutions, Templates support ``$``\
475-based substitutions, using the following rules:
476
477* ``$$`` is an escape; it is replaced with a single ``$``.
478
479* ``$identifier`` names a substitution placeholder matching a mapping key of
480 ``"identifier"``. By default, ``"identifier"`` must spell a Python
481 identifier. The first non-identifier character after the ``$`` character
482 terminates this placeholder specification.
483
484* ``${identifier}`` is equivalent to ``$identifier``. It is required when valid
485 identifier characters follow the placeholder but are not part of the
486 placeholder, such as ``"${noun}ification"``.
487
488Any other appearance of ``$`` in the string will result in a :exc:`ValueError`
489being raised.
490
Georg Brandl116aa622007-08-15 14:28:22 +0000491The :mod:`string` module provides a :class:`Template` class that implements
492these rules. The methods of :class:`Template` are:
493
494
495.. class:: Template(template)
496
497 The constructor takes a single argument which is the template string.
498
499
Georg Brandl7f01a132009-09-16 15:58:14 +0000500 .. method:: substitute(mapping, **kwds)
Georg Brandl116aa622007-08-15 14:28:22 +0000501
Benjamin Petersone41251e2008-04-25 01:59:09 +0000502 Performs the template substitution, returning a new string. *mapping* is
503 any dictionary-like object with keys that match the placeholders in the
504 template. Alternatively, you can provide keyword arguments, where the
Georg Brandl7f01a132009-09-16 15:58:14 +0000505 keywords are the placeholders. When both *mapping* and *kwds* are given
506 and there are duplicates, the placeholders from *kwds* take precedence.
Georg Brandl116aa622007-08-15 14:28:22 +0000507
508
Georg Brandl7f01a132009-09-16 15:58:14 +0000509 .. method:: safe_substitute(mapping, **kwds)
Georg Brandl116aa622007-08-15 14:28:22 +0000510
Benjamin Petersone41251e2008-04-25 01:59:09 +0000511 Like :meth:`substitute`, except that if placeholders are missing from
Georg Brandl7f01a132009-09-16 15:58:14 +0000512 *mapping* and *kwds*, instead of raising a :exc:`KeyError` exception, the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000513 original placeholder will appear in the resulting string intact. Also,
514 unlike with :meth:`substitute`, any other appearances of the ``$`` will
515 simply return ``$`` instead of raising :exc:`ValueError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000516
Benjamin Petersone41251e2008-04-25 01:59:09 +0000517 While other exceptions may still occur, this method is called "safe"
518 because substitutions always tries to return a usable string instead of
519 raising an exception. In another sense, :meth:`safe_substitute` may be
520 anything other than safe, since it will silently ignore malformed
521 templates containing dangling delimiters, unmatched braces, or
522 placeholders that are not valid Python identifiers.
Georg Brandl116aa622007-08-15 14:28:22 +0000523
524:class:`Template` instances also provide one public data attribute:
525
526
527.. attribute:: string.template
528
529 This is the object passed to the constructor's *template* argument. In general,
530 you shouldn't change it, but read-only access is not enforced.
531
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