blob: 37e8e64ac07c97ace0b80a6daca22fca4473cfef [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 Brandl40e15ed2009-04-05 21:48:06 +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 Brandl40e15ed2009-04-05 21:48:06 +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 Brandl40e15ed2009-04-05 21:48:06 +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
Georg Brandl953fe5f2010-03-21 19:06:51 +0000108.. versionadded:: 2.6
109
110The built-in str and unicode classes provide the ability
Benjamin Petersonc15205e2008-05-25 20:05:52 +0000111to do complex variable substitutions and value formatting via the
112:meth:`str.format` method described in :pep:`3101`. The :class:`Formatter`
113class in the :mod:`string` module allows you to create and customize your own
114string formatting behaviors using the same implementation as the built-in
Georg Brandle321c2f2008-05-12 16:45:43 +0000115:meth:`format` method.
116
117.. class:: Formatter
118
119 The :class:`Formatter` class has the following public methods:
120
121 .. method:: format(format_string, *args, *kwargs)
122
123 :meth:`format` is the primary API method. It takes a format template
124 string, and an arbitrary set of positional and keyword argument.
125 :meth:`format` is just a wrapper that calls :meth:`vformat`.
126
127 .. method:: vformat(format_string, args, kwargs)
Georg Brandl734373c2009-01-03 21:55:17 +0000128
Georg Brandle321c2f2008-05-12 16:45:43 +0000129 This function does the actual work of formatting. It is exposed as a
130 separate function for cases where you want to pass in a predefined
131 dictionary of arguments, rather than unpacking and repacking the
132 dictionary as individual arguments using the ``*args`` and ``**kwds``
133 syntax. :meth:`vformat` does the work of breaking up the format template
134 string into character data and replacement fields. It calls the various
135 methods described below.
136
137 In addition, the :class:`Formatter` defines a number of methods that are
138 intended to be replaced by subclasses:
139
140 .. method:: parse(format_string)
Georg Brandl734373c2009-01-03 21:55:17 +0000141
Georg Brandle321c2f2008-05-12 16:45:43 +0000142 Loop over the format_string and return an iterable of tuples
143 (*literal_text*, *field_name*, *format_spec*, *conversion*). This is used
144 by :meth:`vformat` to break the string in to either literal text, or
145 replacement fields.
Georg Brandl734373c2009-01-03 21:55:17 +0000146
Georg Brandle321c2f2008-05-12 16:45:43 +0000147 The values in the tuple conceptually represent a span of literal text
148 followed by a single replacement field. If there is no literal text
149 (which can happen if two replacement fields occur consecutively), then
150 *literal_text* will be a zero-length string. If there is no replacement
151 field, then the values of *field_name*, *format_spec* and *conversion*
152 will be ``None``.
153
154 .. method:: get_field(field_name, args, kwargs)
155
156 Given *field_name* as returned by :meth:`parse` (see above), convert it to
157 an object to be formatted. Returns a tuple (obj, used_key). The default
158 version takes strings of the form defined in :pep:`3101`, such as
159 "0[name]" or "label.title". *args* and *kwargs* are as passed in to
160 :meth:`vformat`. The return value *used_key* has the same meaning as the
161 *key* parameter to :meth:`get_value`.
162
163 .. method:: get_value(key, args, kwargs)
Georg Brandl734373c2009-01-03 21:55:17 +0000164
Georg Brandle321c2f2008-05-12 16:45:43 +0000165 Retrieve a given field value. The *key* argument will be either an
166 integer or a string. If it is an integer, it represents the index of the
167 positional argument in *args*; if it is a string, then it represents a
168 named argument in *kwargs*.
169
170 The *args* parameter is set to the list of positional arguments to
171 :meth:`vformat`, and the *kwargs* parameter is set to the dictionary of
172 keyword arguments.
173
174 For compound field names, these functions are only called for the first
175 component of the field name; Subsequent components are handled through
176 normal attribute and indexing operations.
177
178 So for example, the field expression '0.name' would cause
179 :meth:`get_value` to be called with a *key* argument of 0. The ``name``
180 attribute will be looked up after :meth:`get_value` returns by calling the
181 built-in :func:`getattr` function.
182
183 If the index or keyword refers to an item that does not exist, then an
184 :exc:`IndexError` or :exc:`KeyError` should be raised.
185
186 .. method:: check_unused_args(used_args, args, kwargs)
187
188 Implement checking for unused arguments if desired. The arguments to this
189 function is the set of all argument keys that were actually referred to in
190 the format string (integers for positional arguments, and strings for
191 named arguments), and a reference to the *args* and *kwargs* that was
192 passed to vformat. The set of unused args can be calculated from these
193 parameters. :meth:`check_unused_args` is assumed to throw an exception if
194 the check fails.
195
196 .. method:: format_field(value, format_spec)
197
198 :meth:`format_field` simply calls the global :func:`format` built-in. The
199 method is provided so that subclasses can override it.
200
201 .. method:: convert_field(value, conversion)
Georg Brandl734373c2009-01-03 21:55:17 +0000202
Georg Brandle321c2f2008-05-12 16:45:43 +0000203 Converts the value (returned by :meth:`get_field`) given a conversion type
204 (as in the tuple returned by the :meth:`parse` method.) The default
205 version understands 'r' (repr) and 's' (str) conversion types.
206
207
208.. _formatstrings:
209
210Format String Syntax
211--------------------
212
213The :meth:`str.format` method and the :class:`Formatter` class share the same
214syntax for format strings (although in the case of :class:`Formatter`,
215subclasses can define their own format string syntax.)
216
217Format strings contain "replacement fields" surrounded by curly braces ``{}``.
218Anything that is not contained in braces is considered literal text, which is
219copied unchanged to the output. If you need to include a brace character in the
220literal text, it can be escaped by doubling: ``{{`` and ``}}``.
221
222The grammar for a replacement field is as follows:
223
224 .. productionlist:: sf
225 replacement_field: "{" `field_name` ["!" `conversion`] [":" `format_spec`] "}"
Georg Brandl40e15ed2009-04-05 21:48:06 +0000226 field_name: (`identifier` | `integer`) ("." `attribute_name` | "[" `element_index` "]")*
Georg Brandle321c2f2008-05-12 16:45:43 +0000227 attribute_name: `identifier`
Eric Smith5a896782010-02-25 14:55:41 +0000228 element_index: `integer` | `index_string`
229 index_string: <any source character except "]"> +
Georg Brandle321c2f2008-05-12 16:45:43 +0000230 conversion: "r" | "s"
231 format_spec: <described in the next section>
Georg Brandl734373c2009-01-03 21:55:17 +0000232
Georg Brandle321c2f2008-05-12 16:45:43 +0000233In less formal terms, the replacement field starts with a *field_name*, which
234can either be a number (for a positional argument), or an identifier (for
235keyword arguments). Following this is an optional *conversion* field, which is
236preceded by an exclamation point ``'!'``, and a *format_spec*, which is preceded
237by a colon ``':'``.
238
239The *field_name* itself begins with either a number or a keyword. If it's a
240number, it refers to a positional argument, and if it's a keyword it refers to a
241named keyword argument. This can be followed by any number of index or
242attribute expressions. An expression of the form ``'.name'`` selects the named
243attribute using :func:`getattr`, while an expression of the form ``'[index]'``
244does an index lookup using :func:`__getitem__`.
245
246Some simple format string examples::
247
248 "First, thou shalt count to {0}" # References first positional argument
249 "My quest is {name}" # References keyword argument 'name'
250 "Weight in tons {0.weight}" # 'weight' attribute of first positional arg
251 "Units destroyed: {players[0]}" # First element of keyword argument 'players'.
Georg Brandl734373c2009-01-03 21:55:17 +0000252
Georg Brandle321c2f2008-05-12 16:45:43 +0000253The *conversion* field causes a type coercion before formatting. Normally, the
254job of formatting a value is done by the :meth:`__format__` method of the value
255itself. However, in some cases it is desirable to force a type to be formatted
256as a string, overriding its own definition of formatting. By converting the
257value to a string before calling :meth:`__format__`, the normal formatting logic
258is bypassed.
259
260Two conversion flags are currently supported: ``'!s'`` which calls :func:`str`
261on the value, and ``'!r'`` which calls :func:`repr`.
262
263Some examples::
264
265 "Harold's a clever {0!s}" # Calls str() on the argument first
266 "Bring out the holy {name!r}" # Calls repr() on the argument first
267
268The *format_spec* field contains a specification of how the value should be
269presented, including such details as field width, alignment, padding, decimal
Eric Smith7b12cce2010-02-15 11:56:37 +0000270precision and so on. Each value type can define its own "formatting
Georg Brandle321c2f2008-05-12 16:45:43 +0000271mini-language" or interpretation of the *format_spec*.
272
273Most built-in types support a common formatting mini-language, which is
274described in the next section.
275
276A *format_spec* field can also include nested replacement fields within it.
277These nested replacement fields can contain only a field name; conversion flags
278and format specifications are not allowed. The replacement fields within the
279format_spec are substituted before the *format_spec* string is interpreted.
280This allows the formatting of a value to be dynamically specified.
281
282For example, suppose you wanted to have a replacement field whose field width is
283determined by another variable::
284
285 "A man with two {0:{1}}".format("noses", 10)
286
287This would first evaluate the inner replacement field, making the format string
288effectively::
289
290 "A man with two {0:10}"
291
292Then the outer replacement field would be evaluated, producing::
293
294 "noses "
Georg Brandl734373c2009-01-03 21:55:17 +0000295
Benjamin Peterson90f36732008-07-12 20:16:19 +0000296Which is substituted into the string, yielding::
Georg Brandl734373c2009-01-03 21:55:17 +0000297
Georg Brandle321c2f2008-05-12 16:45:43 +0000298 "A man with two noses "
Georg Brandl734373c2009-01-03 21:55:17 +0000299
Georg Brandle321c2f2008-05-12 16:45:43 +0000300(The extra space is because we specified a field width of 10, and because left
301alignment is the default for strings.)
302
303
304.. _formatspec:
305
306Format Specification Mini-Language
307^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
308
309"Format specifications" are used within replacement fields contained within a
310format string to define how individual values are presented (see
Georg Brandl4ae4f872009-10-27 14:37:48 +0000311:ref:`formatstrings`.) They can also be passed directly to the built-in
Georg Brandle321c2f2008-05-12 16:45:43 +0000312:func:`format` function. Each formattable type may define how the format
313specification is to be interpreted.
314
315Most built-in types implement the following options for format specifications,
316although some of the formatting options are only supported by the numeric types.
317
Eric Smithf34bef22010-02-25 14:16:46 +0000318A general convention is that an empty format string (``""``) produces
319the same result as if you had called :func:`str` on the value. A
320non-empty format string typically modifies the result.
Georg Brandle321c2f2008-05-12 16:45:43 +0000321
322The general form of a *standard format specifier* is:
323
324.. productionlist:: sf
Eric Smitha5fa5a22008-07-16 00:11:49 +0000325 format_spec: [[`fill`]`align`][`sign`][#][0][`width`][.`precision`][`type`]
Georg Brandle321c2f2008-05-12 16:45:43 +0000326 fill: <a character other than '}'>
327 align: "<" | ">" | "=" | "^"
328 sign: "+" | "-" | " "
329 width: `integer`
330 precision: `integer`
Eric Smithf34bef22010-02-25 14:16:46 +0000331 type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
Georg Brandl734373c2009-01-03 21:55:17 +0000332
Georg Brandle321c2f2008-05-12 16:45:43 +0000333The *fill* character can be any character other than '}' (which signifies the
334end of the field). The presence of a fill character is signaled by the *next*
335character, which must be one of the alignment options. If the second character
336of *format_spec* is not a valid alignment option, then it is assumed that both
337the fill character and the alignment option are absent.
338
339The meaning of the various alignment options is as follows:
340
341 +---------+----------------------------------------------------------+
342 | Option | Meaning |
343 +=========+==========================================================+
344 | ``'<'`` | Forces the field to be left-aligned within the available |
345 | | space (This is the default.) |
346 +---------+----------------------------------------------------------+
347 | ``'>'`` | Forces the field to be right-aligned within the |
348 | | available space. |
349 +---------+----------------------------------------------------------+
350 | ``'='`` | Forces the padding to be placed after the sign (if any) |
351 | | but before the digits. This is used for printing fields |
352 | | in the form '+000000120'. This alignment option is only |
353 | | valid for numeric types. |
354 +---------+----------------------------------------------------------+
355 | ``'^'`` | Forces the field to be centered within the available |
356 | | space. |
357 +---------+----------------------------------------------------------+
358
359Note that unless a minimum field width is defined, the field width will always
360be the same size as the data to fill it, so that the alignment option has no
361meaning in this case.
362
363The *sign* option is only valid for number types, and can be one of the
364following:
365
366 +---------+----------------------------------------------------------+
367 | Option | Meaning |
368 +=========+==========================================================+
369 | ``'+'`` | indicates that a sign should be used for both |
370 | | positive as well as negative numbers. |
371 +---------+----------------------------------------------------------+
372 | ``'-'`` | indicates that a sign should be used only for negative |
373 | | numbers (this is the default behavior). |
374 +---------+----------------------------------------------------------+
375 | space | indicates that a leading space should be used on |
376 | | positive numbers, and a minus sign on negative numbers. |
377 +---------+----------------------------------------------------------+
378
Benjamin Petersonb535d322008-09-11 22:04:02 +0000379The ``'#'`` option is only valid for integers, and only for binary, octal, or
380hexadecimal output. If present, it specifies that the output will be prefixed
381by ``'0b'``, ``'0o'``, or ``'0x'``, respectively.
Eric Smitha5fa5a22008-07-16 00:11:49 +0000382
Georg Brandle321c2f2008-05-12 16:45:43 +0000383*width* is a decimal integer defining the minimum field width. If not
384specified, then the field width will be determined by the content.
385
386If the *width* field is preceded by a zero (``'0'``) character, this enables
387zero-padding. This is equivalent to an *alignment* type of ``'='`` and a *fill*
388character of ``'0'``.
389
390The *precision* is a decimal number indicating how many digits should be
Georg Brandlbf899812008-07-18 11:15:06 +0000391displayed after the decimal point for a floating point value formatted with
392``'f'`` and ``'F'``, or before and after the decimal point for a floating point
393value formatted with ``'g'`` or ``'G'``. For non-number types the field
394indicates the maximum field size - in other words, how many characters will be
Eric Smith98ff81d2009-05-07 19:37:22 +0000395used from the field content. The *precision* is not allowed for integer values.
Georg Brandle321c2f2008-05-12 16:45:43 +0000396
397Finally, the *type* determines how the data should be presented.
398
Eric Smithf34bef22010-02-25 14:16:46 +0000399The available string presentation types are:
400
401 +---------+----------------------------------------------------------+
402 | Type | Meaning |
403 +=========+==========================================================+
404 | ``'s'`` | String format. This is the default type for strings and |
405 | | may be omitted. |
406 +---------+----------------------------------------------------------+
407 | None | The same as ``'s'``. |
408 +---------+----------------------------------------------------------+
409
Georg Brandle321c2f2008-05-12 16:45:43 +0000410The available integer presentation types are:
411
412 +---------+----------------------------------------------------------+
413 | Type | Meaning |
414 +=========+==========================================================+
Eric Smitha5fa5a22008-07-16 00:11:49 +0000415 | ``'b'`` | Binary format. Outputs the number in base 2. |
Georg Brandle321c2f2008-05-12 16:45:43 +0000416 +---------+----------------------------------------------------------+
417 | ``'c'`` | Character. Converts the integer to the corresponding |
418 | | unicode character before printing. |
419 +---------+----------------------------------------------------------+
420 | ``'d'`` | Decimal Integer. Outputs the number in base 10. |
421 +---------+----------------------------------------------------------+
422 | ``'o'`` | Octal format. Outputs the number in base 8. |
423 +---------+----------------------------------------------------------+
424 | ``'x'`` | Hex format. Outputs the number in base 16, using lower- |
425 | | case letters for the digits above 9. |
426 +---------+----------------------------------------------------------+
427 | ``'X'`` | Hex format. Outputs the number in base 16, using upper- |
428 | | case letters for the digits above 9. |
429 +---------+----------------------------------------------------------+
430 | ``'n'`` | Number. This is the same as ``'d'``, except that it uses |
431 | | the current locale setting to insert the appropriate |
432 | | number separator characters. |
433 +---------+----------------------------------------------------------+
Georg Brandlbf899812008-07-18 11:15:06 +0000434 | None | The same as ``'d'``. |
Georg Brandle321c2f2008-05-12 16:45:43 +0000435 +---------+----------------------------------------------------------+
Georg Brandl734373c2009-01-03 21:55:17 +0000436
Eric Smithf34bef22010-02-25 14:16:46 +0000437In addition to the above presentation types, integers can be formatted
438with the floating point presentation types listed below (except
439``'n'`` and None). When doing so, :func:`float` is used to convert the
440integer to a floating point number before formatting.
441
Georg Brandle321c2f2008-05-12 16:45:43 +0000442The available presentation types for floating point and decimal values are:
Georg Brandl734373c2009-01-03 21:55:17 +0000443
Georg Brandle321c2f2008-05-12 16:45:43 +0000444 +---------+----------------------------------------------------------+
445 | Type | Meaning |
446 +=========+==========================================================+
447 | ``'e'`` | Exponent notation. Prints the number in scientific |
448 | | notation using the letter 'e' to indicate the exponent. |
449 +---------+----------------------------------------------------------+
Eric Smithd6c393a2008-07-17 19:49:47 +0000450 | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an |
451 | | upper case 'E' as the separator character. |
Georg Brandle321c2f2008-05-12 16:45:43 +0000452 +---------+----------------------------------------------------------+
453 | ``'f'`` | Fixed point. Displays the number as a fixed-point |
454 | | number. |
455 +---------+----------------------------------------------------------+
Eric Smithd6c393a2008-07-17 19:49:47 +0000456 | ``'F'`` | Fixed point. Same as ``'f'``. |
Georg Brandle321c2f2008-05-12 16:45:43 +0000457 +---------+----------------------------------------------------------+
Georg Brandl8a859452009-10-27 14:59:26 +0000458 | ``'g'`` | General format. For a given precision ``p >= 1``, |
459 | | this rounds the number to ``p`` significant digits and |
460 | | then formats the result in either fixed-point format |
461 | | or in scientific notation, depending on its magnitude. |
462 | | |
463 | | The precise rules are as follows: suppose that the |
464 | | result formatted with presentation type ``'e'`` and |
465 | | precision ``p-1`` would have exponent ``exp``. Then |
466 | | if ``-4 <= exp < p``, the number is formatted |
467 | | with presentation type ``'f'`` and precision |
468 | | ``p-1-exp``. Otherwise, the number is formatted |
469 | | with presentation type ``'e'`` and precision ``p-1``. |
470 | | In both cases insignificant trailing zeros are removed |
471 | | from the significand, and the decimal point is also |
472 | | removed if there are no remaining digits following it. |
473 | | |
474 | | Postive and negative infinity, positive and negative |
475 | | zero, and nans, are formatted as ``inf``, ``-inf``, |
476 | | ``0``, ``-0`` and ``nan`` respectively, regardless of |
477 | | the precision. |
478 | | |
479 | | A precision of ``0`` is treated as equivalent to a |
480 | | precision of ``1``. |
Georg Brandle321c2f2008-05-12 16:45:43 +0000481 +---------+----------------------------------------------------------+
482 | ``'G'`` | General format. Same as ``'g'`` except switches to |
Georg Brandl8a859452009-10-27 14:59:26 +0000483 | | ``'E'`` if the number gets too large. The |
484 | | representations of infinity and NaN are uppercased, too. |
Georg Brandle321c2f2008-05-12 16:45:43 +0000485 +---------+----------------------------------------------------------+
486 | ``'n'`` | Number. This is the same as ``'g'``, except that it uses |
487 | | the current locale setting to insert the appropriate |
488 | | number separator characters. |
489 +---------+----------------------------------------------------------+
490 | ``'%'`` | Percentage. Multiplies the number by 100 and displays |
491 | | in fixed (``'f'``) format, followed by a percent sign. |
492 +---------+----------------------------------------------------------+
Georg Brandlbf899812008-07-18 11:15:06 +0000493 | None | The same as ``'g'``. |
Georg Brandle321c2f2008-05-12 16:45:43 +0000494 +---------+----------------------------------------------------------+
495
496
Georg Brandl8ec7f652007-08-15 14:28:01 +0000497Template strings
498----------------
499
Georg Brandl953fe5f2010-03-21 19:06:51 +0000500.. versionadded:: 2.4
501
Georg Brandl8ec7f652007-08-15 14:28:01 +0000502Templates provide simpler string substitutions as described in :pep:`292`.
503Instead of the normal ``%``\ -based substitutions, Templates support ``$``\
504-based substitutions, using the following rules:
505
506* ``$$`` is an escape; it is replaced with a single ``$``.
507
508* ``$identifier`` names a substitution placeholder matching a mapping key of
509 ``"identifier"``. By default, ``"identifier"`` must spell a Python
510 identifier. The first non-identifier character after the ``$`` character
511 terminates this placeholder specification.
512
513* ``${identifier}`` is equivalent to ``$identifier``. It is required when valid
514 identifier characters follow the placeholder but are not part of the
515 placeholder, such as ``"${noun}ification"``.
516
517Any other appearance of ``$`` in the string will result in a :exc:`ValueError`
518being raised.
519
Georg Brandl8ec7f652007-08-15 14:28:01 +0000520The :mod:`string` module provides a :class:`Template` class that implements
521these rules. The methods of :class:`Template` are:
522
523
524.. class:: Template(template)
525
526 The constructor takes a single argument which is the template string.
527
528
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000529 .. method:: substitute(mapping[, **kws])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000530
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000531 Performs the template substitution, returning a new string. *mapping* is
532 any dictionary-like object with keys that match the placeholders in the
533 template. Alternatively, you can provide keyword arguments, where the
534 keywords are the placeholders. When both *mapping* and *kws* are given
535 and there are duplicates, the placeholders from *kws* take precedence.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000536
537
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000538 .. method:: safe_substitute(mapping[, **kws])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000539
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000540 Like :meth:`substitute`, except that if placeholders are missing from
541 *mapping* and *kws*, instead of raising a :exc:`KeyError` exception, the
542 original placeholder will appear in the resulting string intact. Also,
543 unlike with :meth:`substitute`, any other appearances of the ``$`` will
544 simply return ``$`` instead of raising :exc:`ValueError`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000545
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000546 While other exceptions may still occur, this method is called "safe"
547 because substitutions always tries to return a usable string instead of
548 raising an exception. In another sense, :meth:`safe_substitute` may be
549 anything other than safe, since it will silently ignore malformed
550 templates containing dangling delimiters, unmatched braces, or
551 placeholders that are not valid Python identifiers.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000552
Georg Brandl46d441e2010-03-21 19:01:15 +0000553 :class:`Template` instances also provide one public data attribute:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000554
Georg Brandl46d441e2010-03-21 19:01:15 +0000555 .. attribute:: template
Georg Brandl8ec7f652007-08-15 14:28:01 +0000556
Georg Brandl46d441e2010-03-21 19:01:15 +0000557 This is the object passed to the constructor's *template* argument. In
558 general, you shouldn't change it, but read-only access is not enforced.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000559
Georg Brandle8f1b002008-03-22 22:04:10 +0000560Here is an example of how to use a Template:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000561
562 >>> from string import Template
563 >>> s = Template('$who likes $what')
564 >>> s.substitute(who='tim', what='kung pao')
565 'tim likes kung pao'
566 >>> d = dict(who='tim')
567 >>> Template('Give $who $100').substitute(d)
568 Traceback (most recent call last):
569 [...]
570 ValueError: Invalid placeholder in string: line 1, col 10
571 >>> Template('$who likes $what').substitute(d)
572 Traceback (most recent call last):
573 [...]
574 KeyError: 'what'
575 >>> Template('$who likes $what').safe_substitute(d)
576 'tim likes $what'
577
578Advanced usage: you can derive subclasses of :class:`Template` to customize the
579placeholder syntax, delimiter character, or the entire regular expression used
580to parse template strings. To do this, you can override these class attributes:
581
582* *delimiter* -- This is the literal string describing a placeholder introducing
583 delimiter. The default value ``$``. Note that this should *not* be a regular
584 expression, as the implementation will call :meth:`re.escape` on this string as
585 needed.
586
587* *idpattern* -- This is the regular expression describing the pattern for
588 non-braced placeholders (the braces will be added automatically as
589 appropriate). The default value is the regular expression
590 ``[_a-z][_a-z0-9]*``.
591
592Alternatively, you can provide the entire regular expression pattern by
593overriding the class attribute *pattern*. If you do this, the value must be a
594regular expression object with four named capturing groups. The capturing
595groups correspond to the rules given above, along with the invalid placeholder
596rule:
597
598* *escaped* -- This group matches the escape sequence, e.g. ``$$``, in the
599 default pattern.
600
601* *named* -- This group matches the unbraced placeholder name; it should not
602 include the delimiter in capturing group.
603
604* *braced* -- This group matches the brace enclosed placeholder name; it should
605 not include either the delimiter or braces in the capturing group.
606
607* *invalid* -- This group matches any other delimiter pattern (usually a single
608 delimiter), and it should appear last in the regular expression.
609
610
611String functions
612----------------
613
614The following functions are available to operate on string and Unicode objects.
615They are not available as string methods.
616
617
Ezio Melotti9ba83c52009-09-26 11:23:16 +0000618.. function:: capwords(s[, sep])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000619
Ezio Melotti9ba83c52009-09-26 11:23:16 +0000620 Split the argument into words using :meth:`str.split`, capitalize each word
621 using :meth:`str.capitalize`, and join the capitalized words using
622 :meth:`str.join`. If the optional second argument *sep* is absent
623 or ``None``, runs of whitespace characters are replaced by a single space
624 and leading and trailing whitespace are removed, otherwise *sep* is used to
625 split and join the words.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000626
627
628.. function:: maketrans(from, to)
629
630 Return a translation table suitable for passing to :func:`translate`, that will
631 map each character in *from* into the character at the same position in *to*;
632 *from* and *to* must have the same length.
633
Georg Brandl38853142009-04-28 18:23:28 +0000634 .. note::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000635
636 Don't use strings derived from :const:`lowercase` and :const:`uppercase` as
637 arguments; in some locales, these don't have the same length. For case
Georg Brandl40e15ed2009-04-05 21:48:06 +0000638 conversions, always use :meth:`str.lower` and :meth:`str.upper`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000639
640
641Deprecated string functions
642---------------------------
643
644The following list of functions are also defined as methods of string and
645Unicode objects; see section :ref:`string-methods` for more information on
646those. You should consider these functions as deprecated, although they will
647not be removed until Python 3.0. The functions defined in this module are:
648
649
650.. function:: atof(s)
651
652 .. deprecated:: 2.0
653 Use the :func:`float` built-in function.
654
655 .. index:: builtin: float
656
657 Convert a string to a floating point number. The string must have the standard
658 syntax for a floating point literal in Python, optionally preceded by a sign
659 (``+`` or ``-``). Note that this behaves identical to the built-in function
660 :func:`float` when passed a string.
661
662 .. note::
663
664 .. index::
665 single: NaN
666 single: Infinity
667
668 When passing in a string, values for NaN and Infinity may be returned, depending
669 on the underlying C library. The specific set of strings accepted which cause
670 these values to be returned depends entirely on the C library and is known to
671 vary.
672
673
674.. function:: atoi(s[, base])
675
676 .. deprecated:: 2.0
677 Use the :func:`int` built-in function.
678
679 .. index:: builtin: eval
680
681 Convert string *s* to an integer in the given *base*. The string must consist
682 of one or more digits, optionally preceded by a sign (``+`` or ``-``). The
683 *base* defaults to 10. If it is 0, a default base is chosen depending on the
684 leading characters of the string (after stripping the sign): ``0x`` or ``0X``
685 means 16, ``0`` means 8, anything else means 10. If *base* is 16, a leading
686 ``0x`` or ``0X`` is always accepted, though not required. This behaves
687 identically to the built-in function :func:`int` when passed a string. (Also
688 note: for a more flexible interpretation of numeric literals, use the built-in
689 function :func:`eval`.)
690
691
692.. function:: atol(s[, base])
693
694 .. deprecated:: 2.0
695 Use the :func:`long` built-in function.
696
697 .. index:: builtin: long
698
699 Convert string *s* to a long integer in the given *base*. The string must
700 consist of one or more digits, optionally preceded by a sign (``+`` or ``-``).
701 The *base* argument has the same meaning as for :func:`atoi`. A trailing ``l``
702 or ``L`` is not allowed, except if the base is 0. Note that when invoked
703 without *base* or with *base* set to 10, this behaves identical to the built-in
704 function :func:`long` when passed a string.
705
706
707.. function:: capitalize(word)
708
709 Return a copy of *word* with only its first character capitalized.
710
711
712.. function:: expandtabs(s[, tabsize])
713
714 Expand tabs in a string replacing them by one or more spaces, depending on the
715 current column and the given tab size. The column number is reset to zero after
716 each newline occurring in the string. This doesn't understand other non-printing
717 characters or escape sequences. The tab size defaults to 8.
718
719
720.. function:: find(s, sub[, start[,end]])
721
722 Return the lowest index in *s* where the substring *sub* is found such that
723 *sub* is wholly contained in ``s[start:end]``. Return ``-1`` on failure.
724 Defaults for *start* and *end* and interpretation of negative values is the same
725 as for slices.
726
727
728.. function:: rfind(s, sub[, start[, end]])
729
730 Like :func:`find` but find the highest index.
731
732
733.. function:: index(s, sub[, start[, end]])
734
735 Like :func:`find` but raise :exc:`ValueError` when the substring is not found.
736
737
738.. function:: rindex(s, sub[, start[, end]])
739
740 Like :func:`rfind` but raise :exc:`ValueError` when the substring is not found.
741
742
743.. function:: count(s, sub[, start[, end]])
744
745 Return the number of (non-overlapping) occurrences of substring *sub* in string
746 ``s[start:end]``. Defaults for *start* and *end* and interpretation of negative
747 values are the same as for slices.
748
749
750.. function:: lower(s)
751
752 Return a copy of *s*, but with upper case letters converted to lower case.
753
754
755.. function:: split(s[, sep[, maxsplit]])
756
757 Return a list of the words of the string *s*. If the optional second argument
758 *sep* is absent or ``None``, the words are separated by arbitrary strings of
759 whitespace characters (space, tab, newline, return, formfeed). If the second
760 argument *sep* is present and not ``None``, it specifies a string to be used as
761 the word separator. The returned list will then have one more item than the
762 number of non-overlapping occurrences of the separator in the string. The
763 optional third argument *maxsplit* defaults to 0. If it is nonzero, at most
764 *maxsplit* number of splits occur, and the remainder of the string is returned
765 as the final element of the list (thus, the list will have at most
766 ``maxsplit+1`` elements).
767
768 The behavior of split on an empty string depends on the value of *sep*. If *sep*
769 is not specified, or specified as ``None``, the result will be an empty list.
770 If *sep* is specified as any string, the result will be a list containing one
771 element which is an empty string.
772
773
774.. function:: rsplit(s[, sep[, maxsplit]])
775
776 Return a list of the words of the string *s*, scanning *s* from the end. To all
777 intents and purposes, the resulting list of words is the same as returned by
778 :func:`split`, except when the optional third argument *maxsplit* is explicitly
779 specified and nonzero. When *maxsplit* is nonzero, at most *maxsplit* number of
780 splits -- the *rightmost* ones -- occur, and the remainder of the string is
781 returned as the first element of the list (thus, the list will have at most
782 ``maxsplit+1`` elements).
783
784 .. versionadded:: 2.4
785
786
787.. function:: splitfields(s[, sep[, maxsplit]])
788
789 This function behaves identically to :func:`split`. (In the past, :func:`split`
790 was only used with one argument, while :func:`splitfields` was only used with
791 two arguments.)
792
793
794.. function:: join(words[, sep])
795
796 Concatenate a list or tuple of words with intervening occurrences of *sep*.
797 The default value for *sep* is a single space character. It is always true that
798 ``string.join(string.split(s, sep), sep)`` equals *s*.
799
800
801.. function:: joinfields(words[, sep])
802
803 This function behaves identically to :func:`join`. (In the past, :func:`join`
804 was only used with one argument, while :func:`joinfields` was only used with two
805 arguments.) Note that there is no :meth:`joinfields` method on string objects;
806 use the :meth:`join` method instead.
807
808
809.. function:: lstrip(s[, chars])
810
811 Return a copy of the string with leading characters removed. If *chars* is
812 omitted or ``None``, whitespace characters are removed. If given and not
813 ``None``, *chars* must be a string; the characters in the string will be
814 stripped from the beginning of the string this method is called on.
815
816 .. versionchanged:: 2.2.3
817 The *chars* parameter was added. The *chars* parameter cannot be passed in
818 earlier 2.2 versions.
819
820
821.. function:: rstrip(s[, chars])
822
823 Return a copy of the string with trailing characters removed. If *chars* is
824 omitted or ``None``, whitespace characters are removed. If given and not
825 ``None``, *chars* must be a string; the characters in the string will be
826 stripped from the end of the string this method is called on.
827
828 .. versionchanged:: 2.2.3
829 The *chars* parameter was added. The *chars* parameter cannot be passed in
830 earlier 2.2 versions.
831
832
833.. function:: strip(s[, chars])
834
835 Return a copy of the string with leading and trailing characters removed. If
836 *chars* is omitted or ``None``, whitespace characters are removed. If given and
837 not ``None``, *chars* must be a string; the characters in the string will be
838 stripped from the both ends of the string this method is called on.
839
840 .. versionchanged:: 2.2.3
841 The *chars* parameter was added. The *chars* parameter cannot be passed in
842 earlier 2.2 versions.
843
844
845.. function:: swapcase(s)
846
847 Return a copy of *s*, but with lower case letters converted to upper case and
848 vice versa.
849
850
851.. function:: translate(s, table[, deletechars])
852
853 Delete all characters from *s* that are in *deletechars* (if present), and then
854 translate the characters using *table*, which must be a 256-character string
855 giving the translation for each character value, indexed by its ordinal. If
856 *table* is ``None``, then only the character deletion step is performed.
857
858
859.. function:: upper(s)
860
861 Return a copy of *s*, but with lower case letters converted to upper case.
862
863
Georg Brandlf18d5ce2009-10-27 14:29:22 +0000864.. function:: ljust(s, width[, fillchar])
865 rjust(s, width[, fillchar])
866 center(s, width[, fillchar])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000867
868 These functions respectively left-justify, right-justify and center a string in
869 a field of given width. They return a string that is at least *width*
Georg Brandlf18d5ce2009-10-27 14:29:22 +0000870 characters wide, created by padding the string *s* with the character *fillchar*
871 (default is a space) until the given width on the right, left or both sides.
872 The string is never truncated.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000873
874
875.. function:: zfill(s, width)
876
877 Pad a numeric string on the left with zero digits until the given width is
878 reached. Strings starting with a sign are handled correctly.
879
880
881.. function:: replace(str, old, new[, maxreplace])
882
883 Return a copy of string *str* with all occurrences of substring *old* replaced
884 by *new*. If the optional argument *maxreplace* is given, the first
885 *maxreplace* occurrences are replaced.
886