blob: 517e209b5b008762355dba69695806f0ecabf8d6 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`string` --- Common string operations
3==========================================
4
5.. module:: string
6 :synopsis: Common string operations.
7
8
9.. index:: module: re
10
Georg Brandl4b491312007-08-31 09:22:56 +000011The :mod:`string` module contains a number of useful constants and classes, as
12well as some deprecated legacy functions that are also available as methods on
13strings. In addition, Python's built-in string classes support the sequence type
14methods described in the :ref:`typesseq` section, and also the string-specific
15methods described in the :ref:`string-methods` section. To output formatted
16strings, see the :ref:`string-formatting` section. Also, see the :mod:`re`
17module for string functions based on regular expressions.
Georg Brandl116aa622007-08-15 14:28:22 +000018
19
20String constants
21----------------
22
23The constants defined in this module are:
24
25
26.. data:: ascii_letters
27
28 The concatenation of the :const:`ascii_lowercase` and :const:`ascii_uppercase`
29 constants described below. This value is not locale-dependent.
30
31
32.. data:: ascii_lowercase
33
34 The lowercase letters ``'abcdefghijklmnopqrstuvwxyz'``. This value is not
35 locale-dependent and will not change.
36
37
38.. data:: ascii_uppercase
39
40 The uppercase letters ``'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. This value is not
41 locale-dependent and will not change.
42
43
44.. data:: digits
45
46 The string ``'0123456789'``.
47
48
49.. data:: hexdigits
50
51 The string ``'0123456789abcdefABCDEF'``.
52
53
54.. data:: octdigits
55
56 The string ``'01234567'``.
57
58
59.. data:: punctuation
60
61 String of ASCII characters which are considered punctuation characters
62 in the ``C`` locale.
63
64
65.. data:: printable
66
67 String of ASCII characters which are considered printable. This is a
68 combination of :const:`digits`, :const:`ascii_letters`, :const:`punctuation`,
69 and :const:`whitespace`.
70
71
72.. data:: whitespace
73
Georg Brandl50767402008-11-22 08:31:09 +000074 A string containing all ASCII characters that are considered whitespace.
Georg Brandl116aa622007-08-15 14:28:22 +000075 This includes the characters space, tab, linefeed, return, formfeed, and
76 vertical tab.
77
78
Georg Brandl4b491312007-08-31 09:22:56 +000079.. _string-formatting:
80
81String Formatting
82-----------------
83
Benjamin Peterson50923f92008-05-25 19:45:17 +000084The built-in string class provides the ability to do complex variable
85substitutions and value formatting via the :func:`format` method described in
86:pep:`3101`. The :class:`Formatter` class in the :mod:`string` module allows
87you to create and customize your own string formatting behaviors using the same
88implementation as the built-in :meth:`format` method.
Georg Brandl4b491312007-08-31 09:22:56 +000089
90.. 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
198 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
Eric Smithc4cae322009-04-22 00:53:01 +0000206In less formal terms, the replacement field starts with a *field_name* that specifies
207the 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
Eric Smithc4cae322009-04-22 00:53:01 +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
247
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
291:ref:`formatstrings`.) They can also be passed directly to the builtin
292: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
Eric Smithd68af8f2008-07-16 00:15:35 +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
Georg Brandl4b491312007-08-31 09:22:56 +0000362*width* is a decimal integer defining the minimum field width. If not
363specified, then the field width will be determined by the content.
364
365If the *width* field is preceded by a zero (``'0'``) character, this enables
366zero-padding. This is equivalent to an *alignment* type of ``'='`` and a *fill*
367character of ``'0'``.
368
369The *precision* is a decimal number indicating how many digits should be
Georg Brandl3dbca812008-07-23 16:10:53 +0000370displayed after the decimal point for a floating point value formatted with
371``'f'`` and ``'F'``, or before and after the decimal point for a floating point
372value formatted with ``'g'`` or ``'G'``. For non-number types the field
373indicates the maximum field size - in other words, how many characters will be
374used from the field content. The *precision* is ignored for integer values.
Georg Brandl4b491312007-08-31 09:22:56 +0000375
376Finally, the *type* determines how the data should be presented.
377
378The available integer presentation types are:
379
380 +---------+----------------------------------------------------------+
381 | Type | Meaning |
382 +=========+==========================================================+
Eric Smithd68af8f2008-07-16 00:15:35 +0000383 | ``'b'`` | Binary format. Outputs the number in base 2. |
Georg Brandl4b491312007-08-31 09:22:56 +0000384 +---------+----------------------------------------------------------+
385 | ``'c'`` | Character. Converts the integer to the corresponding |
386 | | unicode character before printing. |
387 +---------+----------------------------------------------------------+
388 | ``'d'`` | Decimal Integer. Outputs the number in base 10. |
389 +---------+----------------------------------------------------------+
390 | ``'o'`` | Octal format. Outputs the number in base 8. |
391 +---------+----------------------------------------------------------+
392 | ``'x'`` | Hex format. Outputs the number in base 16, using lower- |
393 | | case letters for the digits above 9. |
394 +---------+----------------------------------------------------------+
395 | ``'X'`` | Hex format. Outputs the number in base 16, using upper- |
396 | | case letters for the digits above 9. |
397 +---------+----------------------------------------------------------+
Eric Smith5e18a202008-05-12 10:01:24 +0000398 | ``'n'`` | Number. This is the same as ``'d'``, except that it uses |
399 | | the current locale setting to insert the appropriate |
400 | | number separator characters. |
401 +---------+----------------------------------------------------------+
Georg Brandl3dbca812008-07-23 16:10:53 +0000402 | None | The same as ``'d'``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000403 +---------+----------------------------------------------------------+
Georg Brandl48310cd2009-01-03 21:18:54 +0000404
Georg Brandl4b491312007-08-31 09:22:56 +0000405The available presentation types for floating point and decimal values are:
Georg Brandl48310cd2009-01-03 21:18:54 +0000406
Georg Brandl4b491312007-08-31 09:22:56 +0000407 +---------+----------------------------------------------------------+
408 | Type | Meaning |
409 +=========+==========================================================+
410 | ``'e'`` | Exponent notation. Prints the number in scientific |
411 | | notation using the letter 'e' to indicate the exponent. |
412 +---------+----------------------------------------------------------+
Eric Smith22b85b32008-07-17 19:18:29 +0000413 | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an |
414 | | upper case 'E' as the separator character. |
Georg Brandl4b491312007-08-31 09:22:56 +0000415 +---------+----------------------------------------------------------+
416 | ``'f'`` | Fixed point. Displays the number as a fixed-point |
417 | | number. |
418 +---------+----------------------------------------------------------+
Eric Smith22b85b32008-07-17 19:18:29 +0000419 | ``'F'`` | Fixed point. Same as ``'f'``. |
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 +---------+----------------------------------------------------------+
Georg Brandl3dbca812008-07-23 16:10:53 +0000438 | None | The same as ``'g'``. |
Georg Brandl4b491312007-08-31 09:22:56 +0000439 +---------+----------------------------------------------------------+
440
441
442.. _template-strings:
443
Georg Brandl116aa622007-08-15 14:28:22 +0000444Template strings
445----------------
446
447Templates provide simpler string substitutions as described in :pep:`292`.
448Instead of the normal ``%``\ -based substitutions, Templates support ``$``\
449-based substitutions, using the following rules:
450
451* ``$$`` is an escape; it is replaced with a single ``$``.
452
453* ``$identifier`` names a substitution placeholder matching a mapping key of
454 ``"identifier"``. By default, ``"identifier"`` must spell a Python
455 identifier. The first non-identifier character after the ``$`` character
456 terminates this placeholder specification.
457
458* ``${identifier}`` is equivalent to ``$identifier``. It is required when valid
459 identifier characters follow the placeholder but are not part of the
460 placeholder, such as ``"${noun}ification"``.
461
462Any other appearance of ``$`` in the string will result in a :exc:`ValueError`
463being raised.
464
Georg Brandl116aa622007-08-15 14:28:22 +0000465The :mod:`string` module provides a :class:`Template` class that implements
466these rules. The methods of :class:`Template` are:
467
468
469.. class:: Template(template)
470
471 The constructor takes a single argument which is the template string.
472
473
Benjamin Petersone41251e2008-04-25 01:59:09 +0000474 .. method:: substitute(mapping[, **kws])
Georg Brandl116aa622007-08-15 14:28:22 +0000475
Benjamin Petersone41251e2008-04-25 01:59:09 +0000476 Performs the template substitution, returning a new string. *mapping* is
477 any dictionary-like object with keys that match the placeholders in the
478 template. Alternatively, you can provide keyword arguments, where the
479 keywords are the placeholders. When both *mapping* and *kws* are given
480 and there are duplicates, the placeholders from *kws* take precedence.
Georg Brandl116aa622007-08-15 14:28:22 +0000481
482
Benjamin Petersone41251e2008-04-25 01:59:09 +0000483 .. method:: safe_substitute(mapping[, **kws])
Georg Brandl116aa622007-08-15 14:28:22 +0000484
Benjamin Petersone41251e2008-04-25 01:59:09 +0000485 Like :meth:`substitute`, except that if placeholders are missing from
486 *mapping* and *kws*, instead of raising a :exc:`KeyError` exception, the
487 original placeholder will appear in the resulting string intact. Also,
488 unlike with :meth:`substitute`, any other appearances of the ``$`` will
489 simply return ``$`` instead of raising :exc:`ValueError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000490
Benjamin Petersone41251e2008-04-25 01:59:09 +0000491 While other exceptions may still occur, this method is called "safe"
492 because substitutions always tries to return a usable string instead of
493 raising an exception. In another sense, :meth:`safe_substitute` may be
494 anything other than safe, since it will silently ignore malformed
495 templates containing dangling delimiters, unmatched braces, or
496 placeholders that are not valid Python identifiers.
Georg Brandl116aa622007-08-15 14:28:22 +0000497
498:class:`Template` instances also provide one public data attribute:
499
500
501.. attribute:: string.template
502
503 This is the object passed to the constructor's *template* argument. In general,
504 you shouldn't change it, but read-only access is not enforced.
505
Christian Heimesfe337bf2008-03-23 21:54:12 +0000506Here is an example of how to use a Template:
Georg Brandl116aa622007-08-15 14:28:22 +0000507
508 >>> from string import Template
509 >>> s = Template('$who likes $what')
510 >>> s.substitute(who='tim', what='kung pao')
511 'tim likes kung pao'
512 >>> d = dict(who='tim')
513 >>> Template('Give $who $100').substitute(d)
514 Traceback (most recent call last):
515 [...]
516 ValueError: Invalid placeholder in string: line 1, col 10
517 >>> Template('$who likes $what').substitute(d)
518 Traceback (most recent call last):
519 [...]
520 KeyError: 'what'
521 >>> Template('$who likes $what').safe_substitute(d)
522 'tim likes $what'
523
524Advanced usage: you can derive subclasses of :class:`Template` to customize the
525placeholder syntax, delimiter character, or the entire regular expression used
526to parse template strings. To do this, you can override these class attributes:
527
528* *delimiter* -- This is the literal string describing a placeholder introducing
529 delimiter. The default value ``$``. Note that this should *not* be a regular
530 expression, as the implementation will call :meth:`re.escape` on this string as
531 needed.
532
533* *idpattern* -- This is the regular expression describing the pattern for
534 non-braced placeholders (the braces will be added automatically as
535 appropriate). The default value is the regular expression
536 ``[_a-z][_a-z0-9]*``.
537
538Alternatively, you can provide the entire regular expression pattern by
539overriding the class attribute *pattern*. If you do this, the value must be a
540regular expression object with four named capturing groups. The capturing
541groups correspond to the rules given above, along with the invalid placeholder
542rule:
543
544* *escaped* -- This group matches the escape sequence, e.g. ``$$``, in the
545 default pattern.
546
547* *named* -- This group matches the unbraced placeholder name; it should not
548 include the delimiter in capturing group.
549
550* *braced* -- This group matches the brace enclosed placeholder name; it should
551 not include either the delimiter or braces in the capturing group.
552
553* *invalid* -- This group matches any other delimiter pattern (usually a single
554 delimiter), and it should appear last in the regular expression.
555
556
Georg Brandlabc38772009-04-12 15:51:51 +0000557Helper functions
Georg Brandl116aa622007-08-15 14:28:22 +0000558----------------
559
Georg Brandl116aa622007-08-15 14:28:22 +0000560.. function:: capwords(s)
561
562 Split the argument into words using :func:`split`, capitalize each word using
563 :func:`capitalize`, and join the capitalized words using :func:`join`. Note
564 that this replaces runs of whitespace characters by a single space, and removes
565 leading and trailing whitespace.
566
567
Georg Brandl7f13e6b2007-08-31 10:37:15 +0000568.. function:: maketrans(frm, to)
Georg Brandl116aa622007-08-15 14:28:22 +0000569
Georg Brandl7f13e6b2007-08-31 10:37:15 +0000570 Return a translation table suitable for passing to :meth:`bytes.translate`,
571 that will map each character in *from* into the character at the same
572 position in *to*; *from* and *to* must have the same length.
Georg Brandlabc38772009-04-12 15:51:51 +0000573
574 .. deprecated:: 3.1
575 Use the :meth:`bytes.maketrans` static method instead.