blob: 40aa07c8f92e9087015a975b62cf61698cb16678 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001:mod:`string` --- Common string operations
2==========================================
3
4.. module:: string
5 :synopsis: Common string operations.
6
7
8.. index:: module: re
9
10The :mod:`string` module contains a number of useful constants and
11classes, as well as some deprecated legacy functions that are also
12available as methods on strings. In addition, Python's built-in string
13classes support the sequence type methods described in the
14:ref:`typesseq` section, and also the string-specific methods described
15in the :ref:`string-methods` section. To output formatted strings use
16template strings or the ``%`` operator described in the
17:ref:`string-formatting` section. Also, see the :mod:`re` module for
18string functions based on regular expressions.
19
20
21String constants
22----------------
23
24The constants defined in this module are:
25
26
27.. data:: ascii_letters
28
29 The concatenation of the :const:`ascii_lowercase` and :const:`ascii_uppercase`
30 constants described below. This value is not locale-dependent.
31
32
33.. data:: ascii_lowercase
34
35 The lowercase letters ``'abcdefghijklmnopqrstuvwxyz'``. This value is not
36 locale-dependent and will not change.
37
38
39.. data:: ascii_uppercase
40
41 The uppercase letters ``'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. This value is not
42 locale-dependent and will not change.
43
44
45.. data:: digits
46
47 The string ``'0123456789'``.
48
49
50.. data:: hexdigits
51
52 The string ``'0123456789abcdefABCDEF'``.
53
54
55.. data:: letters
56
57 The concatenation of the strings :const:`lowercase` and :const:`uppercase`
58 described below. The specific value is locale-dependent, and will be updated
59 when :func:`locale.setlocale` is called.
60
61
62.. data:: lowercase
63
64 A string containing all the characters that are considered lowercase letters.
Georg Brandld5ad6da2009-03-04 18:24:41 +000065 On most systems this is the string ``'abcdefghijklmnopqrstuvwxyz'``. The
66 specific value is locale-dependent, and will be updated when
67 :func:`locale.setlocale` is called.
Georg Brandl8ec7f652007-08-15 14:28:01 +000068
69
70.. data:: octdigits
71
72 The string ``'01234567'``.
73
74
75.. data:: punctuation
76
77 String of ASCII characters which are considered punctuation characters in the
78 ``C`` locale.
79
80
81.. data:: printable
82
83 String of characters which are considered printable. This is a combination of
84 :const:`digits`, :const:`letters`, :const:`punctuation`, and
85 :const:`whitespace`.
86
87
88.. data:: uppercase
89
90 A string containing all the characters that are considered uppercase letters.
Georg Brandld5ad6da2009-03-04 18:24:41 +000091 On most systems this is the string ``'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. The
92 specific value is locale-dependent, and will be updated when
93 :func:`locale.setlocale` is called.
Georg Brandl8ec7f652007-08-15 14:28:01 +000094
95
96.. data:: whitespace
97
98 A string containing all characters that are considered whitespace. On most
99 systems this includes the characters space, tab, linefeed, return, formfeed, and
Georg Brandld5ad6da2009-03-04 18:24:41 +0000100 vertical tab.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000101
102
Benjamin Petersonc15205e2008-05-25 20:05:52 +0000103.. _new-string-formatting:
Georg Brandle321c2f2008-05-12 16:45:43 +0000104
105String Formatting
106-----------------
107
108Starting in Python 2.6, the built-in str and unicode classes provide the ability
Benjamin Petersonc15205e2008-05-25 20:05:52 +0000109to do complex variable substitutions and value formatting via the
110:meth:`str.format` method described in :pep:`3101`. The :class:`Formatter`
111class in the :mod:`string` module allows you to create and customize your own
112string formatting behaviors using the same implementation as the built-in
Georg Brandle321c2f2008-05-12 16:45:43 +0000113:meth:`format` method.
114
115.. class:: Formatter
116
117 The :class:`Formatter` class has the following public methods:
118
119 .. method:: format(format_string, *args, *kwargs)
120
121 :meth:`format` is the primary API method. It takes a format template
122 string, and an arbitrary set of positional and keyword argument.
123 :meth:`format` is just a wrapper that calls :meth:`vformat`.
124
125 .. method:: vformat(format_string, args, kwargs)
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000126
Georg Brandle321c2f2008-05-12 16:45:43 +0000127 This function does the actual work of formatting. It is exposed as a
128 separate function for cases where you want to pass in a predefined
129 dictionary of arguments, rather than unpacking and repacking the
130 dictionary as individual arguments using the ``*args`` and ``**kwds``
131 syntax. :meth:`vformat` does the work of breaking up the format template
132 string into character data and replacement fields. It calls the various
133 methods described below.
134
135 In addition, the :class:`Formatter` defines a number of methods that are
136 intended to be replaced by subclasses:
137
138 .. method:: parse(format_string)
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000139
Georg Brandle321c2f2008-05-12 16:45:43 +0000140 Loop over the format_string and return an iterable of tuples
141 (*literal_text*, *field_name*, *format_spec*, *conversion*). This is used
142 by :meth:`vformat` to break the string in to either literal text, or
143 replacement fields.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000144
Georg Brandle321c2f2008-05-12 16:45:43 +0000145 The values in the tuple conceptually represent a span of literal text
146 followed by a single replacement field. If there is no literal text
147 (which can happen if two replacement fields occur consecutively), then
148 *literal_text* will be a zero-length string. If there is no replacement
149 field, then the values of *field_name*, *format_spec* and *conversion*
150 will be ``None``.
151
152 .. method:: get_field(field_name, args, kwargs)
153
154 Given *field_name* as returned by :meth:`parse` (see above), convert it to
155 an object to be formatted. Returns a tuple (obj, used_key). The default
156 version takes strings of the form defined in :pep:`3101`, such as
157 "0[name]" or "label.title". *args* and *kwargs* are as passed in to
158 :meth:`vformat`. The return value *used_key* has the same meaning as the
159 *key* parameter to :meth:`get_value`.
160
161 .. method:: get_value(key, args, kwargs)
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000162
Georg Brandle321c2f2008-05-12 16:45:43 +0000163 Retrieve a given field value. The *key* argument will be either an
164 integer or a string. If it is an integer, it represents the index of the
165 positional argument in *args*; if it is a string, then it represents a
166 named argument in *kwargs*.
167
168 The *args* parameter is set to the list of positional arguments to
169 :meth:`vformat`, and the *kwargs* parameter is set to the dictionary of
170 keyword arguments.
171
172 For compound field names, these functions are only called for the first
173 component of the field name; Subsequent components are handled through
174 normal attribute and indexing operations.
175
176 So for example, the field expression '0.name' would cause
177 :meth:`get_value` to be called with a *key* argument of 0. The ``name``
178 attribute will be looked up after :meth:`get_value` returns by calling the
179 built-in :func:`getattr` function.
180
181 If the index or keyword refers to an item that does not exist, then an
182 :exc:`IndexError` or :exc:`KeyError` should be raised.
183
184 .. method:: check_unused_args(used_args, args, kwargs)
185
186 Implement checking for unused arguments if desired. The arguments to this
187 function is the set of all argument keys that were actually referred to in
188 the format string (integers for positional arguments, and strings for
189 named arguments), and a reference to the *args* and *kwargs* that was
190 passed to vformat. The set of unused args can be calculated from these
191 parameters. :meth:`check_unused_args` is assumed to throw an exception if
192 the check fails.
193
194 .. method:: format_field(value, format_spec)
195
196 :meth:`format_field` simply calls the global :func:`format` built-in. The
197 method is provided so that subclasses can override it.
198
199 .. method:: convert_field(value, conversion)
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000200
Georg Brandle321c2f2008-05-12 16:45:43 +0000201 Converts the value (returned by :meth:`get_field`) given a conversion type
202 (as in the tuple returned by the :meth:`parse` method.) The default
203 version understands 'r' (repr) and 's' (str) conversion types.
204
205
206.. _formatstrings:
207
208Format String Syntax
209--------------------
210
211The :meth:`str.format` method and the :class:`Formatter` class share the same
212syntax for format strings (although in the case of :class:`Formatter`,
213subclasses can define their own format string syntax.)
214
215Format strings contain "replacement fields" surrounded by curly braces ``{}``.
216Anything that is not contained in braces is considered literal text, which is
217copied unchanged to the output. If you need to include a brace character in the
218literal text, it can be escaped by doubling: ``{{`` and ``}}``.
219
220The grammar for a replacement field is as follows:
221
222 .. productionlist:: sf
223 replacement_field: "{" `field_name` ["!" `conversion`] [":" `format_spec`] "}"
Georg Brandl8cbe9552009-03-16 19:42:03 +0000224 field_name: (`identifier` | `integer`) ("." `attribute_name` | "[" `element_index` "]")*
Georg Brandle321c2f2008-05-12 16:45:43 +0000225 attribute_name: `identifier`
226 element_index: `integer`
227 conversion: "r" | "s"
228 format_spec: <described in the next section>
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000229
Georg Brandle321c2f2008-05-12 16:45:43 +0000230In less formal terms, the replacement field starts with a *field_name*, which
231can either be a number (for a positional argument), or an identifier (for
232keyword arguments). Following this is an optional *conversion* field, which is
233preceded by an exclamation point ``'!'``, and a *format_spec*, which is preceded
234by a colon ``':'``.
235
236The *field_name* itself begins with either a number or a keyword. If it's a
237number, it refers to a positional argument, and if it's a keyword it refers to a
238named keyword argument. This can be followed by any number of index or
239attribute expressions. An expression of the form ``'.name'`` selects the named
240attribute using :func:`getattr`, while an expression of the form ``'[index]'``
241does an index lookup using :func:`__getitem__`.
242
243Some simple format string examples::
244
245 "First, thou shalt count to {0}" # References first positional argument
Benjamin Peterson0e928582009-03-28 19:16:10 +0000246 "Bring me a {}" # Implicitly references the first positional argument
Georg Brandle321c2f2008-05-12 16:45:43 +0000247 "My quest is {name}" # References keyword argument 'name'
248 "Weight in tons {0.weight}" # 'weight' attribute of first positional arg
249 "Units destroyed: {players[0]}" # First element of keyword argument 'players'.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000250
Georg Brandle321c2f2008-05-12 16:45:43 +0000251The *conversion* field causes a type coercion before formatting. Normally, the
252job of formatting a value is done by the :meth:`__format__` method of the value
253itself. However, in some cases it is desirable to force a type to be formatted
254as a string, overriding its own definition of formatting. By converting the
255value to a string before calling :meth:`__format__`, the normal formatting logic
256is bypassed.
257
258Two conversion flags are currently supported: ``'!s'`` which calls :func:`str`
259on the value, and ``'!r'`` which calls :func:`repr`.
260
261Some examples::
262
263 "Harold's a clever {0!s}" # Calls str() on the argument first
264 "Bring out the holy {name!r}" # Calls repr() on the argument first
265
266The *format_spec* field contains a specification of how the value should be
267presented, including such details as field width, alignment, padding, decimal
268precision and so on. Each value type can define it's own "formatting
269mini-language" or interpretation of the *format_spec*.
270
271Most built-in types support a common formatting mini-language, which is
272described in the next section.
273
274A *format_spec* field can also include nested replacement fields within it.
275These nested replacement fields can contain only a field name; conversion flags
276and format specifications are not allowed. The replacement fields within the
277format_spec are substituted before the *format_spec* string is interpreted.
278This allows the formatting of a value to be dynamically specified.
279
280For example, suppose you wanted to have a replacement field whose field width is
281determined by another variable::
282
283 "A man with two {0:{1}}".format("noses", 10)
284
285This would first evaluate the inner replacement field, making the format string
286effectively::
287
288 "A man with two {0:10}"
289
290Then the outer replacement field would be evaluated, producing::
291
292 "noses "
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000293
Benjamin Peterson90f36732008-07-12 20:16:19 +0000294Which is substituted into the string, yielding::
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000295
Georg Brandle321c2f2008-05-12 16:45:43 +0000296 "A man with two noses "
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000297
Georg Brandle321c2f2008-05-12 16:45:43 +0000298(The extra space is because we specified a field width of 10, and because left
299alignment is the default for strings.)
300
301
302.. _formatspec:
303
304Format Specification Mini-Language
305^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
306
307"Format specifications" are used within replacement fields contained within a
308format string to define how individual values are presented (see
309:ref:`formatstrings`.) They can also be passed directly to the builtin
310:func:`format` function. Each formattable type may define how the format
311specification is to be interpreted.
312
313Most built-in types implement the following options for format specifications,
314although some of the formatting options are only supported by the numeric types.
315
316A general convention is that an empty format string (``""``) produces the same
317result as if you had called :func:`str` on the value.
318
319The general form of a *standard format specifier* is:
320
321.. productionlist:: sf
Eric Smitha5fa5a22008-07-16 00:11:49 +0000322 format_spec: [[`fill`]`align`][`sign`][#][0][`width`][.`precision`][`type`]
Georg Brandle321c2f2008-05-12 16:45:43 +0000323 fill: <a character other than '}'>
324 align: "<" | ">" | "=" | "^"
325 sign: "+" | "-" | " "
326 width: `integer`
327 precision: `integer`
328 type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "x" | "X" | "%"
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000329
Georg Brandle321c2f2008-05-12 16:45:43 +0000330The *fill* character can be any character other than '}' (which signifies the
331end of the field). The presence of a fill character is signaled by the *next*
332character, which must be one of the alignment options. If the second character
333of *format_spec* is not a valid alignment option, then it is assumed that both
334the fill character and the alignment option are absent.
335
336The meaning of the various alignment options is as follows:
337
338 +---------+----------------------------------------------------------+
339 | Option | Meaning |
340 +=========+==========================================================+
341 | ``'<'`` | Forces the field to be left-aligned within the available |
342 | | space (This is the default.) |
343 +---------+----------------------------------------------------------+
344 | ``'>'`` | Forces the field to be right-aligned within the |
345 | | available space. |
346 +---------+----------------------------------------------------------+
347 | ``'='`` | Forces the padding to be placed after the sign (if any) |
348 | | but before the digits. This is used for printing fields |
349 | | in the form '+000000120'. This alignment option is only |
350 | | valid for numeric types. |
351 +---------+----------------------------------------------------------+
352 | ``'^'`` | Forces the field to be centered within the available |
353 | | space. |
354 +---------+----------------------------------------------------------+
355
356Note that unless a minimum field width is defined, the field width will always
357be the same size as the data to fill it, so that the alignment option has no
358meaning in this case.
359
360The *sign* option is only valid for number types, and can be one of the
361following:
362
363 +---------+----------------------------------------------------------+
364 | Option | Meaning |
365 +=========+==========================================================+
366 | ``'+'`` | indicates that a sign should be used for both |
367 | | positive as well as negative numbers. |
368 +---------+----------------------------------------------------------+
369 | ``'-'`` | indicates that a sign should be used only for negative |
370 | | numbers (this is the default behavior). |
371 +---------+----------------------------------------------------------+
372 | space | indicates that a leading space should be used on |
373 | | positive numbers, and a minus sign on negative numbers. |
374 +---------+----------------------------------------------------------+
375
Benjamin Petersonb535d322008-09-11 22:04:02 +0000376The ``'#'`` option is only valid for integers, and only for binary, octal, or
377hexadecimal output. If present, it specifies that the output will be prefixed
378by ``'0b'``, ``'0o'``, or ``'0x'``, respectively.
Eric Smitha5fa5a22008-07-16 00:11:49 +0000379
Georg Brandle321c2f2008-05-12 16:45:43 +0000380*width* is a decimal integer defining the minimum field width. If not
381specified, then the field width will be determined by the content.
382
383If the *width* field is preceded by a zero (``'0'``) character, this enables
384zero-padding. This is equivalent to an *alignment* type of ``'='`` and a *fill*
385character of ``'0'``.
386
387The *precision* is a decimal number indicating how many digits should be
Georg Brandlbf899812008-07-18 11:15:06 +0000388displayed after the decimal point for a floating point value formatted with
389``'f'`` and ``'F'``, or before and after the decimal point for a floating point
390value formatted with ``'g'`` or ``'G'``. For non-number types the field
391indicates the maximum field size - in other words, how many characters will be
392used from the field content. The *precision* is ignored for integer values.
Georg Brandle321c2f2008-05-12 16:45:43 +0000393
394Finally, the *type* determines how the data should be presented.
395
396The available integer presentation types are:
397
398 +---------+----------------------------------------------------------+
399 | Type | Meaning |
400 +=========+==========================================================+
Eric Smitha5fa5a22008-07-16 00:11:49 +0000401 | ``'b'`` | Binary format. Outputs the number in base 2. |
Georg Brandle321c2f2008-05-12 16:45:43 +0000402 +---------+----------------------------------------------------------+
403 | ``'c'`` | Character. Converts the integer to the corresponding |
404 | | unicode character before printing. |
405 +---------+----------------------------------------------------------+
406 | ``'d'`` | Decimal Integer. Outputs the number in base 10. |
407 +---------+----------------------------------------------------------+
408 | ``'o'`` | Octal format. Outputs the number in base 8. |
409 +---------+----------------------------------------------------------+
410 | ``'x'`` | Hex format. Outputs the number in base 16, using lower- |
411 | | case letters for the digits above 9. |
412 +---------+----------------------------------------------------------+
413 | ``'X'`` | Hex format. Outputs the number in base 16, using upper- |
414 | | case letters for the digits above 9. |
415 +---------+----------------------------------------------------------+
416 | ``'n'`` | Number. This is the same as ``'d'``, except that it uses |
417 | | the current locale setting to insert the appropriate |
418 | | number separator characters. |
419 +---------+----------------------------------------------------------+
Georg Brandlbf899812008-07-18 11:15:06 +0000420 | None | The same as ``'d'``. |
Georg Brandle321c2f2008-05-12 16:45:43 +0000421 +---------+----------------------------------------------------------+
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000422
Georg Brandle321c2f2008-05-12 16:45:43 +0000423The available presentation types for floating point and decimal values are:
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000424
Georg Brandle321c2f2008-05-12 16:45:43 +0000425 +---------+----------------------------------------------------------+
426 | Type | Meaning |
427 +=========+==========================================================+
428 | ``'e'`` | Exponent notation. Prints the number in scientific |
429 | | notation using the letter 'e' to indicate the exponent. |
430 +---------+----------------------------------------------------------+
Eric Smithd6c393a2008-07-17 19:49:47 +0000431 | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an |
432 | | upper case 'E' as the separator character. |
Georg Brandle321c2f2008-05-12 16:45:43 +0000433 +---------+----------------------------------------------------------+
434 | ``'f'`` | Fixed point. Displays the number as a fixed-point |
435 | | number. |
436 +---------+----------------------------------------------------------+
Eric Smithd6c393a2008-07-17 19:49:47 +0000437 | ``'F'`` | Fixed point. Same as ``'f'``. |
Georg Brandle321c2f2008-05-12 16:45:43 +0000438 +---------+----------------------------------------------------------+
439 | ``'g'`` | General format. This prints the number as a fixed-point |
440 | | number, unless the number is too large, in which case |
Georg Brandlbf899812008-07-18 11:15:06 +0000441 | | it switches to ``'e'`` exponent notation. Infinity and |
442 | | NaN values are formatted as ``inf``, ``-inf`` and |
443 | | ``nan``, respectively. |
Georg Brandle321c2f2008-05-12 16:45:43 +0000444 +---------+----------------------------------------------------------+
445 | ``'G'`` | General format. Same as ``'g'`` except switches to |
Georg Brandlbf899812008-07-18 11:15:06 +0000446 | | ``'E'`` if the number gets to large. The representations |
447 | | of infinity and NaN are uppercased, too. |
Georg Brandle321c2f2008-05-12 16:45:43 +0000448 +---------+----------------------------------------------------------+
449 | ``'n'`` | Number. This is the same as ``'g'``, except that it uses |
450 | | the current locale setting to insert the appropriate |
451 | | number separator characters. |
452 +---------+----------------------------------------------------------+
453 | ``'%'`` | Percentage. Multiplies the number by 100 and displays |
454 | | in fixed (``'f'``) format, followed by a percent sign. |
455 +---------+----------------------------------------------------------+
Georg Brandlbf899812008-07-18 11:15:06 +0000456 | None | The same as ``'g'``. |
Georg Brandle321c2f2008-05-12 16:45:43 +0000457 +---------+----------------------------------------------------------+
458
459
Georg Brandl8ec7f652007-08-15 14:28:01 +0000460Template strings
461----------------
462
463Templates provide simpler string substitutions as described in :pep:`292`.
464Instead of the normal ``%``\ -based substitutions, Templates support ``$``\
465-based substitutions, using the following rules:
466
467* ``$$`` is an escape; it is replaced with a single ``$``.
468
469* ``$identifier`` names a substitution placeholder matching a mapping key of
470 ``"identifier"``. By default, ``"identifier"`` must spell a Python
471 identifier. The first non-identifier character after the ``$`` character
472 terminates this placeholder specification.
473
474* ``${identifier}`` is equivalent to ``$identifier``. It is required when valid
475 identifier characters follow the placeholder but are not part of the
476 placeholder, such as ``"${noun}ification"``.
477
478Any other appearance of ``$`` in the string will result in a :exc:`ValueError`
479being raised.
480
481.. versionadded:: 2.4
482
483The :mod:`string` module provides a :class:`Template` class that implements
484these rules. The methods of :class:`Template` are:
485
486
487.. class:: Template(template)
488
489 The constructor takes a single argument which is the template string.
490
491
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000492 .. method:: substitute(mapping[, **kws])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000493
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000494 Performs the template substitution, returning a new string. *mapping* is
495 any dictionary-like object with keys that match the placeholders in the
496 template. Alternatively, you can provide keyword arguments, where the
497 keywords are the placeholders. When both *mapping* and *kws* are given
498 and there are duplicates, the placeholders from *kws* take precedence.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000499
500
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000501 .. method:: safe_substitute(mapping[, **kws])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000502
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000503 Like :meth:`substitute`, except that if placeholders are missing from
504 *mapping* and *kws*, instead of raising a :exc:`KeyError` exception, the
505 original placeholder will appear in the resulting string intact. Also,
506 unlike with :meth:`substitute`, any other appearances of the ``$`` will
507 simply return ``$`` instead of raising :exc:`ValueError`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000508
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000509 While other exceptions may still occur, this method is called "safe"
510 because substitutions always tries to return a usable string instead of
511 raising an exception. In another sense, :meth:`safe_substitute` may be
512 anything other than safe, since it will silently ignore malformed
513 templates containing dangling delimiters, unmatched braces, or
514 placeholders that are not valid Python identifiers.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000515
516:class:`Template` instances also provide one public data attribute:
517
518
519.. attribute:: string.template
520
521 This is the object passed to the constructor's *template* argument. In general,
522 you shouldn't change it, but read-only access is not enforced.
523
Georg Brandle8f1b002008-03-22 22:04:10 +0000524Here is an example of how to use a Template:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000525
526 >>> from string import Template
527 >>> s = Template('$who likes $what')
528 >>> s.substitute(who='tim', what='kung pao')
529 'tim likes kung pao'
530 >>> d = dict(who='tim')
531 >>> Template('Give $who $100').substitute(d)
532 Traceback (most recent call last):
533 [...]
534 ValueError: Invalid placeholder in string: line 1, col 10
535 >>> Template('$who likes $what').substitute(d)
536 Traceback (most recent call last):
537 [...]
538 KeyError: 'what'
539 >>> Template('$who likes $what').safe_substitute(d)
540 'tim likes $what'
541
542Advanced usage: you can derive subclasses of :class:`Template` to customize the
543placeholder syntax, delimiter character, or the entire regular expression used
544to parse template strings. To do this, you can override these class attributes:
545
546* *delimiter* -- This is the literal string describing a placeholder introducing
547 delimiter. The default value ``$``. Note that this should *not* be a regular
548 expression, as the implementation will call :meth:`re.escape` on this string as
549 needed.
550
551* *idpattern* -- This is the regular expression describing the pattern for
552 non-braced placeholders (the braces will be added automatically as
553 appropriate). The default value is the regular expression
554 ``[_a-z][_a-z0-9]*``.
555
556Alternatively, you can provide the entire regular expression pattern by
557overriding the class attribute *pattern*. If you do this, the value must be a
558regular expression object with four named capturing groups. The capturing
559groups correspond to the rules given above, along with the invalid placeholder
560rule:
561
562* *escaped* -- This group matches the escape sequence, e.g. ``$$``, in the
563 default pattern.
564
565* *named* -- This group matches the unbraced placeholder name; it should not
566 include the delimiter in capturing group.
567
568* *braced* -- This group matches the brace enclosed placeholder name; it should
569 not include either the delimiter or braces in the capturing group.
570
571* *invalid* -- This group matches any other delimiter pattern (usually a single
572 delimiter), and it should appear last in the regular expression.
573
574
575String functions
576----------------
577
578The following functions are available to operate on string and Unicode objects.
579They are not available as string methods.
580
581
582.. function:: capwords(s)
583
584 Split the argument into words using :func:`split`, capitalize each word using
585 :func:`capitalize`, and join the capitalized words using :func:`join`. Note
586 that this replaces runs of whitespace characters by a single space, and removes
587 leading and trailing whitespace.
588
589
590.. function:: maketrans(from, to)
591
592 Return a translation table suitable for passing to :func:`translate`, that will
593 map each character in *from* into the character at the same position in *to*;
594 *from* and *to* must have the same length.
595
596 .. warning::
597
598 Don't use strings derived from :const:`lowercase` and :const:`uppercase` as
599 arguments; in some locales, these don't have the same length. For case
Georg Brandld5ad6da2009-03-04 18:24:41 +0000600 conversions, always use :meth:`str.lower` and :meth:`str.upper`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000601
602
603Deprecated string functions
604---------------------------
605
606The following list of functions are also defined as methods of string and
607Unicode objects; see section :ref:`string-methods` for more information on
608those. You should consider these functions as deprecated, although they will
609not be removed until Python 3.0. The functions defined in this module are:
610
611
612.. function:: atof(s)
613
614 .. deprecated:: 2.0
615 Use the :func:`float` built-in function.
616
617 .. index:: builtin: float
618
619 Convert a string to a floating point number. The string must have the standard
620 syntax for a floating point literal in Python, optionally preceded by a sign
621 (``+`` or ``-``). Note that this behaves identical to the built-in function
622 :func:`float` when passed a string.
623
624 .. note::
625
626 .. index::
627 single: NaN
628 single: Infinity
629
630 When passing in a string, values for NaN and Infinity may be returned, depending
631 on the underlying C library. The specific set of strings accepted which cause
632 these values to be returned depends entirely on the C library and is known to
633 vary.
634
635
636.. function:: atoi(s[, base])
637
638 .. deprecated:: 2.0
639 Use the :func:`int` built-in function.
640
641 .. index:: builtin: eval
642
643 Convert string *s* to an integer in the given *base*. The string must consist
644 of one or more digits, optionally preceded by a sign (``+`` or ``-``). The
645 *base* defaults to 10. If it is 0, a default base is chosen depending on the
646 leading characters of the string (after stripping the sign): ``0x`` or ``0X``
647 means 16, ``0`` means 8, anything else means 10. If *base* is 16, a leading
648 ``0x`` or ``0X`` is always accepted, though not required. This behaves
649 identically to the built-in function :func:`int` when passed a string. (Also
650 note: for a more flexible interpretation of numeric literals, use the built-in
651 function :func:`eval`.)
652
653
654.. function:: atol(s[, base])
655
656 .. deprecated:: 2.0
657 Use the :func:`long` built-in function.
658
659 .. index:: builtin: long
660
661 Convert string *s* to a long integer in the given *base*. The string must
662 consist of one or more digits, optionally preceded by a sign (``+`` or ``-``).
663 The *base* argument has the same meaning as for :func:`atoi`. A trailing ``l``
664 or ``L`` is not allowed, except if the base is 0. Note that when invoked
665 without *base* or with *base* set to 10, this behaves identical to the built-in
666 function :func:`long` when passed a string.
667
668
669.. function:: capitalize(word)
670
671 Return a copy of *word* with only its first character capitalized.
672
673
674.. function:: expandtabs(s[, tabsize])
675
676 Expand tabs in a string replacing them by one or more spaces, depending on the
677 current column and the given tab size. The column number is reset to zero after
678 each newline occurring in the string. This doesn't understand other non-printing
679 characters or escape sequences. The tab size defaults to 8.
680
681
682.. function:: find(s, sub[, start[,end]])
683
684 Return the lowest index in *s* where the substring *sub* is found such that
685 *sub* is wholly contained in ``s[start:end]``. Return ``-1`` on failure.
686 Defaults for *start* and *end* and interpretation of negative values is the same
687 as for slices.
688
689
690.. function:: rfind(s, sub[, start[, end]])
691
692 Like :func:`find` but find the highest index.
693
694
695.. function:: index(s, sub[, start[, end]])
696
697 Like :func:`find` but raise :exc:`ValueError` when the substring is not found.
698
699
700.. function:: rindex(s, sub[, start[, end]])
701
702 Like :func:`rfind` but raise :exc:`ValueError` when the substring is not found.
703
704
705.. function:: count(s, sub[, start[, end]])
706
707 Return the number of (non-overlapping) occurrences of substring *sub* in string
708 ``s[start:end]``. Defaults for *start* and *end* and interpretation of negative
709 values are the same as for slices.
710
711
712.. function:: lower(s)
713
714 Return a copy of *s*, but with upper case letters converted to lower case.
715
716
717.. function:: split(s[, sep[, maxsplit]])
718
719 Return a list of the words of the string *s*. If the optional second argument
720 *sep* is absent or ``None``, the words are separated by arbitrary strings of
721 whitespace characters (space, tab, newline, return, formfeed). If the second
722 argument *sep* is present and not ``None``, it specifies a string to be used as
723 the word separator. The returned list will then have one more item than the
724 number of non-overlapping occurrences of the separator in the string. The
725 optional third argument *maxsplit* defaults to 0. If it is nonzero, at most
726 *maxsplit* number of splits occur, and the remainder of the string is returned
727 as the final element of the list (thus, the list will have at most
728 ``maxsplit+1`` elements).
729
730 The behavior of split on an empty string depends on the value of *sep*. If *sep*
731 is not specified, or specified as ``None``, the result will be an empty list.
732 If *sep* is specified as any string, the result will be a list containing one
733 element which is an empty string.
734
735
736.. function:: rsplit(s[, sep[, maxsplit]])
737
738 Return a list of the words of the string *s*, scanning *s* from the end. To all
739 intents and purposes, the resulting list of words is the same as returned by
740 :func:`split`, except when the optional third argument *maxsplit* is explicitly
741 specified and nonzero. When *maxsplit* is nonzero, at most *maxsplit* number of
742 splits -- the *rightmost* ones -- occur, and the remainder of the string is
743 returned as the first element of the list (thus, the list will have at most
744 ``maxsplit+1`` elements).
745
746 .. versionadded:: 2.4
747
748
749.. function:: splitfields(s[, sep[, maxsplit]])
750
751 This function behaves identically to :func:`split`. (In the past, :func:`split`
752 was only used with one argument, while :func:`splitfields` was only used with
753 two arguments.)
754
755
756.. function:: join(words[, sep])
757
758 Concatenate a list or tuple of words with intervening occurrences of *sep*.
759 The default value for *sep* is a single space character. It is always true that
760 ``string.join(string.split(s, sep), sep)`` equals *s*.
761
762
763.. function:: joinfields(words[, sep])
764
765 This function behaves identically to :func:`join`. (In the past, :func:`join`
766 was only used with one argument, while :func:`joinfields` was only used with two
767 arguments.) Note that there is no :meth:`joinfields` method on string objects;
768 use the :meth:`join` method instead.
769
770
771.. function:: lstrip(s[, chars])
772
773 Return a copy of the string with leading characters removed. If *chars* is
774 omitted or ``None``, whitespace characters are removed. If given and not
775 ``None``, *chars* must be a string; the characters in the string will be
776 stripped from the beginning of the string this method is called on.
777
778 .. versionchanged:: 2.2.3
779 The *chars* parameter was added. The *chars* parameter cannot be passed in
780 earlier 2.2 versions.
781
782
783.. function:: rstrip(s[, chars])
784
785 Return a copy of the string with trailing characters removed. If *chars* is
786 omitted or ``None``, whitespace characters are removed. If given and not
787 ``None``, *chars* must be a string; the characters in the string will be
788 stripped from the end of the string this method is called on.
789
790 .. versionchanged:: 2.2.3
791 The *chars* parameter was added. The *chars* parameter cannot be passed in
792 earlier 2.2 versions.
793
794
795.. function:: strip(s[, chars])
796
797 Return a copy of the string with leading and trailing characters removed. If
798 *chars* is omitted or ``None``, whitespace characters are removed. If given and
799 not ``None``, *chars* must be a string; the characters in the string will be
800 stripped from the both ends of the string this method is called on.
801
802 .. versionchanged:: 2.2.3
803 The *chars* parameter was added. The *chars* parameter cannot be passed in
804 earlier 2.2 versions.
805
806
807.. function:: swapcase(s)
808
809 Return a copy of *s*, but with lower case letters converted to upper case and
810 vice versa.
811
812
813.. function:: translate(s, table[, deletechars])
814
815 Delete all characters from *s* that are in *deletechars* (if present), and then
816 translate the characters using *table*, which must be a 256-character string
817 giving the translation for each character value, indexed by its ordinal. If
818 *table* is ``None``, then only the character deletion step is performed.
819
820
821.. function:: upper(s)
822
823 Return a copy of *s*, but with lower case letters converted to upper case.
824
825
826.. function:: ljust(s, width)
827 rjust(s, width)
828 center(s, width)
829
830 These functions respectively left-justify, right-justify and center a string in
831 a field of given width. They return a string that is at least *width*
832 characters wide, created by padding the string *s* with spaces until the given
833 width on the right, left or both sides. The string is never truncated.
834
835
836.. function:: zfill(s, width)
837
838 Pad a numeric string on the left with zero digits until the given width is
839 reached. Strings starting with a sign are handled correctly.
840
841
842.. function:: replace(str, old, new[, maxreplace])
843
844 Return a copy of string *str* with all occurrences of substring *old* replaced
845 by *new*. If the optional argument *maxreplace* is given, the first
846 *maxreplace* occurrences are replaced.
847