blob: 0e345e38de10f3c0db2284d5dfac20460f3243f6 [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.
65 On most systems this is the string ``'abcdefghijklmnopqrstuvwxyz'``. Do not
66 change its definition --- the effect on the routines :func:`upper` and
67 :func:`swapcase` is undefined. The specific value is locale-dependent, and will
68 be updated when :func:`locale.setlocale` is called.
69
70
71.. data:: octdigits
72
73 The string ``'01234567'``.
74
75
76.. data:: punctuation
77
78 String of ASCII characters which are considered punctuation characters in the
79 ``C`` locale.
80
81
82.. data:: printable
83
84 String of characters which are considered printable. This is a combination of
85 :const:`digits`, :const:`letters`, :const:`punctuation`, and
86 :const:`whitespace`.
87
88
89.. data:: uppercase
90
91 A string containing all the characters that are considered uppercase letters.
92 On most systems this is the string ``'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. Do not
93 change its definition --- the effect on the routines :func:`lower` and
94 :func:`swapcase` is undefined. The specific value is locale-dependent, and will
95 be updated when :func:`locale.setlocale` is called.
96
97
98.. data:: whitespace
99
100 A string containing all characters that are considered whitespace. On most
101 systems this includes the characters space, tab, linefeed, return, formfeed, and
102 vertical tab. Do not change its definition --- the effect on the routines
103 :func:`strip` and :func:`split` is undefined.
104
105
Benjamin Petersonc15205e2008-05-25 20:05:52 +0000106.. _new-string-formatting:
Georg Brandle321c2f2008-05-12 16:45:43 +0000107
108String Formatting
109-----------------
110
111Starting in Python 2.6, the built-in str and unicode classes provide the ability
Benjamin Petersonc15205e2008-05-25 20:05:52 +0000112to do complex variable substitutions and value formatting via the
113:meth:`str.format` method described in :pep:`3101`. The :class:`Formatter`
114class in the :mod:`string` module allows you to create and customize your own
115string formatting behaviors using the same implementation as the built-in
Georg Brandle321c2f2008-05-12 16:45:43 +0000116:meth:`format` method.
117
118.. class:: Formatter
119
120 The :class:`Formatter` class has the following public methods:
121
122 .. method:: format(format_string, *args, *kwargs)
123
124 :meth:`format` is the primary API method. It takes a format template
125 string, and an arbitrary set of positional and keyword argument.
126 :meth:`format` is just a wrapper that calls :meth:`vformat`.
127
128 .. method:: vformat(format_string, args, kwargs)
129
130 This function does the actual work of formatting. It is exposed as a
131 separate function for cases where you want to pass in a predefined
132 dictionary of arguments, rather than unpacking and repacking the
133 dictionary as individual arguments using the ``*args`` and ``**kwds``
134 syntax. :meth:`vformat` does the work of breaking up the format template
135 string into character data and replacement fields. It calls the various
136 methods described below.
137
138 In addition, the :class:`Formatter` defines a number of methods that are
139 intended to be replaced by subclasses:
140
141 .. method:: parse(format_string)
142
143 Loop over the format_string and return an iterable of tuples
144 (*literal_text*, *field_name*, *format_spec*, *conversion*). This is used
145 by :meth:`vformat` to break the string in to either literal text, or
146 replacement fields.
147
148 The values in the tuple conceptually represent a span of literal text
149 followed by a single replacement field. If there is no literal text
150 (which can happen if two replacement fields occur consecutively), then
151 *literal_text* will be a zero-length string. If there is no replacement
152 field, then the values of *field_name*, *format_spec* and *conversion*
153 will be ``None``.
154
155 .. method:: get_field(field_name, args, kwargs)
156
157 Given *field_name* as returned by :meth:`parse` (see above), convert it to
158 an object to be formatted. Returns a tuple (obj, used_key). The default
159 version takes strings of the form defined in :pep:`3101`, such as
160 "0[name]" or "label.title". *args* and *kwargs* are as passed in to
161 :meth:`vformat`. The return value *used_key* has the same meaning as the
162 *key* parameter to :meth:`get_value`.
163
164 .. method:: get_value(key, args, kwargs)
165
166 Retrieve a given field value. The *key* argument will be either an
167 integer or a string. If it is an integer, it represents the index of the
168 positional argument in *args*; if it is a string, then it represents a
169 named argument in *kwargs*.
170
171 The *args* parameter is set to the list of positional arguments to
172 :meth:`vformat`, and the *kwargs* parameter is set to the dictionary of
173 keyword arguments.
174
175 For compound field names, these functions are only called for the first
176 component of the field name; Subsequent components are handled through
177 normal attribute and indexing operations.
178
179 So for example, the field expression '0.name' would cause
180 :meth:`get_value` to be called with a *key* argument of 0. The ``name``
181 attribute will be looked up after :meth:`get_value` returns by calling the
182 built-in :func:`getattr` function.
183
184 If the index or keyword refers to an item that does not exist, then an
185 :exc:`IndexError` or :exc:`KeyError` should be raised.
186
187 .. method:: check_unused_args(used_args, args, kwargs)
188
189 Implement checking for unused arguments if desired. The arguments to this
190 function is the set of all argument keys that were actually referred to in
191 the format string (integers for positional arguments, and strings for
192 named arguments), and a reference to the *args* and *kwargs* that was
193 passed to vformat. The set of unused args can be calculated from these
194 parameters. :meth:`check_unused_args` is assumed to throw an exception if
195 the check fails.
196
197 .. method:: format_field(value, format_spec)
198
199 :meth:`format_field` simply calls the global :func:`format` built-in. The
200 method is provided so that subclasses can override it.
201
202 .. method:: convert_field(value, conversion)
203
204 Converts the value (returned by :meth:`get_field`) given a conversion type
205 (as in the tuple returned by the :meth:`parse` method.) The default
206 version understands 'r' (repr) and 's' (str) conversion types.
207
208
209.. _formatstrings:
210
211Format String Syntax
212--------------------
213
214The :meth:`str.format` method and the :class:`Formatter` class share the same
215syntax for format strings (although in the case of :class:`Formatter`,
216subclasses can define their own format string syntax.)
217
218Format strings contain "replacement fields" surrounded by curly braces ``{}``.
219Anything that is not contained in braces is considered literal text, which is
220copied unchanged to the output. If you need to include a brace character in the
221literal text, it can be escaped by doubling: ``{{`` and ``}}``.
222
223The grammar for a replacement field is as follows:
224
225 .. productionlist:: sf
226 replacement_field: "{" `field_name` ["!" `conversion`] [":" `format_spec`] "}"
227 field_name: (`identifier` | `integer`) ("." `attribute_name` | "[" element_index "]")*
228 attribute_name: `identifier`
229 element_index: `integer`
230 conversion: "r" | "s"
231 format_spec: <described in the next section>
232
233In 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'.
252
253The *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
270precision and so on. Each value type can define it's own "formatting
271mini-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 "
295
Benjamin Peterson90f36732008-07-12 20:16:19 +0000296Which is substituted into the string, yielding::
Georg Brandle321c2f2008-05-12 16:45:43 +0000297
298 "A man with two noses "
299
300(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
311:ref:`formatstrings`.) They can also be passed directly to the builtin
312: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
318A general convention is that an empty format string (``""``) produces the same
319result as if you had called :func:`str` on the value.
320
321The general form of a *standard format specifier* is:
322
323.. productionlist:: sf
Eric Smitha5fa5a22008-07-16 00:11:49 +0000324 format_spec: [[`fill`]`align`][`sign`][#][0][`width`][.`precision`][`type`]
Georg Brandle321c2f2008-05-12 16:45:43 +0000325 fill: <a character other than '}'>
326 align: "<" | ">" | "=" | "^"
327 sign: "+" | "-" | " "
328 width: `integer`
329 precision: `integer`
330 type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "x" | "X" | "%"
331
332The *fill* character can be any character other than '}' (which signifies the
333end of the field). The presence of a fill character is signaled by the *next*
334character, which must be one of the alignment options. If the second character
335of *format_spec* is not a valid alignment option, then it is assumed that both
336the fill character and the alignment option are absent.
337
338The meaning of the various alignment options is as follows:
339
340 +---------+----------------------------------------------------------+
341 | Option | Meaning |
342 +=========+==========================================================+
343 | ``'<'`` | Forces the field to be left-aligned within the available |
344 | | space (This is the default.) |
345 +---------+----------------------------------------------------------+
346 | ``'>'`` | Forces the field to be right-aligned within the |
347 | | available space. |
348 +---------+----------------------------------------------------------+
349 | ``'='`` | Forces the padding to be placed after the sign (if any) |
350 | | but before the digits. This is used for printing fields |
351 | | in the form '+000000120'. This alignment option is only |
352 | | valid for numeric types. |
353 +---------+----------------------------------------------------------+
354 | ``'^'`` | Forces the field to be centered within the available |
355 | | space. |
356 +---------+----------------------------------------------------------+
357
358Note that unless a minimum field width is defined, the field width will always
359be the same size as the data to fill it, so that the alignment option has no
360meaning in this case.
361
362The *sign* option is only valid for number types, and can be one of the
363following:
364
365 +---------+----------------------------------------------------------+
366 | Option | Meaning |
367 +=========+==========================================================+
368 | ``'+'`` | indicates that a sign should be used for both |
369 | | positive as well as negative numbers. |
370 +---------+----------------------------------------------------------+
371 | ``'-'`` | indicates that a sign should be used only for negative |
372 | | numbers (this is the default behavior). |
373 +---------+----------------------------------------------------------+
374 | space | indicates that a leading space should be used on |
375 | | positive numbers, and a minus sign on negative numbers. |
376 +---------+----------------------------------------------------------+
377
Eric Smitha5fa5a22008-07-16 00:11:49 +0000378The ``'#'`` option is only valid for integers, and only for binary,
379octal, or decimal output. If present, it specifies that the output
380will be prefixed by ``'0b'``, ``'0o'``, or ``'0x'``, respectively.
381
Georg Brandle321c2f2008-05-12 16:45:43 +0000382*width* is a decimal integer defining the minimum field width. If not
383specified, then the field width will be determined by the content.
384
385If the *width* field is preceded by a zero (``'0'``) character, this enables
386zero-padding. This is equivalent to an *alignment* type of ``'='`` and a *fill*
387character of ``'0'``.
388
389The *precision* is a decimal number indicating how many digits should be
390displayed after the decimal point for a floating point value. For non-number
391types the field indicates the maximum field size - in other words, how many
392characters will be used from the field content. The *precision* is ignored for
393integer values.
394
395Finally, the *type* determines how the data should be presented.
396
397The available integer presentation types are:
398
399 +---------+----------------------------------------------------------+
400 | Type | Meaning |
401 +=========+==========================================================+
Eric Smitha5fa5a22008-07-16 00:11:49 +0000402 | ``'b'`` | Binary format. Outputs the number in base 2. |
Georg Brandle321c2f2008-05-12 16:45:43 +0000403 +---------+----------------------------------------------------------+
404 | ``'c'`` | Character. Converts the integer to the corresponding |
405 | | unicode character before printing. |
406 +---------+----------------------------------------------------------+
407 | ``'d'`` | Decimal Integer. Outputs the number in base 10. |
408 +---------+----------------------------------------------------------+
409 | ``'o'`` | Octal format. Outputs the number in base 8. |
410 +---------+----------------------------------------------------------+
411 | ``'x'`` | Hex format. Outputs the number in base 16, using lower- |
412 | | case letters for the digits above 9. |
413 +---------+----------------------------------------------------------+
414 | ``'X'`` | Hex format. Outputs the number in base 16, using upper- |
415 | | case letters for the digits above 9. |
416 +---------+----------------------------------------------------------+
417 | ``'n'`` | Number. This is the same as ``'d'``, except that it uses |
418 | | the current locale setting to insert the appropriate |
419 | | number separator characters. |
420 +---------+----------------------------------------------------------+
421 | None | the same as ``'d'`` |
422 +---------+----------------------------------------------------------+
423
424The available presentation types for floating point and decimal values are:
425
426 +---------+----------------------------------------------------------+
427 | Type | Meaning |
428 +=========+==========================================================+
429 | ``'e'`` | Exponent notation. Prints the number in scientific |
430 | | notation using the letter 'e' to indicate the exponent. |
431 +---------+----------------------------------------------------------+
Eric Smithd6c393a2008-07-17 19:49:47 +0000432 | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an |
433 | | upper case 'E' as the separator character. |
Georg Brandle321c2f2008-05-12 16:45:43 +0000434 +---------+----------------------------------------------------------+
435 | ``'f'`` | Fixed point. Displays the number as a fixed-point |
436 | | number. |
437 +---------+----------------------------------------------------------+
Eric Smithd6c393a2008-07-17 19:49:47 +0000438 | ``'F'`` | Fixed point. Same as ``'f'``. |
Georg Brandle321c2f2008-05-12 16:45:43 +0000439 +---------+----------------------------------------------------------+
440 | ``'g'`` | General format. This prints the number as a fixed-point |
441 | | number, unless the number is too large, in which case |
442 | | it switches to ``'e'`` exponent notation. |
443 +---------+----------------------------------------------------------+
444 | ``'G'`` | General format. Same as ``'g'`` except switches to |
445 | | ``'E'`` if the number gets to large. |
446 +---------+----------------------------------------------------------+
447 | ``'n'`` | Number. This is the same as ``'g'``, except that it uses |
448 | | the current locale setting to insert the appropriate |
449 | | number separator characters. |
450 +---------+----------------------------------------------------------+
451 | ``'%'`` | Percentage. Multiplies the number by 100 and displays |
452 | | in fixed (``'f'``) format, followed by a percent sign. |
453 +---------+----------------------------------------------------------+
454 | None | the same as ``'g'`` |
455 +---------+----------------------------------------------------------+
456
457
Georg Brandl8ec7f652007-08-15 14:28:01 +0000458Template strings
459----------------
460
461Templates provide simpler string substitutions as described in :pep:`292`.
462Instead of the normal ``%``\ -based substitutions, Templates support ``$``\
463-based substitutions, using the following rules:
464
465* ``$$`` is an escape; it is replaced with a single ``$``.
466
467* ``$identifier`` names a substitution placeholder matching a mapping key of
468 ``"identifier"``. By default, ``"identifier"`` must spell a Python
469 identifier. The first non-identifier character after the ``$`` character
470 terminates this placeholder specification.
471
472* ``${identifier}`` is equivalent to ``$identifier``. It is required when valid
473 identifier characters follow the placeholder but are not part of the
474 placeholder, such as ``"${noun}ification"``.
475
476Any other appearance of ``$`` in the string will result in a :exc:`ValueError`
477being raised.
478
479.. versionadded:: 2.4
480
481The :mod:`string` module provides a :class:`Template` class that implements
482these rules. The methods of :class:`Template` are:
483
484
485.. class:: Template(template)
486
487 The constructor takes a single argument which is the template string.
488
489
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000490 .. method:: substitute(mapping[, **kws])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000491
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000492 Performs the template substitution, returning a new string. *mapping* is
493 any dictionary-like object with keys that match the placeholders in the
494 template. Alternatively, you can provide keyword arguments, where the
495 keywords are the placeholders. When both *mapping* and *kws* are given
496 and there are duplicates, the placeholders from *kws* take precedence.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000497
498
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000499 .. method:: safe_substitute(mapping[, **kws])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000500
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000501 Like :meth:`substitute`, except that if placeholders are missing from
502 *mapping* and *kws*, instead of raising a :exc:`KeyError` exception, the
503 original placeholder will appear in the resulting string intact. Also,
504 unlike with :meth:`substitute`, any other appearances of the ``$`` will
505 simply return ``$`` instead of raising :exc:`ValueError`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000506
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000507 While other exceptions may still occur, this method is called "safe"
508 because substitutions always tries to return a usable string instead of
509 raising an exception. In another sense, :meth:`safe_substitute` may be
510 anything other than safe, since it will silently ignore malformed
511 templates containing dangling delimiters, unmatched braces, or
512 placeholders that are not valid Python identifiers.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000513
514:class:`Template` instances also provide one public data attribute:
515
516
517.. attribute:: string.template
518
519 This is the object passed to the constructor's *template* argument. In general,
520 you shouldn't change it, but read-only access is not enforced.
521
Georg Brandle8f1b002008-03-22 22:04:10 +0000522Here is an example of how to use a Template:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000523
524 >>> from string import Template
525 >>> s = Template('$who likes $what')
526 >>> s.substitute(who='tim', what='kung pao')
527 'tim likes kung pao'
528 >>> d = dict(who='tim')
529 >>> Template('Give $who $100').substitute(d)
530 Traceback (most recent call last):
531 [...]
532 ValueError: Invalid placeholder in string: line 1, col 10
533 >>> Template('$who likes $what').substitute(d)
534 Traceback (most recent call last):
535 [...]
536 KeyError: 'what'
537 >>> Template('$who likes $what').safe_substitute(d)
538 'tim likes $what'
539
540Advanced usage: you can derive subclasses of :class:`Template` to customize the
541placeholder syntax, delimiter character, or the entire regular expression used
542to parse template strings. To do this, you can override these class attributes:
543
544* *delimiter* -- This is the literal string describing a placeholder introducing
545 delimiter. The default value ``$``. Note that this should *not* be a regular
546 expression, as the implementation will call :meth:`re.escape` on this string as
547 needed.
548
549* *idpattern* -- This is the regular expression describing the pattern for
550 non-braced placeholders (the braces will be added automatically as
551 appropriate). The default value is the regular expression
552 ``[_a-z][_a-z0-9]*``.
553
554Alternatively, you can provide the entire regular expression pattern by
555overriding the class attribute *pattern*. If you do this, the value must be a
556regular expression object with four named capturing groups. The capturing
557groups correspond to the rules given above, along with the invalid placeholder
558rule:
559
560* *escaped* -- This group matches the escape sequence, e.g. ``$$``, in the
561 default pattern.
562
563* *named* -- This group matches the unbraced placeholder name; it should not
564 include the delimiter in capturing group.
565
566* *braced* -- This group matches the brace enclosed placeholder name; it should
567 not include either the delimiter or braces in the capturing group.
568
569* *invalid* -- This group matches any other delimiter pattern (usually a single
570 delimiter), and it should appear last in the regular expression.
571
572
573String functions
574----------------
575
576The following functions are available to operate on string and Unicode objects.
577They are not available as string methods.
578
579
580.. function:: capwords(s)
581
582 Split the argument into words using :func:`split`, capitalize each word using
583 :func:`capitalize`, and join the capitalized words using :func:`join`. Note
584 that this replaces runs of whitespace characters by a single space, and removes
585 leading and trailing whitespace.
586
587
588.. function:: maketrans(from, to)
589
590 Return a translation table suitable for passing to :func:`translate`, that will
591 map each character in *from* into the character at the same position in *to*;
592 *from* and *to* must have the same length.
593
594 .. warning::
595
596 Don't use strings derived from :const:`lowercase` and :const:`uppercase` as
597 arguments; in some locales, these don't have the same length. For case
598 conversions, always use :func:`lower` and :func:`upper`.
599
600
601Deprecated string functions
602---------------------------
603
604The following list of functions are also defined as methods of string and
605Unicode objects; see section :ref:`string-methods` for more information on
606those. You should consider these functions as deprecated, although they will
607not be removed until Python 3.0. The functions defined in this module are:
608
609
610.. function:: atof(s)
611
612 .. deprecated:: 2.0
613 Use the :func:`float` built-in function.
614
615 .. index:: builtin: float
616
617 Convert a string to a floating point number. The string must have the standard
618 syntax for a floating point literal in Python, optionally preceded by a sign
619 (``+`` or ``-``). Note that this behaves identical to the built-in function
620 :func:`float` when passed a string.
621
622 .. note::
623
624 .. index::
625 single: NaN
626 single: Infinity
627
628 When passing in a string, values for NaN and Infinity may be returned, depending
629 on the underlying C library. The specific set of strings accepted which cause
630 these values to be returned depends entirely on the C library and is known to
631 vary.
632
633
634.. function:: atoi(s[, base])
635
636 .. deprecated:: 2.0
637 Use the :func:`int` built-in function.
638
639 .. index:: builtin: eval
640
641 Convert string *s* to an integer in the given *base*. The string must consist
642 of one or more digits, optionally preceded by a sign (``+`` or ``-``). The
643 *base* defaults to 10. If it is 0, a default base is chosen depending on the
644 leading characters of the string (after stripping the sign): ``0x`` or ``0X``
645 means 16, ``0`` means 8, anything else means 10. If *base* is 16, a leading
646 ``0x`` or ``0X`` is always accepted, though not required. This behaves
647 identically to the built-in function :func:`int` when passed a string. (Also
648 note: for a more flexible interpretation of numeric literals, use the built-in
649 function :func:`eval`.)
650
651
652.. function:: atol(s[, base])
653
654 .. deprecated:: 2.0
655 Use the :func:`long` built-in function.
656
657 .. index:: builtin: long
658
659 Convert string *s* to a long integer in the given *base*. The string must
660 consist of one or more digits, optionally preceded by a sign (``+`` or ``-``).
661 The *base* argument has the same meaning as for :func:`atoi`. A trailing ``l``
662 or ``L`` is not allowed, except if the base is 0. Note that when invoked
663 without *base* or with *base* set to 10, this behaves identical to the built-in
664 function :func:`long` when passed a string.
665
666
667.. function:: capitalize(word)
668
669 Return a copy of *word* with only its first character capitalized.
670
671
672.. function:: expandtabs(s[, tabsize])
673
674 Expand tabs in a string replacing them by one or more spaces, depending on the
675 current column and the given tab size. The column number is reset to zero after
676 each newline occurring in the string. This doesn't understand other non-printing
677 characters or escape sequences. The tab size defaults to 8.
678
679
680.. function:: find(s, sub[, start[,end]])
681
682 Return the lowest index in *s* where the substring *sub* is found such that
683 *sub* is wholly contained in ``s[start:end]``. Return ``-1`` on failure.
684 Defaults for *start* and *end* and interpretation of negative values is the same
685 as for slices.
686
687
688.. function:: rfind(s, sub[, start[, end]])
689
690 Like :func:`find` but find the highest index.
691
692
693.. function:: index(s, sub[, start[, end]])
694
695 Like :func:`find` but raise :exc:`ValueError` when the substring is not found.
696
697
698.. function:: rindex(s, sub[, start[, end]])
699
700 Like :func:`rfind` but raise :exc:`ValueError` when the substring is not found.
701
702
703.. function:: count(s, sub[, start[, end]])
704
705 Return the number of (non-overlapping) occurrences of substring *sub* in string
706 ``s[start:end]``. Defaults for *start* and *end* and interpretation of negative
707 values are the same as for slices.
708
709
710.. function:: lower(s)
711
712 Return a copy of *s*, but with upper case letters converted to lower case.
713
714
715.. function:: split(s[, sep[, maxsplit]])
716
717 Return a list of the words of the string *s*. If the optional second argument
718 *sep* is absent or ``None``, the words are separated by arbitrary strings of
719 whitespace characters (space, tab, newline, return, formfeed). If the second
720 argument *sep* is present and not ``None``, it specifies a string to be used as
721 the word separator. The returned list will then have one more item than the
722 number of non-overlapping occurrences of the separator in the string. The
723 optional third argument *maxsplit* defaults to 0. If it is nonzero, at most
724 *maxsplit* number of splits occur, and the remainder of the string is returned
725 as the final element of the list (thus, the list will have at most
726 ``maxsplit+1`` elements).
727
728 The behavior of split on an empty string depends on the value of *sep*. If *sep*
729 is not specified, or specified as ``None``, the result will be an empty list.
730 If *sep* is specified as any string, the result will be a list containing one
731 element which is an empty string.
732
733
734.. function:: rsplit(s[, sep[, maxsplit]])
735
736 Return a list of the words of the string *s*, scanning *s* from the end. To all
737 intents and purposes, the resulting list of words is the same as returned by
738 :func:`split`, except when the optional third argument *maxsplit* is explicitly
739 specified and nonzero. When *maxsplit* is nonzero, at most *maxsplit* number of
740 splits -- the *rightmost* ones -- occur, and the remainder of the string is
741 returned as the first element of the list (thus, the list will have at most
742 ``maxsplit+1`` elements).
743
744 .. versionadded:: 2.4
745
746
747.. function:: splitfields(s[, sep[, maxsplit]])
748
749 This function behaves identically to :func:`split`. (In the past, :func:`split`
750 was only used with one argument, while :func:`splitfields` was only used with
751 two arguments.)
752
753
754.. function:: join(words[, sep])
755
756 Concatenate a list or tuple of words with intervening occurrences of *sep*.
757 The default value for *sep* is a single space character. It is always true that
758 ``string.join(string.split(s, sep), sep)`` equals *s*.
759
760
761.. function:: joinfields(words[, sep])
762
763 This function behaves identically to :func:`join`. (In the past, :func:`join`
764 was only used with one argument, while :func:`joinfields` was only used with two
765 arguments.) Note that there is no :meth:`joinfields` method on string objects;
766 use the :meth:`join` method instead.
767
768
769.. function:: lstrip(s[, chars])
770
771 Return a copy of the string with leading characters removed. If *chars* is
772 omitted or ``None``, whitespace characters are removed. If given and not
773 ``None``, *chars* must be a string; the characters in the string will be
774 stripped from the beginning of the string this method is called on.
775
776 .. versionchanged:: 2.2.3
777 The *chars* parameter was added. The *chars* parameter cannot be passed in
778 earlier 2.2 versions.
779
780
781.. function:: rstrip(s[, chars])
782
783 Return a copy of the string with trailing characters removed. If *chars* is
784 omitted or ``None``, whitespace characters are removed. If given and not
785 ``None``, *chars* must be a string; the characters in the string will be
786 stripped from the end of the string this method is called on.
787
788 .. versionchanged:: 2.2.3
789 The *chars* parameter was added. The *chars* parameter cannot be passed in
790 earlier 2.2 versions.
791
792
793.. function:: strip(s[, chars])
794
795 Return a copy of the string with leading and trailing characters removed. If
796 *chars* is omitted or ``None``, whitespace characters are removed. If given and
797 not ``None``, *chars* must be a string; the characters in the string will be
798 stripped from the both ends of the string this method is called on.
799
800 .. versionchanged:: 2.2.3
801 The *chars* parameter was added. The *chars* parameter cannot be passed in
802 earlier 2.2 versions.
803
804
805.. function:: swapcase(s)
806
807 Return a copy of *s*, but with lower case letters converted to upper case and
808 vice versa.
809
810
811.. function:: translate(s, table[, deletechars])
812
813 Delete all characters from *s* that are in *deletechars* (if present), and then
814 translate the characters using *table*, which must be a 256-character string
815 giving the translation for each character value, indexed by its ordinal. If
816 *table* is ``None``, then only the character deletion step is performed.
817
818
819.. function:: upper(s)
820
821 Return a copy of *s*, but with lower case letters converted to upper case.
822
823
824.. function:: ljust(s, width)
825 rjust(s, width)
826 center(s, width)
827
828 These functions respectively left-justify, right-justify and center a string in
829 a field of given width. They return a string that is at least *width*
830 characters wide, created by padding the string *s* with spaces until the given
831 width on the right, left or both sides. The string is never truncated.
832
833
834.. function:: zfill(s, width)
835
836 Pad a numeric string on the left with zero digits until the given width is
837 reached. Strings starting with a sign are handled correctly.
838
839
840.. function:: replace(str, old, new[, maxreplace])
841
842 Return a copy of string *str* with all occurrences of substring *old* replaced
843 by *new*. If the optional argument *maxreplace* is given, the first
844 *maxreplace* occurrences are replaced.
845