blob: 2e1b529a8eb348943012aa56a40a559ee3f45b17 [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
74 A string containing all characters that are considered whitespace.
75 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
84Starting in Python 3.0, the built-in string class provides the ability to do
85complex variable substitutions and value formatting via the :func:`format`
86method described in :pep:`3101`. The :class:`Formatter` class in the
87:mod:`string` module allows you to create and customize your own string
88formatting behaviors using the same implementation as the built-in
89:meth:`format` method.
90
91.. class:: Formatter
92
93 The :class:`Formatter` class has the following public methods:
94
95 .. method:: format(format_string, *args, *kwargs)
96
97 :meth:`format` is the primary API method. It takes a format template
98 string, and an arbitrary set of positional and keyword argument.
99 :meth:`format` is just a wrapper that calls :meth:`vformat`.
100
101 .. method:: vformat(format_string, args, kwargs)
102
103 This function does the actual work of formatting. It is exposed as a
104 separate function for cases where you want to pass in a predefined
105 dictionary of arguments, rather than unpacking and repacking the
106 dictionary as individual arguments using the ``*args`` and ``**kwds``
107 syntax. :meth:`vformat` does the work of breaking up the format template
108 string into character data and replacement fields. It calls the various
109 methods described below.
110
111 In addition, the :class:`Formatter` defines a number of methods that are
112 intended to be replaced by subclasses:
113
114 .. method:: parse(format_string)
115
116 Loop over the format_string and return an iterable of tuples
117 (*literal_text*, *field_name*, *format_spec*, *conversion*). This is used
118 by :meth:`vformat` to break the string in to either literal text, or
119 replacement fields.
120
121 The values in the tuple conceptually represent a span of literal text
122 followed by a single replacement field. If there is no literal text
123 (which can happen if two replacement fields occur consecutively), then
124 *literal_text* will be a zero-length string. If there is no replacement
125 field, then the values of *field_name*, *format_spec* and *conversion*
126 will be ``None``.
127
128 .. method:: get_field(field_name, args, kwargs, used_args)
129
130 Given *field_name* as returned by :meth:`parse` (see above), convert it to
Georg Brandl7f13e6b2007-08-31 10:37:15 +0000131 an object to be formatted. Returns a tuple (obj, used_key). The default
132 version takes strings of the form defined in :pep:`3101`, such as
133 "0[name]" or "label.title". *args* and *kwargs* are as passed in to
134 :meth:`vformat`. The return value *used_key* has the same meaning as the
135 *key* parameter to :meth:`get_value`.
Georg Brandl4b491312007-08-31 09:22:56 +0000136
137 .. method:: get_value(key, args, kwargs)
138
139 Retrieve a given field value. The *key* argument will be either an
140 integer or a string. If it is an integer, it represents the index of the
141 positional argument in *args*; if it is a string, then it represents a
142 named argument in *kwargs*.
143
144 The *args* parameter is set to the list of positional arguments to
145 :meth:`vformat`, and the *kwargs* parameter is set to the dictionary of
146 keyword arguments.
147
148 For compound field names, these functions are only called for the first
149 component of the field name; Subsequent components are handled through
150 normal attribute and indexing operations.
151
152 So for example, the field expression '0.name' would cause
153 :meth:`get_value` to be called with a *key* argument of 0. The ``name``
154 attribute will be looked up after :meth:`get_value` returns by calling the
155 built-in :func:`getattr` function.
156
157 If the index or keyword refers to an item that does not exist, then an
158 :exc:`IndexError` or :exc:`KeyError` should be raised.
159
160 .. method:: check_unused_args(used_args, args, kwargs)
161
162 Implement checking for unused arguments if desired. The arguments to this
163 function is the set of all argument keys that were actually referred to in
164 the format string (integers for positional arguments, and strings for
165 named arguments), and a reference to the *args* and *kwargs* that was
166 passed to vformat. The set of unused args can be calculated from these
167 parameters. :meth:`check_unused_args` is assumed to throw an exception if
168 the check fails.
169
170 .. method:: format_field(value, format_spec)
171
172 :meth:`format_field` simply calls the global :func:`format` built-in. The
173 method is provided so that subclasses can override it.
174
175 .. method:: convert_field(value, conversion)
176
177 Converts the value (returned by :meth:`get_field`) given a conversion type
178 (as in the tuple returned by the :meth:`parse` method.) The default
179 version understands 'r' (repr) and 's' (str) conversion types.
180
181 .. versionadded:: 3.0
182
183.. _formatstrings:
184
185Format String Syntax
186--------------------
187
188The :meth:`str.format` method and the :class:`Formatter` class share the same
189syntax for format strings (although in the case of :class:`Formatter`,
190subclasses can define their own format string syntax.)
191
192Format strings contain "replacement fields" surrounded by curly braces ``{}``.
193Anything that is not contained in braces is considered literal text, which is
194copied unchanged to the output. If you need to include a brace character in the
195literal text, it can be escaped by doubling: ``{{`` and ``}}``.
196
197The grammar for a replacement field is as follows:
198
199 .. productionlist:: sf
200 replacement_field: "{" `field_name` ["!" `conversion`] [":" `format_spec`] "}"
201 field_name: (`identifier` | `integer`) ("." `attribute_name` | "[" element_index "]")*
202 attribute_name: `identifier`
203 element_index: `integer`
204 conversion: "r" | "s"
205 format_spec: <described in the next section>
206
207In less formal terms, the replacement field starts with a *field_name*, which
208can either be a number (for a positional argument), or an identifier (for
209keyword arguments). Following this is an optional *conversion* field, which is
210preceded by an exclamation point ``'!'``, and a *format_spec*, which is preceded
211by a colon ``':'``.
212
213The *field_name* itself begins with either a number or a keyword. If it's a
214number, it refers to a positional argument, and if it's a keyword it refers to a
215named keyword argument. This can be followed by any number of index or
216attribute expressions. An expression of the form ``'.name'`` selects the named
217attribute using :func:`getattr`, while an expression of the form ``'[index]'``
218does an index lookup using :func:`__getitem__`.
219
220Some simple format string examples::
221
222 "First, thou shalt count to {0}" # References first positional argument
223 "My quest is {name}" # References keyword argument 'name'
224 "Weight in tons {0.weight}" # 'weight' attribute of first positional arg
225 "Units destroyed: {players[0]}" # First element of keyword argument 'players'.
226
227The *conversion* field causes a type coercion before formatting. Normally, the
228job of formatting a value is done by the :meth:`__format__` method of the value
229itself. However, in some cases it is desirable to force a type to be formatted
230as a string, overriding its own definition of formatting. By converting the
231value to a string before calling :meth:`__format__`, the normal formatting logic
232is bypassed.
233
234Two conversion flags are currently supported: ``'!s'`` which calls :func:`str()`
235on the value, and ``'!r'`` which calls :func:`repr()`.
236
237Some examples::
238
239 "Harold's a clever {0!s}" # Calls str() on the argument first
240 "Bring out the holy {name!r}" # Calls repr() on the argument first
241
242The *format_spec* field contains a specification of how the value should be
243presented, including such details as field width, alignment, padding, decimal
244precision and so on. Each value type can define it's own "formatting
245mini-language" or interpretation of the *format_spec*.
246
247Most built-in types support a common formatting mini-language, which is
248described in the next section.
249
250A *format_spec* field can also include nested replacement fields within it.
251These nested replacement fields can contain only a field name; conversion flags
252and format specifications are not allowed. The replacement fields within the
253format_spec are substituted before the *format_spec* string is interpreted.
254This allows the formatting of a value to be dynamically specified.
255
256For example, suppose you wanted to have a replacement field whose field width is
257determined by another variable::
258
259 "A man with two {0:{1}}".format("noses", 10)
260
261This would first evaluate the inner replacement field, making the format string
262effectively::
263
264 "A man with two {0:10}"
265
266Then the outer replacement field would be evaluated, producing::
267
268 "noses "
269
270Which is subsitituted into the string, yielding::
271
272 "A man with two noses "
273
274(The extra space is because we specified a field width of 10, and because left
275alignment is the default for strings.)
276
277.. versionadded:: 3.0
278
279.. _formatspec:
280
281Format Specification Mini-Language
282^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
283
284"Format specifications" are used within replacement fields contained within a
285format string to define how individual values are presented (see
286:ref:`formatstrings`.) They can also be passed directly to the builtin
287:func:`format` function. Each formattable type may define how the format
288specification is to be interpreted.
289
290Most built-in types implement the following options for format specifications,
291although some of the formatting options are only supported by the numeric types.
292
293A general convention is that an empty format string (``""``) produces the same
294result as if you had called :func:`str()` on the value.
295
296The general form of a *standard format specifier* is:
297
298.. productionlist:: sf
299 format_spec: [[`fill`]`align`][`sign`][0][`width`][.`precision`][`type`]
300 fill: <a character other than '}'>
301 align: "<" | ">" | "=" | "^"
302 sign: "+" | "-" | " "
303 width: `integer`
304 precision: `integer`
305 type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "x" | "X" | "%"
306
307The *fill* character can be any character other than '}' (which signifies the
308end of the field). The presence of a fill character is signaled by the *next*
309character, which must be one of the alignment options. If the second character
310of *format_spec* is not a valid alignment option, then it is assumed that both
311the fill character and the alignment option are absent.
312
313The meaning of the various alignment options is as follows:
314
315 +---------+----------------------------------------------------------+
316 | Option | Meaning |
317 +=========+==========================================================+
318 | ``'<'`` | Forces the field to be left-aligned within the available |
319 | | space (This is the default.) |
320 +---------+----------------------------------------------------------+
321 | ``'>'`` | Forces the field to be right-aligned within the |
322 | | available space. |
323 +---------+----------------------------------------------------------+
324 | ``'='`` | Forces the padding to be placed after the sign (if any) |
325 | | but before the digits. This is used for printing fields |
326 | | in the form '+000000120'. This alignment option is only |
327 | | valid for numeric types. |
328 +---------+----------------------------------------------------------+
329 | ``'^'`` | Forces the field to be centered within the available |
330 | | space. |
331 +---------+----------------------------------------------------------+
332
333Note that unless a minimum field width is defined, the field width will always
334be the same size as the data to fill it, so that the alignment option has no
335meaning in this case.
336
337The *sign* option is only valid for number types, and can be one of the
338following:
339
340 +---------+----------------------------------------------------------+
341 | Option | Meaning |
342 +=========+==========================================================+
343 | ``'+'`` | indicates that a sign should be used for both |
344 | | positive as well as negative numbers. |
345 +---------+----------------------------------------------------------+
346 | ``'-'`` | indicates that a sign should be used only for negative |
347 | | numbers (this is the default behavior). |
348 +---------+----------------------------------------------------------+
349 | space | indicates that a leading space should be used on |
350 | | positive numbers, and a minus sign on negative numbers. |
351 +---------+----------------------------------------------------------+
352
353*width* is a decimal integer defining the minimum field width. If not
354specified, then the field width will be determined by the content.
355
356If the *width* field is preceded by a zero (``'0'``) character, this enables
357zero-padding. This is equivalent to an *alignment* type of ``'='`` and a *fill*
358character of ``'0'``.
359
360The *precision* is a decimal number indicating how many digits should be
361displayed after the decimal point for a floating point value. For non-number
362types the field indicates the maximum field size - in other words, how many
363characters will be used from the field content. The *precision* is ignored for
364integer values.
365
366Finally, the *type* determines how the data should be presented.
367
368The available integer presentation types are:
369
370 +---------+----------------------------------------------------------+
371 | Type | Meaning |
372 +=========+==========================================================+
373 | ``'b'`` | Binary. Outputs the number in base 2. |
374 +---------+----------------------------------------------------------+
375 | ``'c'`` | Character. Converts the integer to the corresponding |
376 | | unicode character before printing. |
377 +---------+----------------------------------------------------------+
378 | ``'d'`` | Decimal Integer. Outputs the number in base 10. |
379 +---------+----------------------------------------------------------+
380 | ``'o'`` | Octal format. Outputs the number in base 8. |
381 +---------+----------------------------------------------------------+
382 | ``'x'`` | Hex format. Outputs the number in base 16, using lower- |
383 | | case letters for the digits above 9. |
384 +---------+----------------------------------------------------------+
385 | ``'X'`` | Hex format. Outputs the number in base 16, using upper- |
386 | | case letters for the digits above 9. |
387 +---------+----------------------------------------------------------+
388 | None | the same as ``'d'`` |
389 +---------+----------------------------------------------------------+
390
391The available presentation types for floating point and decimal values are:
392
393 +---------+----------------------------------------------------------+
394 | Type | Meaning |
395 +=========+==========================================================+
396 | ``'e'`` | Exponent notation. Prints the number in scientific |
397 | | notation using the letter 'e' to indicate the exponent. |
398 +---------+----------------------------------------------------------+
399 | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an |
400 | | upper case 'E' as the separator character. |
401 +---------+----------------------------------------------------------+
402 | ``'f'`` | Fixed point. Displays the number as a fixed-point |
403 | | number. |
404 +---------+----------------------------------------------------------+
405 | ``'F'`` | Fixed point. Same as ``'f'``. |
406 +---------+----------------------------------------------------------+
407 | ``'g'`` | General format. This prints the number as a fixed-point |
408 | | number, unless the number is too large, in which case |
409 | | it switches to ``'e'`` exponent notation. |
410 +---------+----------------------------------------------------------+
411 | ``'G'`` | General format. Same as ``'g'`` except switches to |
412 | | ``'E'`` if the number gets to large. |
413 +---------+----------------------------------------------------------+
414 | ``'n'`` | Number. This is the same as ``'g'``, except that it uses |
415 | | the current locale setting to insert the appropriate |
416 | | number separator characters. |
417 +---------+----------------------------------------------------------+
418 | ``'%'`` | Percentage. Multiplies the number by 100 and displays |
419 | | in fixed (``'f'``) format, followed by a percent sign. |
420 +---------+----------------------------------------------------------+
421 | None | similar to ``'g'``, except that it prints at least one |
422 | | digit after the decimal point. |
423 +---------+----------------------------------------------------------+
424
425
426.. _template-strings:
427
Georg Brandl116aa622007-08-15 14:28:22 +0000428Template strings
429----------------
430
431Templates provide simpler string substitutions as described in :pep:`292`.
432Instead of the normal ``%``\ -based substitutions, Templates support ``$``\
433-based substitutions, using the following rules:
434
435* ``$$`` is an escape; it is replaced with a single ``$``.
436
437* ``$identifier`` names a substitution placeholder matching a mapping key of
438 ``"identifier"``. By default, ``"identifier"`` must spell a Python
439 identifier. The first non-identifier character after the ``$`` character
440 terminates this placeholder specification.
441
442* ``${identifier}`` is equivalent to ``$identifier``. It is required when valid
443 identifier characters follow the placeholder but are not part of the
444 placeholder, such as ``"${noun}ification"``.
445
446Any other appearance of ``$`` in the string will result in a :exc:`ValueError`
447being raised.
448
449.. versionadded:: 2.4
450
451The :mod:`string` module provides a :class:`Template` class that implements
452these rules. The methods of :class:`Template` are:
453
454
455.. class:: Template(template)
456
457 The constructor takes a single argument which is the template string.
458
459
460.. method:: Template.substitute(mapping[, **kws])
461
462 Performs the template substitution, returning a new string. *mapping* is any
463 dictionary-like object with keys that match the placeholders in the template.
464 Alternatively, you can provide keyword arguments, where the keywords are the
465 placeholders. When both *mapping* and *kws* are given and there are duplicates,
466 the placeholders from *kws* take precedence.
467
468
469.. method:: Template.safe_substitute(mapping[, **kws])
470
471 Like :meth:`substitute`, except that if placeholders are missing from *mapping*
472 and *kws*, instead of raising a :exc:`KeyError` exception, the original
473 placeholder will appear in the resulting string intact. Also, unlike with
474 :meth:`substitute`, any other appearances of the ``$`` will simply return ``$``
475 instead of raising :exc:`ValueError`.
476
477 While other exceptions may still occur, this method is called "safe" because
478 substitutions always tries to return a usable string instead of raising an
479 exception. In another sense, :meth:`safe_substitute` may be anything other than
480 safe, since it will silently ignore malformed templates containing dangling
481 delimiters, unmatched braces, or placeholders that are not valid Python
482 identifiers.
483
484:class:`Template` instances also provide one public data attribute:
485
486
487.. attribute:: string.template
488
489 This is the object passed to the constructor's *template* argument. In general,
490 you shouldn't change it, but read-only access is not enforced.
491
492Here is an example of how to use a Template::
493
494 >>> from string import Template
495 >>> s = Template('$who likes $what')
496 >>> s.substitute(who='tim', what='kung pao')
497 'tim likes kung pao'
498 >>> d = dict(who='tim')
499 >>> Template('Give $who $100').substitute(d)
500 Traceback (most recent call last):
501 [...]
502 ValueError: Invalid placeholder in string: line 1, col 10
503 >>> Template('$who likes $what').substitute(d)
504 Traceback (most recent call last):
505 [...]
506 KeyError: 'what'
507 >>> Template('$who likes $what').safe_substitute(d)
508 'tim likes $what'
509
510Advanced usage: you can derive subclasses of :class:`Template` to customize the
511placeholder syntax, delimiter character, or the entire regular expression used
512to parse template strings. To do this, you can override these class attributes:
513
514* *delimiter* -- This is the literal string describing a placeholder introducing
515 delimiter. The default value ``$``. Note that this should *not* be a regular
516 expression, as the implementation will call :meth:`re.escape` on this string as
517 needed.
518
519* *idpattern* -- This is the regular expression describing the pattern for
520 non-braced placeholders (the braces will be added automatically as
521 appropriate). The default value is the regular expression
522 ``[_a-z][_a-z0-9]*``.
523
524Alternatively, you can provide the entire regular expression pattern by
525overriding the class attribute *pattern*. If you do this, the value must be a
526regular expression object with four named capturing groups. The capturing
527groups correspond to the rules given above, along with the invalid placeholder
528rule:
529
530* *escaped* -- This group matches the escape sequence, e.g. ``$$``, in the
531 default pattern.
532
533* *named* -- This group matches the unbraced placeholder name; it should not
534 include the delimiter in capturing group.
535
536* *braced* -- This group matches the brace enclosed placeholder name; it should
537 not include either the delimiter or braces in the capturing group.
538
539* *invalid* -- This group matches any other delimiter pattern (usually a single
540 delimiter), and it should appear last in the regular expression.
541
542
543String functions
544----------------
545
546The following functions are available to operate on string and Unicode objects.
547They are not available as string methods.
548
549
550.. function:: capwords(s)
551
552 Split the argument into words using :func:`split`, capitalize each word using
553 :func:`capitalize`, and join the capitalized words using :func:`join`. Note
554 that this replaces runs of whitespace characters by a single space, and removes
555 leading and trailing whitespace.
556
557
Georg Brandl7f13e6b2007-08-31 10:37:15 +0000558.. function:: maketrans(frm, to)
Georg Brandl116aa622007-08-15 14:28:22 +0000559
Georg Brandl7f13e6b2007-08-31 10:37:15 +0000560 Return a translation table suitable for passing to :meth:`bytes.translate`,
561 that will map each character in *from* into the character at the same
562 position in *to*; *from* and *to* must have the same length.