blob: 959ea99a953aa0baab09e5a01970f5515596aaef [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
197 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
Eric Smithc4cae322009-04-22 00:53:01 +0000205In less formal terms, the replacement field starts with a *field_name* that specifies
206the 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
Eric Smithc4cae322009-04-22 00:53:01 +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
246
247The *format_spec* field contains a specification of how the value should be
248presented, including such details as field width, alignment, padding, decimal
249precision and so on. Each value type can define it's own "formatting
250mini-language" or interpretation of the *format_spec*.
251
252Most built-in types support a common formatting mini-language, which is
253described in the next section.
254
255A *format_spec* field can also include nested replacement fields within it.
256These nested replacement fields can contain only a field name; conversion flags
257and format specifications are not allowed. The replacement fields within the
258format_spec are substituted before the *format_spec* string is interpreted.
259This allows the formatting of a value to be dynamically specified.
260
261For example, suppose you wanted to have a replacement field whose field width is
262determined by another variable::
263
264 "A man with two {0:{1}}".format("noses", 10)
265
266This would first evaluate the inner replacement field, making the format string
267effectively::
268
269 "A man with two {0:10}"
270
271Then the outer replacement field would be evaluated, producing::
272
273 "noses "
Georg Brandl48310cd2009-01-03 21:18:54 +0000274
Georg Brandl2ee470f2008-07-16 12:55:28 +0000275Which is substituted into the string, yielding::
Georg Brandl48310cd2009-01-03 21:18:54 +0000276
Georg Brandl4b491312007-08-31 09:22:56 +0000277 "A man with two noses "
Georg Brandl48310cd2009-01-03 21:18:54 +0000278
Georg Brandl4b491312007-08-31 09:22:56 +0000279(The extra space is because we specified a field width of 10, and because left
280alignment is the default for strings.)
281
Georg Brandl4b491312007-08-31 09:22:56 +0000282
283.. _formatspec:
284
285Format Specification Mini-Language
286^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
287
288"Format specifications" are used within replacement fields contained within a
289format string to define how individual values are presented (see
290:ref:`formatstrings`.) They can also be passed directly to the builtin
291:func:`format` function. Each formattable type may define how the format
292specification is to be interpreted.
293
294Most built-in types implement the following options for format specifications,
295although some of the formatting options are only supported by the numeric types.
296
297A general convention is that an empty format string (``""``) produces the same
Georg Brandl222e1272008-01-11 12:58:40 +0000298result as if you had called :func:`str` on the value.
Georg Brandl4b491312007-08-31 09:22:56 +0000299
300The general form of a *standard format specifier* is:
301
302.. productionlist:: sf
Eric Smithd68af8f2008-07-16 00:15:35 +0000303 format_spec: [[`fill`]`align`][`sign`][#][0][`width`][.`precision`][`type`]
Georg Brandl4b491312007-08-31 09:22:56 +0000304 fill: <a character other than '}'>
305 align: "<" | ">" | "=" | "^"
306 sign: "+" | "-" | " "
307 width: `integer`
308 precision: `integer`
309 type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "x" | "X" | "%"
Georg Brandl48310cd2009-01-03 21:18:54 +0000310
Georg Brandl4b491312007-08-31 09:22:56 +0000311The *fill* character can be any character other than '}' (which signifies the
312end of the field). The presence of a fill character is signaled by the *next*
313character, which must be one of the alignment options. If the second character
314of *format_spec* is not a valid alignment option, then it is assumed that both
315the fill character and the alignment option are absent.
316
317The meaning of the various alignment options is as follows:
318
319 +---------+----------------------------------------------------------+
320 | Option | Meaning |
321 +=========+==========================================================+
322 | ``'<'`` | Forces the field to be left-aligned within the available |
323 | | space (This is the default.) |
324 +---------+----------------------------------------------------------+
325 | ``'>'`` | Forces the field to be right-aligned within the |
326 | | available space. |
327 +---------+----------------------------------------------------------+
328 | ``'='`` | Forces the padding to be placed after the sign (if any) |
329 | | but before the digits. This is used for printing fields |
330 | | in the form '+000000120'. This alignment option is only |
331 | | valid for numeric types. |
332 +---------+----------------------------------------------------------+
333 | ``'^'`` | Forces the field to be centered within the available |
334 | | space. |
335 +---------+----------------------------------------------------------+
336
337Note that unless a minimum field width is defined, the field width will always
338be the same size as the data to fill it, so that the alignment option has no
339meaning in this case.
340
341The *sign* option is only valid for number types, and can be one of the
342following:
343
344 +---------+----------------------------------------------------------+
345 | Option | Meaning |
346 +=========+==========================================================+
347 | ``'+'`` | indicates that a sign should be used for both |
348 | | positive as well as negative numbers. |
349 +---------+----------------------------------------------------------+
350 | ``'-'`` | indicates that a sign should be used only for negative |
351 | | numbers (this is the default behavior). |
352 +---------+----------------------------------------------------------+
353 | space | indicates that a leading space should be used on |
354 | | positive numbers, and a minus sign on negative numbers. |
355 +---------+----------------------------------------------------------+
356
Benjamin Petersond7b03282008-09-13 15:58:53 +0000357The ``'#'`` option is only valid for integers, and only for binary, octal, or
358hexadecimal output. If present, it specifies that the output will be prefixed
359by ``'0b'``, ``'0o'``, or ``'0x'``, respectively.
Eric Smithd68af8f2008-07-16 00:15:35 +0000360
Georg Brandl4b491312007-08-31 09:22:56 +0000361*width* is a decimal integer defining the minimum field width. If not
362specified, then the field width will be determined by the content.
363
364If the *width* field is preceded by a zero (``'0'``) character, this enables
365zero-padding. This is equivalent to an *alignment* type of ``'='`` and a *fill*
366character of ``'0'``.
367
368The *precision* is a decimal number indicating how many digits should be
Georg Brandl3dbca812008-07-23 16:10:53 +0000369displayed after the decimal point for a floating point value formatted with
370``'f'`` and ``'F'``, or before and after the decimal point for a floating point
371value formatted with ``'g'`` or ``'G'``. For non-number types the field
372indicates the maximum field size - in other words, how many characters will be
373used from the field content. The *precision* is ignored for integer values.
Georg Brandl4b491312007-08-31 09:22:56 +0000374
375Finally, the *type* determines how the data should be presented.
376
377The available integer presentation types are:
378
379 +---------+----------------------------------------------------------+
380 | Type | Meaning |
381 +=========+==========================================================+
Eric Smithd68af8f2008-07-16 00:15:35 +0000382 | ``'b'`` | Binary format. Outputs the number in base 2. |
Georg Brandl4b491312007-08-31 09:22:56 +0000383 +---------+----------------------------------------------------------+
384 | ``'c'`` | Character. Converts the integer to the corresponding |
385 | | unicode character before printing. |
386 +---------+----------------------------------------------------------+
387 | ``'d'`` | Decimal Integer. Outputs the number in base 10. |
388 +---------+----------------------------------------------------------+
389 | ``'o'`` | Octal format. Outputs the number in base 8. |
390 +---------+----------------------------------------------------------+
391 | ``'x'`` | Hex format. Outputs the number in base 16, using lower- |
392 | | case letters for the digits above 9. |
393 +---------+----------------------------------------------------------+
394 | ``'X'`` | Hex format. Outputs the number in base 16, using upper- |
395 | | case letters for the digits above 9. |
396 +---------+----------------------------------------------------------+
Eric Smith5e18a202008-05-12 10:01:24 +0000397 | ``'n'`` | Number. This is the same as ``'d'``, except that it uses |
398 | | the current locale setting to insert the appropriate |
399 | | number separator characters. |
400 +---------+----------------------------------------------------------+
Georg Brandl3dbca812008-07-23 16:10:53 +0000401 | None | The same as ``'d'``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000402 +---------+----------------------------------------------------------+
Georg Brandl48310cd2009-01-03 21:18:54 +0000403
Georg Brandl4b491312007-08-31 09:22:56 +0000404The available presentation types for floating point and decimal values are:
Georg Brandl48310cd2009-01-03 21:18:54 +0000405
Georg Brandl4b491312007-08-31 09:22:56 +0000406 +---------+----------------------------------------------------------+
407 | Type | Meaning |
408 +=========+==========================================================+
409 | ``'e'`` | Exponent notation. Prints the number in scientific |
410 | | notation using the letter 'e' to indicate the exponent. |
411 +---------+----------------------------------------------------------+
Eric Smith22b85b32008-07-17 19:18:29 +0000412 | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an |
413 | | upper case 'E' as the separator character. |
Georg Brandl4b491312007-08-31 09:22:56 +0000414 +---------+----------------------------------------------------------+
415 | ``'f'`` | Fixed point. Displays the number as a fixed-point |
416 | | number. |
417 +---------+----------------------------------------------------------+
Eric Smith741191f2009-05-06 13:08:15 +0000418 | ``'F'`` | Fixed point. Same as ``'f'``, but converts ``nan`` to |
419 | | ``NAN`` and ``inf`` to ``INF``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000420 +---------+----------------------------------------------------------+
421 | ``'g'`` | General format. This prints the number as a fixed-point |
422 | | number, unless the number is too large, in which case |
Georg Brandl3dbca812008-07-23 16:10:53 +0000423 | | it switches to ``'e'`` exponent notation. Infinity and |
424 | | NaN values are formatted as ``inf``, ``-inf`` and |
425 | | ``nan``, respectively. |
Georg Brandl4b491312007-08-31 09:22:56 +0000426 +---------+----------------------------------------------------------+
427 | ``'G'`` | General format. Same as ``'g'`` except switches to |
Georg Brandl3dbca812008-07-23 16:10:53 +0000428 | | ``'E'`` if the number gets to large. The representations |
429 | | of infinity and NaN are uppercased, too. |
Georg Brandl4b491312007-08-31 09:22:56 +0000430 +---------+----------------------------------------------------------+
431 | ``'n'`` | Number. This is the same as ``'g'``, except that it uses |
432 | | the current locale setting to insert the appropriate |
433 | | number separator characters. |
434 +---------+----------------------------------------------------------+
435 | ``'%'`` | Percentage. Multiplies the number by 100 and displays |
436 | | in fixed (``'f'``) format, followed by a percent sign. |
437 +---------+----------------------------------------------------------+
Eric Smith3bef15b2009-05-05 17:19:46 +0000438 | None | Similar to ``'g'``, except with at least one digit past |
439 | | the decimal point and a default precision of 12. This is |
440 | | intended to match :func:`str`, except you can add the |
441 | | other format modifiers. |
Georg Brandl4b491312007-08-31 09:22:56 +0000442 +---------+----------------------------------------------------------+
443
444
445.. _template-strings:
446
Georg Brandl116aa622007-08-15 14:28:22 +0000447Template strings
448----------------
449
450Templates provide simpler string substitutions as described in :pep:`292`.
451Instead of the normal ``%``\ -based substitutions, Templates support ``$``\
452-based substitutions, using the following rules:
453
454* ``$$`` is an escape; it is replaced with a single ``$``.
455
456* ``$identifier`` names a substitution placeholder matching a mapping key of
457 ``"identifier"``. By default, ``"identifier"`` must spell a Python
458 identifier. The first non-identifier character after the ``$`` character
459 terminates this placeholder specification.
460
461* ``${identifier}`` is equivalent to ``$identifier``. It is required when valid
462 identifier characters follow the placeholder but are not part of the
463 placeholder, such as ``"${noun}ification"``.
464
465Any other appearance of ``$`` in the string will result in a :exc:`ValueError`
466being raised.
467
Georg Brandl116aa622007-08-15 14:28:22 +0000468The :mod:`string` module provides a :class:`Template` class that implements
469these rules. The methods of :class:`Template` are:
470
471
472.. class:: Template(template)
473
474 The constructor takes a single argument which is the template string.
475
476
Benjamin Petersone41251e2008-04-25 01:59:09 +0000477 .. method:: substitute(mapping[, **kws])
Georg Brandl116aa622007-08-15 14:28:22 +0000478
Benjamin Petersone41251e2008-04-25 01:59:09 +0000479 Performs the template substitution, returning a new string. *mapping* is
480 any dictionary-like object with keys that match the placeholders in the
481 template. Alternatively, you can provide keyword arguments, where the
482 keywords are the placeholders. When both *mapping* and *kws* are given
483 and there are duplicates, the placeholders from *kws* take precedence.
Georg Brandl116aa622007-08-15 14:28:22 +0000484
485
Benjamin Petersone41251e2008-04-25 01:59:09 +0000486 .. method:: safe_substitute(mapping[, **kws])
Georg Brandl116aa622007-08-15 14:28:22 +0000487
Benjamin Petersone41251e2008-04-25 01:59:09 +0000488 Like :meth:`substitute`, except that if placeholders are missing from
489 *mapping* and *kws*, instead of raising a :exc:`KeyError` exception, the
490 original placeholder will appear in the resulting string intact. Also,
491 unlike with :meth:`substitute`, any other appearances of the ``$`` will
492 simply return ``$`` instead of raising :exc:`ValueError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000493
Benjamin Petersone41251e2008-04-25 01:59:09 +0000494 While other exceptions may still occur, this method is called "safe"
495 because substitutions always tries to return a usable string instead of
496 raising an exception. In another sense, :meth:`safe_substitute` may be
497 anything other than safe, since it will silently ignore malformed
498 templates containing dangling delimiters, unmatched braces, or
499 placeholders that are not valid Python identifiers.
Georg Brandl116aa622007-08-15 14:28:22 +0000500
501:class:`Template` instances also provide one public data attribute:
502
503
504.. attribute:: string.template
505
506 This is the object passed to the constructor's *template* argument. In general,
507 you shouldn't change it, but read-only access is not enforced.
508
Christian Heimesfe337bf2008-03-23 21:54:12 +0000509Here is an example of how to use a Template:
Georg Brandl116aa622007-08-15 14:28:22 +0000510
511 >>> from string import Template
512 >>> s = Template('$who likes $what')
513 >>> s.substitute(who='tim', what='kung pao')
514 'tim likes kung pao'
515 >>> d = dict(who='tim')
516 >>> Template('Give $who $100').substitute(d)
517 Traceback (most recent call last):
518 [...]
519 ValueError: Invalid placeholder in string: line 1, col 10
520 >>> Template('$who likes $what').substitute(d)
521 Traceback (most recent call last):
522 [...]
523 KeyError: 'what'
524 >>> Template('$who likes $what').safe_substitute(d)
525 'tim likes $what'
526
527Advanced usage: you can derive subclasses of :class:`Template` to customize the
528placeholder syntax, delimiter character, or the entire regular expression used
529to parse template strings. To do this, you can override these class attributes:
530
531* *delimiter* -- This is the literal string describing a placeholder introducing
532 delimiter. The default value ``$``. Note that this should *not* be a regular
533 expression, as the implementation will call :meth:`re.escape` on this string as
534 needed.
535
536* *idpattern* -- This is the regular expression describing the pattern for
537 non-braced placeholders (the braces will be added automatically as
538 appropriate). The default value is the regular expression
539 ``[_a-z][_a-z0-9]*``.
540
541Alternatively, you can provide the entire regular expression pattern by
542overriding the class attribute *pattern*. If you do this, the value must be a
543regular expression object with four named capturing groups. The capturing
544groups correspond to the rules given above, along with the invalid placeholder
545rule:
546
547* *escaped* -- This group matches the escape sequence, e.g. ``$$``, in the
548 default pattern.
549
550* *named* -- This group matches the unbraced placeholder name; it should not
551 include the delimiter in capturing group.
552
553* *braced* -- This group matches the brace enclosed placeholder name; it should
554 not include either the delimiter or braces in the capturing group.
555
556* *invalid* -- This group matches any other delimiter pattern (usually a single
557 delimiter), and it should appear last in the regular expression.
558
559
Georg Brandlabc38772009-04-12 15:51:51 +0000560Helper functions
Georg Brandl116aa622007-08-15 14:28:22 +0000561----------------
562
Georg Brandl116aa622007-08-15 14:28:22 +0000563.. function:: capwords(s)
564
565 Split the argument into words using :func:`split`, capitalize each word using
566 :func:`capitalize`, and join the capitalized words using :func:`join`. Note
567 that this replaces runs of whitespace characters by a single space, and removes
568 leading and trailing whitespace.
569
570
Georg Brandl7f13e6b2007-08-31 10:37:15 +0000571.. function:: maketrans(frm, to)
Georg Brandl116aa622007-08-15 14:28:22 +0000572
Georg Brandl7f13e6b2007-08-31 10:37:15 +0000573 Return a translation table suitable for passing to :meth:`bytes.translate`,
574 that will map each character in *from* into the character at the same
575 position in *to*; *from* and *to* must have the same length.
Georg Brandlabc38772009-04-12 15:51:51 +0000576
577 .. deprecated:: 3.1
578 Use the :meth:`bytes.maketrans` static method instead.