Issue #7270: Add some dedicated unit tests for multi-thread synchronization
[python.git] / Doc / library / string.rst
blobd01ddf1edf8ef2e323a6b2e7907fe5738a0eb9fc
1 :mod:`string` --- Common string operations
2 ==========================================
4 .. module:: string
5    :synopsis: Common string operations.
8 .. index:: module: re
10 The :mod:`string` module contains a number of useful constants and
11 classes, as well as some deprecated legacy functions that are also
12 available as methods on strings. In addition, Python's built-in string
13 classes support the sequence type methods described in the
14 :ref:`typesseq` section, and also the string-specific methods described
15 in the :ref:`string-methods` section. To output formatted strings use
16 template strings or the ``%`` operator described in the
17 :ref:`string-formatting` section. Also, see the :mod:`re` module for
18 string functions based on regular expressions.
21 String constants
22 ----------------
24 The constants defined in this module are:
27 .. data:: ascii_letters
29    The concatenation of the :const:`ascii_lowercase` and :const:`ascii_uppercase`
30    constants described below.  This value is not locale-dependent.
33 .. data:: ascii_lowercase
35    The lowercase letters ``'abcdefghijklmnopqrstuvwxyz'``.  This value is not
36    locale-dependent and will not change.
39 .. data:: ascii_uppercase
41    The uppercase letters ``'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``.  This value is not
42    locale-dependent and will not change.
45 .. data:: digits
47    The string ``'0123456789'``.
50 .. data:: hexdigits
52    The string ``'0123456789abcdefABCDEF'``.
55 .. data:: letters
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.
62 .. data:: lowercase
64    A string containing all the characters that are considered lowercase letters.
65    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.
70 .. data:: octdigits
72    The string ``'01234567'``.
75 .. data:: punctuation
77    String of ASCII characters which are considered punctuation characters in the
78    ``C`` locale.
81 .. data:: printable
83    String of characters which are considered printable.  This is a combination of
84    :const:`digits`, :const:`letters`, :const:`punctuation`, and
85    :const:`whitespace`.
88 .. data:: uppercase
90    A string containing all the characters that are considered uppercase letters.
91    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.
96 .. data:: whitespace
98    A string containing all characters that are considered whitespace. On most
99    systems this includes the characters space, tab, linefeed, return, formfeed, and
100    vertical tab.
103 .. _new-string-formatting:
105 String Formatting
106 -----------------
108 Starting in Python 2.6, the built-in str and unicode classes provide the ability
109 to do complex variable substitutions and value formatting via the
110 :meth:`str.format` method described in :pep:`3101`.  The :class:`Formatter`
111 class in the :mod:`string` module allows you to create and customize your own
112 string formatting behaviors using the same implementation as the built-in
113 :meth:`format` method.
115 .. class:: Formatter
117    The :class:`Formatter` class has the following public methods:
119    .. method:: format(format_string, *args, *kwargs)
121       :meth:`format` is the primary API method.  It takes a format template
122       string, and an arbitrary set of positional and keyword argument.
123       :meth:`format` is just a wrapper that calls :meth:`vformat`.
125    .. method:: vformat(format_string, args, kwargs)
127       This function does the actual work of formatting.  It is exposed as a
128       separate function for cases where you want to pass in a predefined
129       dictionary of arguments, rather than unpacking and repacking the
130       dictionary as individual arguments using the ``*args`` and ``**kwds``
131       syntax.  :meth:`vformat` does the work of breaking up the format template
132       string into character data and replacement fields.  It calls the various
133       methods described below.
135    In addition, the :class:`Formatter` defines a number of methods that are
136    intended to be replaced by subclasses:
138    .. method:: parse(format_string)
140       Loop over the format_string and return an iterable of tuples
141       (*literal_text*, *field_name*, *format_spec*, *conversion*).  This is used
142       by :meth:`vformat` to break the string in to either literal text, or
143       replacement fields.
145       The values in the tuple conceptually represent a span of literal text
146       followed by a single replacement field.  If there is no literal text
147       (which can happen if two replacement fields occur consecutively), then
148       *literal_text* will be a zero-length string.  If there is no replacement
149       field, then the values of *field_name*, *format_spec* and *conversion*
150       will be ``None``.
152    .. method:: get_field(field_name, args, kwargs)
154       Given *field_name* as returned by :meth:`parse` (see above), convert it to
155       an object to be formatted.  Returns a tuple (obj, used_key).  The default
156       version takes strings of the form defined in :pep:`3101`, such as
157       "0[name]" or "label.title".  *args* and *kwargs* are as passed in to
158       :meth:`vformat`.  The return value *used_key* has the same meaning as the
159       *key* parameter to :meth:`get_value`.
161    .. method:: get_value(key, args, kwargs)
163       Retrieve a given field value.  The *key* argument will be either an
164       integer or a string.  If it is an integer, it represents the index of the
165       positional argument in *args*; if it is a string, then it represents a
166       named argument in *kwargs*.
168       The *args* parameter is set to the list of positional arguments to
169       :meth:`vformat`, and the *kwargs* parameter is set to the dictionary of
170       keyword arguments.
172       For compound field names, these functions are only called for the first
173       component of the field name; Subsequent components are handled through
174       normal attribute and indexing operations.
176       So for example, the field expression '0.name' would cause
177       :meth:`get_value` to be called with a *key* argument of 0.  The ``name``
178       attribute will be looked up after :meth:`get_value` returns by calling the
179       built-in :func:`getattr` function.
181       If the index or keyword refers to an item that does not exist, then an
182       :exc:`IndexError` or :exc:`KeyError` should be raised.
184    .. method:: check_unused_args(used_args, args, kwargs)
186       Implement checking for unused arguments if desired.  The arguments to this
187       function is the set of all argument keys that were actually referred to in
188       the format string (integers for positional arguments, and strings for
189       named arguments), and a reference to the *args* and *kwargs* that was
190       passed to vformat.  The set of unused args can be calculated from these
191       parameters.  :meth:`check_unused_args` is assumed to throw an exception if
192       the check fails.
194    .. method:: format_field(value, format_spec)
196       :meth:`format_field` simply calls the global :func:`format` built-in.  The
197       method is provided so that subclasses can override it.
199    .. method:: convert_field(value, conversion)
201       Converts the value (returned by :meth:`get_field`) given a conversion type
202       (as in the tuple returned by the :meth:`parse` method.)  The default
203       version understands 'r' (repr) and 's' (str) conversion types.
206 .. _formatstrings:
208 Format String Syntax
209 --------------------
211 The :meth:`str.format` method and the :class:`Formatter` class share the same
212 syntax for format strings (although in the case of :class:`Formatter`,
213 subclasses can define their own format string syntax.)
215 Format strings contain "replacement fields" surrounded by curly braces ``{}``.
216 Anything that is not contained in braces is considered literal text, which is
217 copied unchanged to the output.  If you need to include a brace character in the
218 literal text, it can be escaped by doubling: ``{{`` and ``}}``.
220 The grammar for a replacement field is as follows:
222    .. productionlist:: sf
223       replacement_field: "{" [`field_name`] ["!" `conversion`] [":" `format_spec`] "}"
224       field_name: arg_name ("." `attribute_name` | "[" `element_index` "]")*
225       arg_name: (`identifier` | `integer`)?
226       attribute_name: `identifier`
227       element_index: `integer`
228       conversion: "r" | "s"
229       format_spec: <described in the next section>
231 In less formal terms, the replacement field can start with a *field_name* that specifies
232 the object whose value is to be formatted and inserted
233 into the output instead of the replacement field.
234 The *field_name* is optionally followed by a  *conversion* field, which is
235 preceded by an exclamation point ``'!'``, and a *format_spec*, which is preceded
236 by a colon ``':'``.  These specify a non-default format for the replacement value.
238 The *field_name* itself begins with an *arg_name* that is either either a number or a
239 keyword.  If it's a number, it refers to a positional argument, and if it's a keyword,
240 it refers to a named keyword argument.  If the numerical arg_names in a format string
241 are 0, 1, 2, ... in sequence, they can all be omitted (not just some)
242 and the numbers 0, 1, 2, ... will be automatically inserted in that order.
243 The *arg_name* can be followed by any number of index or
244 attribute expressions. An expression of the form ``'.name'`` selects the named
245 attribute using :func:`getattr`, while an expression of the form ``'[index]'``
246 does an index lookup using :func:`__getitem__`.
248 Some simple format string examples::
250    "First, thou shalt count to {0}" # References first positional argument
251    "Bring me a {}"                  # Implicitly references the first positional argument
252    "From {} to {}"                  # Same as "From {0} to {1}"
253    "My quest is {name}"             # References keyword argument 'name'
254    "Weight in tons {0.weight}"      # 'weight' attribute of first positional arg
255    "Units destroyed: {players[0]}"  # First element of keyword argument 'players'.
257 The *conversion* field causes a type coercion before formatting.  Normally, the
258 job of formatting a value is done by the :meth:`__format__` method of the value
259 itself.  However, in some cases it is desirable to force a type to be formatted
260 as a string, overriding its own definition of formatting.  By converting the
261 value to a string before calling :meth:`__format__`, the normal formatting logic
262 is bypassed.
264 Two conversion flags are currently supported: ``'!s'`` which calls :func:`str`
265 on the value, and ``'!r'`` which calls :func:`repr`.
267 Some examples::
269    "Harold's a clever {0!s}"        # Calls str() on the argument first
270    "Bring out the holy {name!r}"    # Calls repr() on the argument first
272 The *format_spec* field contains a specification of how the value should be
273 presented, including such details as field width, alignment, padding, decimal
274 precision and so on.  Each value type can define it's own "formatting
275 mini-language" or interpretation of the *format_spec*.
277 Most built-in types support a common formatting mini-language, which is
278 described in the next section.
280 A *format_spec* field can also include nested replacement fields within it.
281 These nested replacement fields can contain only a field name; conversion flags
282 and format specifications are not allowed.  The replacement fields within the
283 format_spec are substituted before the *format_spec* string is interpreted.
284 This allows the formatting of a value to be dynamically specified.
286 For example, suppose you wanted to have a replacement field whose field width is
287 determined by another variable::
289    "A man with two {0:{1}}".format("noses", 10)
291 This would first evaluate the inner replacement field, making the format string
292 effectively::
294    "A man with two {0:10}"
296 Then the outer replacement field would be evaluated, producing::
298    "noses     "
300 Which is substituted into the string, yielding::
302    "A man with two noses     "
304 (The extra space is because we specified a field width of 10, and because left
305 alignment is the default for strings.)
308 .. _formatspec:
310 Format Specification Mini-Language
311 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
313 "Format specifications" are used within replacement fields contained within a
314 format string to define how individual values are presented (see
315 :ref:`formatstrings`.)  They can also be passed directly to the built-in
316 :func:`format` function.  Each formattable type may define how the format
317 specification is to be interpreted.
319 Most built-in types implement the following options for format specifications,
320 although some of the formatting options are only supported by the numeric types.
322 A general convention is that an empty format string (``""``) produces the same
323 result as if you had called :func:`str` on the value.
325 The general form of a *standard format specifier* is:
327 .. productionlist:: sf
328    format_spec: [[`fill`]`align`][`sign`][#][0][`width`][,][.`precision`][`type`]
329    fill: <a character other than '}'>
330    align: "<" | ">" | "=" | "^"
331    sign: "+" | "-" | " "
332    width: `integer`
333    precision: `integer`
334    type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "x" | "X" | "%"
336 The *fill* character can be any character other than '}' (which signifies the
337 end of the field).  The presence of a fill character is signaled by the *next*
338 character, which must be one of the alignment options. If the second character
339 of *format_spec* is not a valid alignment option, then it is assumed that both
340 the fill character and the alignment option are absent.
342 The meaning of the various alignment options is as follows:
344    +---------+----------------------------------------------------------+
345    | Option  | Meaning                                                  |
346    +=========+==========================================================+
347    | ``'<'`` | Forces the field to be left-aligned within the available |
348    |         | space (This is the default.)                             |
349    +---------+----------------------------------------------------------+
350    | ``'>'`` | Forces the field to be right-aligned within the          |
351    |         | available space.                                         |
352    +---------+----------------------------------------------------------+
353    | ``'='`` | Forces the padding to be placed after the sign (if any)  |
354    |         | but before the digits.  This is used for printing fields |
355    |         | in the form '+000000120'. This alignment option is only  |
356    |         | valid for numeric types.                                 |
357    +---------+----------------------------------------------------------+
358    | ``'^'`` | Forces the field to be centered within the available     |
359    |         | space.                                                   |
360    +---------+----------------------------------------------------------+
362 Note that unless a minimum field width is defined, the field width will always
363 be the same size as the data to fill it, so that the alignment option has no
364 meaning in this case.
366 The *sign* option is only valid for number types, and can be one of the
367 following:
369    +---------+----------------------------------------------------------+
370    | Option  | Meaning                                                  |
371    +=========+==========================================================+
372    | ``'+'`` | indicates that a sign should be used for both            |
373    |         | positive as well as negative numbers.                    |
374    +---------+----------------------------------------------------------+
375    | ``'-'`` | indicates that a sign should be used only for negative   |
376    |         | numbers (this is the default behavior).                  |
377    +---------+----------------------------------------------------------+
378    | space   | indicates that a leading space should be used on         |
379    |         | positive numbers, and a minus sign on negative numbers.  |
380    +---------+----------------------------------------------------------+
382 The ``'#'`` option is only valid for integers, and only for binary, octal, or
383 hexadecimal output.  If present, it specifies that the output will be prefixed
384 by ``'0b'``, ``'0o'``, or ``'0x'``, respectively.
386 The ``','`` option signals the use of a comma for a thousands separator.
387 For a locale aware separator, use the ``'n'`` integer presentation type
388 instead.
390 *width* is a decimal integer defining the minimum field width.  If not
391 specified, then the field width will be determined by the content.
393 If the *width* field is preceded by a zero (``'0'``) character, this enables
394 zero-padding.  This is equivalent to an *alignment* type of ``'='`` and a *fill*
395 character of ``'0'``.
397 The *precision* is a decimal number indicating how many digits should be
398 displayed after the decimal point for a floating point value formatted with
399 ``'f'`` and ``'F'``, or before and after the decimal point for a floating point
400 value formatted with ``'g'`` or ``'G'``.  For non-number types the field
401 indicates the maximum field size - in other words, how many characters will be
402 used from the field content. The *precision* is not allowed for integer values.
404 Finally, the *type* determines how the data should be presented.
406 The available integer presentation types are:
408    +---------+----------------------------------------------------------+
409    | Type    | Meaning                                                  |
410    +=========+==========================================================+
411    | ``'b'`` | Binary format. Outputs the number in base 2.             |
412    +---------+----------------------------------------------------------+
413    | ``'c'`` | Character. Converts the integer to the corresponding     |
414    |         | unicode character before printing.                       |
415    +---------+----------------------------------------------------------+
416    | ``'d'`` | Decimal Integer. Outputs the number in base 10.          |
417    +---------+----------------------------------------------------------+
418    | ``'o'`` | Octal format. Outputs the number in base 8.              |
419    +---------+----------------------------------------------------------+
420    | ``'x'`` | Hex format. Outputs the number in base 16, using lower-  |
421    |         | case letters for the digits above 9.                     |
422    +---------+----------------------------------------------------------+
423    | ``'X'`` | Hex format. Outputs the number in base 16, using upper-  |
424    |         | case letters for the digits above 9.                     |
425    +---------+----------------------------------------------------------+
426    | ``'n'`` | Number. This is the same as ``'d'``, except that it uses |
427    |         | the current locale setting to insert the appropriate     |
428    |         | number separator characters.                             |
429    +---------+----------------------------------------------------------+
430    | None    | The same as ``'d'``.                                     |
431    +---------+----------------------------------------------------------+
433 The available presentation types for floating point and decimal values are:
435    +---------+----------------------------------------------------------+
436    | Type    | Meaning                                                  |
437    +=========+==========================================================+
438    | ``'e'`` | Exponent notation. Prints the number in scientific       |
439    |         | notation using the letter 'e' to indicate the exponent.  |
440    +---------+----------------------------------------------------------+
441    | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an     |
442    |         | upper case 'E' as the separator character.               |
443    +---------+----------------------------------------------------------+
444    | ``'f'`` | Fixed point. Displays the number as a fixed-point        |
445    |         | number.                                                  |
446    +---------+----------------------------------------------------------+
447    | ``'F'`` | Fixed point. Same as ``'f'``.                            |
448    +---------+----------------------------------------------------------+
449    | ``'g'`` | General format.  For a given precision ``p >= 1``,       |
450    |         | this rounds the number to ``p`` significant digits and   |
451    |         | then formats the result in either fixed-point format     |
452    |         | or in scientific notation, depending on its magnitude.   |
453    |         |                                                          |
454    |         | The precise rules are as follows: suppose that the       |
455    |         | result formatted with presentation type ``'e'`` and      |
456    |         | precision ``p-1`` would have exponent ``exp``.  Then     |
457    |         | if ``-4 <= exp < p``, the number is formatted            |
458    |         | with presentation type ``'f'`` and precision             |
459    |         | ``p-1-exp``.  Otherwise, the number is formatted         |
460    |         | with presentation type ``'e'`` and precision ``p-1``.    |
461    |         | In both cases insignificant trailing zeros are removed   |
462    |         | from the significand, and the decimal point is also      |
463    |         | removed if there are no remaining digits following it.   |
464    |         |                                                          |
465    |         | Postive and negative infinity, positive and negative     |
466    |         | zero, and nans, are formatted as ``inf``, ``-inf``,      |
467    |         | ``0``, ``-0`` and ``nan`` respectively, regardless of    |
468    |         | the precision.                                           |
469    |         |                                                          |
470    |         | A precision of ``0`` is treated as equivalent to a       |
471    |         | precision of ``1``.                                      |
472    +---------+----------------------------------------------------------+
473    | ``'G'`` | General format. Same as ``'g'`` except switches to       |
474    |         | ``'E'`` if the number gets too large. The                |
475    |         | representations of infinity and NaN are uppercased, too. |
476    +---------+----------------------------------------------------------+
477    | ``'n'`` | Number. This is the same as ``'g'``, except that it uses |
478    |         | the current locale setting to insert the appropriate     |
479    |         | number separator characters.                             |
480    +---------+----------------------------------------------------------+
481    | ``'%'`` | Percentage. Multiplies the number by 100 and displays    |
482    |         | in fixed (``'f'``) format, followed by a percent sign.   |
483    +---------+----------------------------------------------------------+
484    | None    | The same as ``'g'``.                                     |
485    +---------+----------------------------------------------------------+
488 Template strings
489 ----------------
491 Templates provide simpler string substitutions as described in :pep:`292`.
492 Instead of the normal ``%``\ -based substitutions, Templates support ``$``\
493 -based substitutions, using the following rules:
495 * ``$$`` is an escape; it is replaced with a single ``$``.
497 * ``$identifier`` names a substitution placeholder matching a mapping key of
498   ``"identifier"``.  By default, ``"identifier"`` must spell a Python
499   identifier.  The first non-identifier character after the ``$`` character
500   terminates this placeholder specification.
502 * ``${identifier}`` is equivalent to ``$identifier``.  It is required when valid
503   identifier characters follow the placeholder but are not part of the
504   placeholder, such as ``"${noun}ification"``.
506 Any other appearance of ``$`` in the string will result in a :exc:`ValueError`
507 being raised.
509 .. versionadded:: 2.4
511 The :mod:`string` module provides a :class:`Template` class that implements
512 these rules.  The methods of :class:`Template` are:
515 .. class:: Template(template)
517    The constructor takes a single argument which is the template string.
520    .. method:: substitute(mapping[, **kws])
522       Performs the template substitution, returning a new string.  *mapping* is
523       any dictionary-like object with keys that match the placeholders in the
524       template.  Alternatively, you can provide keyword arguments, where the
525       keywords are the placeholders.  When both *mapping* and *kws* are given
526       and there are duplicates, the placeholders from *kws* take precedence.
529    .. method:: safe_substitute(mapping[, **kws])
531       Like :meth:`substitute`, except that if placeholders are missing from
532       *mapping* and *kws*, instead of raising a :exc:`KeyError` exception, the
533       original placeholder will appear in the resulting string intact.  Also,
534       unlike with :meth:`substitute`, any other appearances of the ``$`` will
535       simply return ``$`` instead of raising :exc:`ValueError`.
537       While other exceptions may still occur, this method is called "safe"
538       because substitutions always tries to return a usable string instead of
539       raising an exception.  In another sense, :meth:`safe_substitute` may be
540       anything other than safe, since it will silently ignore malformed
541       templates containing dangling delimiters, unmatched braces, or
542       placeholders that are not valid Python identifiers.
544 :class:`Template` instances also provide one public data attribute:
547 .. attribute:: string.template
549    This is the object passed to the constructor's *template* argument.  In general,
550    you shouldn't change it, but read-only access is not enforced.
552 Here is an example of how to use a Template:
554    >>> from string import Template
555    >>> s = Template('$who likes $what')
556    >>> s.substitute(who='tim', what='kung pao')
557    'tim likes kung pao'
558    >>> d = dict(who='tim')
559    >>> Template('Give $who $100').substitute(d)
560    Traceback (most recent call last):
561    [...]
562    ValueError: Invalid placeholder in string: line 1, col 10
563    >>> Template('$who likes $what').substitute(d)
564    Traceback (most recent call last):
565    [...]
566    KeyError: 'what'
567    >>> Template('$who likes $what').safe_substitute(d)
568    'tim likes $what'
570 Advanced usage: you can derive subclasses of :class:`Template` to customize the
571 placeholder syntax, delimiter character, or the entire regular expression used
572 to parse template strings.  To do this, you can override these class attributes:
574 * *delimiter* -- This is the literal string describing a placeholder introducing
575   delimiter.  The default value ``$``.  Note that this should *not* be a regular
576   expression, as the implementation will call :meth:`re.escape` on this string as
577   needed.
579 * *idpattern* -- This is the regular expression describing the pattern for
580   non-braced placeholders (the braces will be added automatically as
581   appropriate).  The default value is the regular expression
582   ``[_a-z][_a-z0-9]*``.
584 Alternatively, you can provide the entire regular expression pattern by
585 overriding the class attribute *pattern*.  If you do this, the value must be a
586 regular expression object with four named capturing groups.  The capturing
587 groups correspond to the rules given above, along with the invalid placeholder
588 rule:
590 * *escaped* -- This group matches the escape sequence, e.g. ``$$``, in the
591   default pattern.
593 * *named* -- This group matches the unbraced placeholder name; it should not
594   include the delimiter in capturing group.
596 * *braced* -- This group matches the brace enclosed placeholder name; it should
597   not include either the delimiter or braces in the capturing group.
599 * *invalid* -- This group matches any other delimiter pattern (usually a single
600   delimiter), and it should appear last in the regular expression.
603 String functions
604 ----------------
606 The following functions are available to operate on string and Unicode objects.
607 They are not available as string methods.
610 .. function:: capwords(s[, sep])
612    Split the argument into words using :meth:`str.split`, capitalize each word
613    using :meth:`str.capitalize`, and join the capitalized words using
614    :meth:`str.join`.  If the optional second argument *sep* is absent
615    or ``None``, runs of whitespace characters are replaced by a single space
616    and leading and trailing whitespace are removed, otherwise *sep* is used to
617    split and join the words.
620 .. function:: maketrans(from, to)
622    Return a translation table suitable for passing to :func:`translate`, that will
623    map each character in *from* into the character at the same position in *to*;
624    *from* and *to* must have the same length.
626    .. note::
628       Don't use strings derived from :const:`lowercase` and :const:`uppercase` as
629       arguments; in some locales, these don't have the same length.  For case
630       conversions, always use :meth:`str.lower` and :meth:`str.upper`.
633 Deprecated string functions
634 ---------------------------
636 The following list of functions are also defined as methods of string and
637 Unicode objects; see section :ref:`string-methods` for more information on
638 those.  You should consider these functions as deprecated, although they will
639 not be removed until Python 3.0.  The functions defined in this module are:
642 .. function:: atof(s)
644    .. deprecated:: 2.0
645       Use the :func:`float` built-in function.
647    .. index:: builtin: float
649    Convert a string to a floating point number.  The string must have the standard
650    syntax for a floating point literal in Python, optionally preceded by a sign
651    (``+`` or ``-``).  Note that this behaves identical to the built-in function
652    :func:`float` when passed a string.
654    .. note::
656       .. index::
657          single: NaN
658          single: Infinity
660       When passing in a string, values for NaN and Infinity may be returned, depending
661       on the underlying C library.  The specific set of strings accepted which cause
662       these values to be returned depends entirely on the C library and is known to
663       vary.
666 .. function:: atoi(s[, base])
668    .. deprecated:: 2.0
669       Use the :func:`int` built-in function.
671    .. index:: builtin: eval
673    Convert string *s* to an integer in the given *base*.  The string must consist
674    of one or more digits, optionally preceded by a sign (``+`` or ``-``).  The
675    *base* defaults to 10.  If it is 0, a default base is chosen depending on the
676    leading characters of the string (after stripping the sign): ``0x`` or ``0X``
677    means 16, ``0`` means 8, anything else means 10.  If *base* is 16, a leading
678    ``0x`` or ``0X`` is always accepted, though not required.  This behaves
679    identically to the built-in function :func:`int` when passed a string.  (Also
680    note: for a more flexible interpretation of numeric literals, use the built-in
681    function :func:`eval`.)
684 .. function:: atol(s[, base])
686    .. deprecated:: 2.0
687       Use the :func:`long` built-in function.
689    .. index:: builtin: long
691    Convert string *s* to a long integer in the given *base*. The string must
692    consist of one or more digits, optionally preceded by a sign (``+`` or ``-``).
693    The *base* argument has the same meaning as for :func:`atoi`.  A trailing ``l``
694    or ``L`` is not allowed, except if the base is 0.  Note that when invoked
695    without *base* or with *base* set to 10, this behaves identical to the built-in
696    function :func:`long` when passed a string.
699 .. function:: capitalize(word)
701    Return a copy of *word* with only its first character capitalized.
704 .. function:: expandtabs(s[, tabsize])
706    Expand tabs in a string replacing them by one or more spaces, depending on the
707    current column and the given tab size.  The column number is reset to zero after
708    each newline occurring in the string. This doesn't understand other non-printing
709    characters or escape sequences.  The tab size defaults to 8.
712 .. function:: find(s, sub[, start[,end]])
714    Return the lowest index in *s* where the substring *sub* is found such that
715    *sub* is wholly contained in ``s[start:end]``.  Return ``-1`` on failure.
716    Defaults for *start* and *end* and interpretation of negative values is the same
717    as for slices.
720 .. function:: rfind(s, sub[, start[, end]])
722    Like :func:`find` but find the highest index.
725 .. function:: index(s, sub[, start[, end]])
727    Like :func:`find` but raise :exc:`ValueError` when the substring is not found.
730 .. function:: rindex(s, sub[, start[, end]])
732    Like :func:`rfind` but raise :exc:`ValueError` when the substring is not found.
735 .. function:: count(s, sub[, start[, end]])
737    Return the number of (non-overlapping) occurrences of substring *sub* in string
738    ``s[start:end]``. Defaults for *start* and *end* and interpretation of negative
739    values are the same as for slices.
742 .. function:: lower(s)
744    Return a copy of *s*, but with upper case letters converted to lower case.
747 .. function:: split(s[, sep[, maxsplit]])
749    Return a list of the words of the string *s*.  If the optional second argument
750    *sep* is absent or ``None``, the words are separated by arbitrary strings of
751    whitespace characters (space, tab,  newline, return, formfeed).  If the second
752    argument *sep* is present and not ``None``, it specifies a string to be used as
753    the  word separator.  The returned list will then have one more item than the
754    number of non-overlapping occurrences of the separator in the string.  The
755    optional third argument *maxsplit* defaults to 0.  If it is nonzero, at most
756    *maxsplit* number of splits occur, and the remainder of the string is returned
757    as the final element of the list (thus, the list will have at most
758    ``maxsplit+1`` elements).
760    The behavior of split on an empty string depends on the value of *sep*. If *sep*
761    is not specified, or specified as ``None``, the result will be an empty list.
762    If *sep* is specified as any string, the result will be a list containing one
763    element which is an empty string.
766 .. function:: rsplit(s[, sep[, maxsplit]])
768    Return a list of the words of the string *s*, scanning *s* from the end.  To all
769    intents and purposes, the resulting list of words is the same as returned by
770    :func:`split`, except when the optional third argument *maxsplit* is explicitly
771    specified and nonzero.  When *maxsplit* is nonzero, at most *maxsplit* number of
772    splits -- the *rightmost* ones -- occur, and the remainder of the string is
773    returned as the first element of the list (thus, the list will have at most
774    ``maxsplit+1`` elements).
776    .. versionadded:: 2.4
779 .. function:: splitfields(s[, sep[, maxsplit]])
781    This function behaves identically to :func:`split`.  (In the past, :func:`split`
782    was only used with one argument, while :func:`splitfields` was only used with
783    two arguments.)
786 .. function:: join(words[, sep])
788    Concatenate a list or tuple of words with intervening occurrences of  *sep*.
789    The default value for *sep* is a single space character.  It is always true that
790    ``string.join(string.split(s, sep), sep)`` equals *s*.
793 .. function:: joinfields(words[, sep])
795    This function behaves identically to :func:`join`.  (In the past,  :func:`join`
796    was only used with one argument, while :func:`joinfields` was only used with two
797    arguments.) Note that there is no :meth:`joinfields` method on string objects;
798    use the :meth:`join` method instead.
801 .. function:: lstrip(s[, chars])
803    Return a copy of the string with leading characters removed.  If *chars* is
804    omitted or ``None``, whitespace characters are removed.  If given and not
805    ``None``, *chars* must be a string; the characters in the string will be
806    stripped from the beginning of the string this method is called on.
808    .. versionchanged:: 2.2.3
809       The *chars* parameter was added.  The *chars* parameter cannot be passed in
810       earlier 2.2 versions.
813 .. function:: rstrip(s[, chars])
815    Return a copy of the string with trailing characters removed.  If *chars* is
816    omitted or ``None``, whitespace characters are removed.  If given and not
817    ``None``, *chars* must be a string; the characters in the string will be
818    stripped from the end of the string this method is called on.
820    .. versionchanged:: 2.2.3
821       The *chars* parameter was added.  The *chars* parameter cannot be passed in
822       earlier 2.2 versions.
825 .. function:: strip(s[, chars])
827    Return a copy of the string with leading and trailing characters removed.  If
828    *chars* is omitted or ``None``, whitespace characters are removed.  If given and
829    not ``None``, *chars* must be a string; the characters in the string will be
830    stripped from the both ends of the string this method is called on.
832    .. versionchanged:: 2.2.3
833       The *chars* parameter was added.  The *chars* parameter cannot be passed in
834       earlier 2.2 versions.
837 .. function:: swapcase(s)
839    Return a copy of *s*, but with lower case letters converted to upper case and
840    vice versa.
843 .. function:: translate(s, table[, deletechars])
845    Delete all characters from *s* that are in *deletechars* (if  present), and then
846    translate the characters using *table*, which  must be a 256-character string
847    giving the translation for each character value, indexed by its ordinal.  If
848    *table* is ``None``, then only the character deletion step is performed.
851 .. function:: upper(s)
853    Return a copy of *s*, but with lower case letters converted to upper case.
856 .. function:: ljust(s, width[, fillchar])
857               rjust(s, width[, fillchar])
858               center(s, width[, fillchar])
860    These functions respectively left-justify, right-justify and center a string in
861    a field of given width.  They return a string that is at least *width*
862    characters wide, created by padding the string *s* with the character *fillchar*
863    (default is a space) until the given width on the right, left or both sides.
864    The string is never truncated.
867 .. function:: zfill(s, width)
869    Pad a numeric string on the left with zero digits until the given width is
870    reached.  Strings starting with a sign are handled correctly.
873 .. function:: replace(str, old, new[, maxreplace])
875    Return a copy of string *str* with all occurrences of substring *old* replaced
876    by *new*.  If the optional argument *maxreplace* is given, the first
877    *maxreplace* occurrences are replaced.