/Doc/library/stdtypes.rst
http://unladen-swallow.googlecode.com/ · ReStructuredText · 2723 lines · 1927 code · 796 blank · 0 comment · 0 complexity · b712e452ec171c361e2db790d841e54a MD5 · raw file
Large files are truncated click here to view the full file
- .. XXX: reference/datamodel and this have quite a few overlaps!
- .. _bltin-types:
- **************
- Built-in Types
- **************
- The following sections describe the standard types that are built into the
- interpreter.
- .. note::
- Historically (until release 2.2), Python's built-in types have differed from
- user-defined types because it was not possible to use the built-in types as the
- basis for object-oriented inheritance. This limitation no longer
- exists.
- .. index:: pair: built-in; types
- The principal built-in types are numerics, sequences, mappings, files, classes,
- instances and exceptions.
- .. index:: statement: print
- Some operations are supported by several object types; in particular,
- practically all objects can be compared, tested for truth value, and converted
- to a string (with the :func:`repr` function or the slightly different
- :func:`str` function). The latter function is implicitly used when an object is
- written by the :func:`print` function.
- .. _truth:
- Truth Value Testing
- ===================
- .. index::
- statement: if
- statement: while
- pair: truth; value
- pair: Boolean; operations
- single: false
- Any object can be tested for truth value, for use in an :keyword:`if` or
- :keyword:`while` condition or as operand of the Boolean operations below. The
- following values are considered false:
- .. index:: single: None (Built-in object)
- * ``None``
- .. index:: single: False (Built-in object)
- * ``False``
- * zero of any numeric type, for example, ``0``, ``0L``, ``0.0``, ``0j``.
- * any empty sequence, for example, ``''``, ``()``, ``[]``.
- * any empty mapping, for example, ``{}``.
- * instances of user-defined classes, if the class defines a :meth:`__nonzero__`
- or :meth:`__len__` method, when that method returns the integer zero or
- :class:`bool` value ``False``. [#]_
- .. index:: single: true
- All other values are considered true --- so objects of many types are always
- true.
- .. index::
- operator: or
- operator: and
- single: False
- single: True
- Operations and built-in functions that have a Boolean result always return ``0``
- or ``False`` for false and ``1`` or ``True`` for true, unless otherwise stated.
- (Important exception: the Boolean operations ``or`` and ``and`` always return
- one of their operands.)
- .. _boolean:
- Boolean Operations --- :keyword:`and`, :keyword:`or`, :keyword:`not`
- ====================================================================
- .. index:: pair: Boolean; operations
- These are the Boolean operations, ordered by ascending priority:
- +-------------+---------------------------------+-------+
- | Operation | Result | Notes |
- +=============+=================================+=======+
- | ``x or y`` | if *x* is false, then *y*, else | \(1) |
- | | *x* | |
- +-------------+---------------------------------+-------+
- | ``x and y`` | if *x* is false, then *x*, else | \(2) |
- | | *y* | |
- +-------------+---------------------------------+-------+
- | ``not x`` | if *x* is false, then ``True``, | \(3) |
- | | else ``False`` | |
- +-------------+---------------------------------+-------+
- .. index::
- operator: and
- operator: or
- operator: not
- Notes:
- (1)
- This is a short-circuit operator, so it only evaluates the second
- argument if the first one is :const:`False`.
- (2)
- This is a short-circuit operator, so it only evaluates the second
- argument if the first one is :const:`True`.
- (3)
- ``not`` has a lower priority than non-Boolean operators, so ``not a == b`` is
- interpreted as ``not (a == b)``, and ``a == not b`` is a syntax error.
- .. _stdcomparisons:
- Comparisons
- ===========
- .. index:: pair: chaining; comparisons
- Comparison operations are supported by all objects. They all have the same
- priority (which is higher than that of the Boolean operations). Comparisons can
- be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and
- y <= z``, except that *y* is evaluated only once (but in both cases *z* is not
- evaluated at all when ``x < y`` is found to be false).
- This table summarizes the comparison operations:
- +------------+-------------------------+-------+
- | Operation | Meaning | Notes |
- +============+=========================+=======+
- | ``<`` | strictly less than | |
- +------------+-------------------------+-------+
- | ``<=`` | less than or equal | |
- +------------+-------------------------+-------+
- | ``>`` | strictly greater than | |
- +------------+-------------------------+-------+
- | ``>=`` | greater than or equal | |
- +------------+-------------------------+-------+
- | ``==`` | equal | |
- +------------+-------------------------+-------+
- | ``!=`` | not equal | \(1) |
- +------------+-------------------------+-------+
- | ``is`` | object identity | |
- +------------+-------------------------+-------+
- | ``is not`` | negated object identity | |
- +------------+-------------------------+-------+
- .. index::
- pair: operator; comparison
- operator: ==
- operator: <
- operator: <=
- operator: >
- operator: >=
- operator: !=
- operator: is
- operator: is not
- Notes:
- (1)
- ``!=`` can also be written ``<>``, but this is an obsolete usage
- kept for backwards compatibility only. New code should always use
- ``!=``.
- .. index::
- pair: object; numeric
- pair: objects; comparing
- Objects of different types, except different numeric types and different string
- types, never compare equal; such objects are ordered consistently but
- arbitrarily (so that sorting a heterogeneous array yields a consistent result).
- Furthermore, some types (for example, file objects) support only a degenerate
- notion of comparison where any two objects of that type are unequal. Again,
- such objects are ordered arbitrarily but consistently. The ``<``, ``<=``, ``>``
- and ``>=`` operators will raise a :exc:`TypeError` exception when any operand is
- a complex number.
- .. index:: single: __cmp__() (instance method)
- Instances of a class normally compare as non-equal unless the class defines the
- :meth:`__cmp__` method. Refer to :ref:`customization`) for information on the
- use of this method to effect object comparisons.
- **Implementation note:** Objects of different types except numbers are ordered
- by their type names; objects of the same types that don't support proper
- comparison are ordered by their address.
- .. index::
- operator: in
- operator: not in
- Two more operations with the same syntactic priority, ``in`` and ``not in``, are
- supported only by sequence types (below).
- .. _typesnumeric:
- Numeric Types --- :class:`int`, :class:`float`, :class:`long`, :class:`complex`
- ===============================================================================
- .. index::
- object: numeric
- object: Boolean
- object: integer
- object: long integer
- object: floating point
- object: complex number
- pair: C; language
- There are four distinct numeric types: :dfn:`plain integers`, :dfn:`long
- integers`, :dfn:`floating point numbers`, and :dfn:`complex numbers`. In
- addition, Booleans are a subtype of plain integers. Plain integers (also just
- called :dfn:`integers`) are implemented using :ctype:`long` in C, which gives
- them at least 32 bits of precision (``sys.maxint`` is always set to the maximum
- plain integer value for the current platform, the minimum value is
- ``-sys.maxint - 1``). Long integers have unlimited precision. Floating point
- numbers are implemented using :ctype:`double` in C. All bets on their precision
- are off unless you happen to know the machine you are working with.
- Complex numbers have a real and imaginary part, which are each implemented using
- :ctype:`double` in C. To extract these parts from a complex number *z*, use
- ``z.real`` and ``z.imag``.
- .. index::
- pair: numeric; literals
- pair: integer; literals
- triple: long; integer; literals
- pair: floating point; literals
- pair: complex number; literals
- pair: hexadecimal; literals
- pair: octal; literals
- Numbers are created by numeric literals or as the result of built-in functions
- and operators. Unadorned integer literals (including binary, hex, and octal
- numbers) yield plain integers unless the value they denote is too large to be
- represented as a plain integer, in which case they yield a long integer.
- Integer literals with an ``'L'`` or ``'l'`` suffix yield long integers (``'L'``
- is preferred because ``1l`` looks too much like eleven!). Numeric literals
- containing a decimal point or an exponent sign yield floating point numbers.
- Appending ``'j'`` or ``'J'`` to a numeric literal yields a complex number with a
- zero real part. A complex numeric literal is the sum of a real and an imaginary
- part.
- .. index::
- single: arithmetic
- builtin: int
- builtin: long
- builtin: float
- builtin: complex
- Python fully supports mixed arithmetic: when a binary arithmetic operator has
- operands of different numeric types, the operand with the "narrower" type is
- widened to that of the other, where plain integer is narrower than long integer
- is narrower than floating point is narrower than complex. Comparisons between
- numbers of mixed type use the same rule. [#]_ The constructors :func:`int`,
- :func:`long`, :func:`float`, and :func:`complex` can be used to produce numbers
- of a specific type.
- All builtin numeric types support the following operations. See
- :ref:`power` and later sections for the operators' priorities.
- +--------------------+---------------------------------+--------+
- | Operation | Result | Notes |
- +====================+=================================+========+
- | ``x + y`` | sum of *x* and *y* | |
- +--------------------+---------------------------------+--------+
- | ``x - y`` | difference of *x* and *y* | |
- +--------------------+---------------------------------+--------+
- | ``x * y`` | product of *x* and *y* | |
- +--------------------+---------------------------------+--------+
- | ``x / y`` | quotient of *x* and *y* | \(1) |
- +--------------------+---------------------------------+--------+
- | ``x // y`` | (floored) quotient of *x* and | (4)(5) |
- | | *y* | |
- +--------------------+---------------------------------+--------+
- | ``x % y`` | remainder of ``x / y`` | \(4) |
- +--------------------+---------------------------------+--------+
- | ``-x`` | *x* negated | |
- +--------------------+---------------------------------+--------+
- | ``+x`` | *x* unchanged | |
- +--------------------+---------------------------------+--------+
- | ``abs(x)`` | absolute value or magnitude of | \(3) |
- | | *x* | |
- +--------------------+---------------------------------+--------+
- | ``int(x)`` | *x* converted to integer | \(2) |
- +--------------------+---------------------------------+--------+
- | ``long(x)`` | *x* converted to long integer | \(2) |
- +--------------------+---------------------------------+--------+
- | ``float(x)`` | *x* converted to floating point | \(6) |
- +--------------------+---------------------------------+--------+
- | ``complex(re,im)`` | a complex number with real part | |
- | | *re*, imaginary part *im*. | |
- | | *im* defaults to zero. | |
- +--------------------+---------------------------------+--------+
- | ``c.conjugate()`` | conjugate of the complex number | |
- | | *c*. (Identity on real numbers) | |
- +--------------------+---------------------------------+--------+
- | ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | (3)(4) |
- +--------------------+---------------------------------+--------+
- | ``pow(x, y)`` | *x* to the power *y* | (3)(7) |
- +--------------------+---------------------------------+--------+
- | ``x ** y`` | *x* to the power *y* | \(7) |
- +--------------------+---------------------------------+--------+
- .. index::
- triple: operations on; numeric; types
- single: conjugate() (complex number method)
- Notes:
- (1)
- .. index::
- pair: integer; division
- triple: long; integer; division
- For (plain or long) integer division, the result is an integer. The result is
- always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and
- (-1)/(-2) is 0. Note that the result is a long integer if either operand is a
- long integer, regardless of the numeric value.
- (2)
- .. index::
- module: math
- single: floor() (in module math)
- single: ceil() (in module math)
- single: trunc() (in module math)
- pair: numeric; conversions
- Conversion from floats using :func:`int` or :func:`long` truncates toward
- zero like the related function, :func:`math.trunc`. Use the function
- :func:`math.floor` to round downward and :func:`math.ceil` to round
- upward.
- (3)
- See :ref:`built-in-funcs` for a full description.
- (4)
- Complex floor division operator, modulo operator, and :func:`divmod`.
- .. deprecated:: 2.3
- Instead convert to float using :func:`abs` if appropriate.
- (5)
- Also referred to as integer division. The resultant value is a whole integer,
- though the result's type is not necessarily int.
- (6)
- float also accepts the strings "nan" and "inf" with an optional prefix "+"
- or "-" for Not a Number (NaN) and positive or negative infinity.
- .. versionadded:: 2.6
- (7)
- Python defines ``pow(0, 0)`` and ``0 ** 0`` to be ``1``, as is common for
- programming languages.
- All :class:`numbers.Real` types (:class:`int`, :class:`long`, and
- :class:`float`) also include the following operations:
- +--------------------+------------------------------------+--------+
- | Operation | Result | Notes |
- +====================+====================================+========+
- | ``math.trunc(x)`` | *x* truncated to Integral | |
- +--------------------+------------------------------------+--------+
- | ``round(x[, n])`` | *x* rounded to n digits, | |
- | | rounding half to even. If n is | |
- | | omitted, it defaults to 0. | |
- +--------------------+------------------------------------+--------+
- | ``math.floor(x)`` | the greatest integral float <= *x* | |
- +--------------------+------------------------------------+--------+
- | ``math.ceil(x)`` | the least integral float >= *x* | |
- +--------------------+------------------------------------+--------+
- .. XXXJH exceptions: overflow (when? what operations?) zerodivision
- .. _bitstring-ops:
- Bit-string Operations on Integer Types
- --------------------------------------
- .. _bit-string-operations:
- Plain and long integer types support additional operations that make sense only
- for bit-strings. Negative numbers are treated as their 2's complement value
- (for long integers, this assumes a sufficiently large number of bits that no
- overflow occurs during the operation).
- The priorities of the binary bitwise operations are all lower than the numeric
- operations and higher than the comparisons; the unary operation ``~`` has the
- same priority as the other unary numeric operations (``+`` and ``-``).
- This table lists the bit-string operations sorted in ascending priority:
- +------------+--------------------------------+----------+
- | Operation | Result | Notes |
- +============+================================+==========+
- | ``x | y`` | bitwise :dfn:`or` of *x* and | |
- | | *y* | |
- +------------+--------------------------------+----------+
- | ``x ^ y`` | bitwise :dfn:`exclusive or` of | |
- | | *x* and *y* | |
- +------------+--------------------------------+----------+
- | ``x & y`` | bitwise :dfn:`and` of *x* and | |
- | | *y* | |
- +------------+--------------------------------+----------+
- | ``x << n`` | *x* shifted left by *n* bits | (1)(2) |
- +------------+--------------------------------+----------+
- | ``x >> n`` | *x* shifted right by *n* bits | (1)(3) |
- +------------+--------------------------------+----------+
- | ``~x`` | the bits of *x* inverted | |
- +------------+--------------------------------+----------+
- .. index::
- triple: operations on; integer; types
- pair: bit-string; operations
- pair: shifting; operations
- pair: masking; operations
- Notes:
- (1)
- Negative shift counts are illegal and cause a :exc:`ValueError` to be raised.
- (2)
- A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)``. A
- long integer is returned if the result exceeds the range of plain integers.
- (3)
- A right shift by *n* bits is equivalent to division by ``pow(2, n)``.
- Additional Methods on Float
- ---------------------------
- The float type has some additional methods.
- .. method:: float.as_integer_ratio()
- Return a pair of integers whose ratio is exactly equal to the
- original float and with a positive denominator. Raises
- :exc:`OverflowError` on infinities and a :exc:`ValueError` on
- NaNs.
- .. versionadded:: 2.6
- Two methods support conversion to
- and from hexadecimal strings. Since Python's floats are stored
- internally as binary numbers, converting a float to or from a
- *decimal* string usually involves a small rounding error. In
- contrast, hexadecimal strings allow exact representation and
- specification of floating-point numbers. This can be useful when
- debugging, and in numerical work.
- .. method:: float.hex()
- Return a representation of a floating-point number as a hexadecimal
- string. For finite floating-point numbers, this representation
- will always include a leading ``0x`` and a trailing ``p`` and
- exponent.
- .. versionadded:: 2.6
- .. method:: float.fromhex(s)
- Class method to return the float represented by a hexadecimal
- string *s*. The string *s* may have leading and trailing
- whitespace.
- .. versionadded:: 2.6
- Note that :meth:`float.hex` is an instance method, while
- :meth:`float.fromhex` is a class method.
- A hexadecimal string takes the form::
- [sign] ['0x'] integer ['.' fraction] ['p' exponent]
- where the optional ``sign`` may by either ``+`` or ``-``, ``integer``
- and ``fraction`` are strings of hexadecimal digits, and ``exponent``
- is a decimal integer with an optional leading sign. Case is not
- significant, and there must be at least one hexadecimal digit in
- either the integer or the fraction. This syntax is similar to the
- syntax specified in section 6.4.4.2 of the C99 standard, and also to
- the syntax used in Java 1.5 onwards. In particular, the output of
- :meth:`float.hex` is usable as a hexadecimal floating-point literal in
- C or Java code, and hexadecimal strings produced by C's ``%a`` format
- character or Java's ``Double.toHexString`` are accepted by
- :meth:`float.fromhex`.
- Note that the exponent is written in decimal rather than hexadecimal,
- and that it gives the power of 2 by which to multiply the coefficient.
- For example, the hexadecimal string ``0x3.a7p10`` represents the
- floating-point number ``(3 + 10./16 + 7./16**2) * 2.0**10``, or
- ``3740.0``::
- >>> float.fromhex('0x3.a7p10')
- 3740.0
- Applying the reverse conversion to ``3740.0`` gives a different
- hexadecimal string representing the same number::
- >>> float.hex(3740.0)
- '0x1.d380000000000p+11'
- .. _typeiter:
- Iterator Types
- ==============
- .. versionadded:: 2.2
- .. index::
- single: iterator protocol
- single: protocol; iterator
- single: sequence; iteration
- single: container; iteration over
- Python supports a concept of iteration over containers. This is implemented
- using two distinct methods; these are used to allow user-defined classes to
- support iteration. Sequences, described below in more detail, always support
- the iteration methods.
- One method needs to be defined for container objects to provide iteration
- support:
- .. XXX duplicated in reference/datamodel!
- .. method:: container.__iter__()
- Return an iterator object. The object is required to support the iterator
- protocol described below. If a container supports different types of
- iteration, additional methods can be provided to specifically request
- iterators for those iteration types. (An example of an object supporting
- multiple forms of iteration would be a tree structure which supports both
- breadth-first and depth-first traversal.) This method corresponds to the
- :attr:`tp_iter` slot of the type structure for Python objects in the Python/C
- API.
- The iterator objects themselves are required to support the following two
- methods, which together form the :dfn:`iterator protocol`:
- .. method:: iterator.__iter__()
- Return the iterator object itself. This is required to allow both containers
- and iterators to be used with the :keyword:`for` and :keyword:`in` statements.
- This method corresponds to the :attr:`tp_iter` slot of the type structure for
- Python objects in the Python/C API.
- .. method:: iterator.next()
- Return the next item from the container. If there are no further items, raise
- the :exc:`StopIteration` exception. This method corresponds to the
- :attr:`tp_iternext` slot of the type structure for Python objects in the
- Python/C API.
- Python defines several iterator objects to support iteration over general and
- specific sequence types, dictionaries, and other more specialized forms. The
- specific types are not important beyond their implementation of the iterator
- protocol.
- The intention of the protocol is that once an iterator's :meth:`next` method
- raises :exc:`StopIteration`, it will continue to do so on subsequent calls.
- Implementations that do not obey this property are deemed broken. (This
- constraint was added in Python 2.3; in Python 2.2, various iterators are broken
- according to this rule.)
- Python's :term:`generator`\s provide a convenient way to implement the iterator
- protocol. If a container object's :meth:`__iter__` method is implemented as a
- generator, it will automatically return an iterator object (technically, a
- generator object) supplying the :meth:`__iter__` and :meth:`next` methods.
- .. _typesseq:
- Sequence Types --- :class:`str`, :class:`unicode`, :class:`list`, :class:`tuple`, :class:`buffer`, :class:`xrange`
- ==================================================================================================================
- There are six sequence types: strings, Unicode strings, lists, tuples, buffers,
- and xrange objects.
- For other containers see the built in :class:`dict` and :class:`set` classes,
- and the :mod:`collections` module.
- .. index::
- object: sequence
- object: string
- object: Unicode
- object: tuple
- object: list
- object: buffer
- object: xrange
- String literals are written in single or double quotes: ``'xyzzy'``,
- ``"frobozz"``. See :ref:`strings` for more about string literals.
- Unicode strings are much like strings, but are specified in the syntax
- using a preceding ``'u'`` character: ``u'abc'``, ``u"def"``. In addition
- to the functionality described here, there are also string-specific
- methods described in the :ref:`string-methods` section. Lists are
- constructed with square brackets, separating items with commas: ``[a, b, c]``.
- Tuples are constructed by the comma operator (not within square
- brackets), with or without enclosing parentheses, but an empty tuple
- must have the enclosing parentheses, such as ``a, b, c`` or ``()``. A
- single item tuple must have a trailing comma, such as ``(d,)``.
- Buffer objects are not directly supported by Python syntax, but can be created
- by calling the builtin function :func:`buffer`. They don't support
- concatenation or repetition.
- Objects of type xrange are similar to buffers in that there is no specific syntax to
- create them, but they are created using the :func:`xrange` function. They don't
- support slicing, concatenation or repetition, and using ``in``, ``not in``,
- :func:`min` or :func:`max` on them is inefficient.
- Most sequence types support the following operations. The ``in`` and ``not in``
- operations have the same priorities as the comparison operations. The ``+`` and
- ``*`` operations have the same priority as the corresponding numeric operations.
- [#]_ Additional methods are provided for :ref:`typesseq-mutable`.
- This table lists the sequence operations sorted in ascending priority
- (operations in the same box have the same priority). In the table, *s* and *t*
- are sequences of the same type; *n*, *i* and *j* are integers:
- +------------------+--------------------------------+----------+
- | Operation | Result | Notes |
- +==================+================================+==========+
- | ``x in s`` | ``True`` if an item of *s* is | \(1) |
- | | equal to *x*, else ``False`` | |
- +------------------+--------------------------------+----------+
- | ``x not in s`` | ``False`` if an item of *s* is | \(1) |
- | | equal to *x*, else ``True`` | |
- +------------------+--------------------------------+----------+
- | ``s + t`` | the concatenation of *s* and | \(6) |
- | | *t* | |
- +------------------+--------------------------------+----------+
- | ``s * n, n * s`` | *n* shallow copies of *s* | \(2) |
- | | concatenated | |
- +------------------+--------------------------------+----------+
- | ``s[i]`` | *i*'th item of *s*, origin 0 | \(3) |
- +------------------+--------------------------------+----------+
- | ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) |
- +------------------+--------------------------------+----------+
- | ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) |
- | | with step *k* | |
- +------------------+--------------------------------+----------+
- | ``len(s)`` | length of *s* | |
- +------------------+--------------------------------+----------+
- | ``min(s)`` | smallest item of *s* | |
- +------------------+--------------------------------+----------+
- | ``max(s)`` | largest item of *s* | |
- +------------------+--------------------------------+----------+
- Sequence types also support comparisons. In particular, tuples and lists
- are compared lexicographically by comparing corresponding
- elements. This means that to compare equal, every element must compare
- equal and the two sequences must be of the same type and have the same
- length. (For full details see :ref:`comparisons` in the language
- reference.)
- .. index::
- triple: operations on; sequence; types
- builtin: len
- builtin: min
- builtin: max
- pair: concatenation; operation
- pair: repetition; operation
- pair: subscript; operation
- pair: slice; operation
- pair: extended slice; operation
- operator: in
- operator: not in
- Notes:
- (1)
- When *s* is a string or Unicode string object the ``in`` and ``not in``
- operations act like a substring test. In Python versions before 2.3, *x* had to
- be a string of length 1. In Python 2.3 and beyond, *x* may be a string of any
- length.
- (2)
- Values of *n* less than ``0`` are treated as ``0`` (which yields an empty
- sequence of the same type as *s*). Note also that the copies are shallow;
- nested structures are not copied. This often haunts new Python programmers;
- consider:
- >>> lists = [[]] * 3
- >>> lists
- [[], [], []]
- >>> lists[0].append(3)
- >>> lists
- [[3], [3], [3]]
- What has happened is that ``[[]]`` is a one-element list containing an empty
- list, so all three elements of ``[[]] * 3`` are (pointers to) this single empty
- list. Modifying any of the elements of ``lists`` modifies this single list.
- You can create a list of different lists this way:
- >>> lists = [[] for i in range(3)]
- >>> lists[0].append(3)
- >>> lists[1].append(5)
- >>> lists[2].append(7)
- >>> lists
- [[3], [5], [7]]
- (3)
- If *i* or *j* is negative, the index is relative to the end of the string:
- ``len(s) + i`` or ``len(s) + j`` is substituted. But note that ``-0`` is still
- ``0``.
- (4)
- The slice of *s* from *i* to *j* is defined as the sequence of items with index
- *k* such that ``i <= k < j``. If *i* or *j* is greater than ``len(s)``, use
- ``len(s)``. If *i* is omitted or ``None``, use ``0``. If *j* is omitted or
- ``None``, use ``len(s)``. If *i* is greater than or equal to *j*, the slice is
- empty.
- (5)
- The slice of *s* from *i* to *j* with step *k* is defined as the sequence of
- items with index ``x = i + n*k`` such that ``0 <= n < (j-i)/k``. In other words,
- the indices are ``i``, ``i+k``, ``i+2*k``, ``i+3*k`` and so on, stopping when
- *j* is reached (but never including *j*). If *i* or *j* is greater than
- ``len(s)``, use ``len(s)``. If *i* or *j* are omitted or ``None``, they become
- "end" values (which end depends on the sign of *k*). Note, *k* cannot be zero.
- If *k* is ``None``, it is treated like ``1``.
- (6)
- If *s* and *t* are both strings, some Python implementations such as CPython can
- usually perform an in-place optimization for assignments of the form ``s=s+t``
- or ``s+=t``. When applicable, this optimization makes quadratic run-time much
- less likely. This optimization is both version and implementation dependent.
- For performance sensitive code, it is preferable to use the :meth:`str.join`
- method which assures consistent linear concatenation performance across versions
- and implementations.
- .. versionchanged:: 2.4
- Formerly, string concatenation never occurred in-place.
- .. _string-methods:
- String Methods
- --------------
- .. index:: pair: string; methods
- Below are listed the string methods which both 8-bit strings and Unicode objects
- support. Note that none of these methods take keyword arguments.
- In addition, Python's strings support the sequence type methods
- described in the :ref:`typesseq` section. To output formatted strings
- use template strings or the ``%`` operator described in the
- :ref:`string-formatting` section. Also, see the :mod:`re` module for
- string functions based on regular expressions.
- .. method:: str.capitalize()
- Return a copy of the string with only its first character capitalized.
- For 8-bit strings, this method is locale-dependent.
- .. method:: str.center(width[, fillchar])
- Return centered in a string of length *width*. Padding is done using the
- specified *fillchar* (default is a space).
- .. versionchanged:: 2.4
- Support for the *fillchar* argument.
- .. method:: str.count(sub[, start[, end]])
- Return the number of non-overlapping occurrences of substring *sub* in the
- range [*start*, *end*]. Optional arguments *start* and *end* are
- interpreted as in slice notation.
- .. method:: str.decode([encoding[, errors]])
- Decodes the string using the codec registered for *encoding*. *encoding*
- defaults to the default string encoding. *errors* may be given to set a
- different error handling scheme. The default is ``'strict'``, meaning that
- encoding errors raise :exc:`UnicodeError`. Other possible values are
- ``'ignore'``, ``'replace'`` and any other name registered via
- :func:`codecs.register_error`, see section :ref:`codec-base-classes`.
- .. versionadded:: 2.2
- .. versionchanged:: 2.3
- Support for other error handling schemes added.
- .. method:: str.encode([encoding[,errors]])
- Return an encoded version of the string. Default encoding is the current
- default string encoding. *errors* may be given to set a different error
- handling scheme. The default for *errors* is ``'strict'``, meaning that
- encoding errors raise a :exc:`UnicodeError`. Other possible values are
- ``'ignore'``, ``'replace'``, ``'xmlcharrefreplace'``, ``'backslashreplace'`` and
- any other name registered via :func:`codecs.register_error`, see section
- :ref:`codec-base-classes`. For a list of possible encodings, see section
- :ref:`standard-encodings`.
- .. versionadded:: 2.0
- .. versionchanged:: 2.3
- Support for ``'xmlcharrefreplace'`` and ``'backslashreplace'`` and other error
- handling schemes added.
- .. method:: str.endswith(suffix[, start[, end]])
- Return ``True`` if the string ends with the specified *suffix*, otherwise return
- ``False``. *suffix* can also be a tuple of suffixes to look for. With optional
- *start*, test beginning at that position. With optional *end*, stop comparing
- at that position.
- .. versionchanged:: 2.5
- Accept tuples as *suffix*.
- .. method:: str.expandtabs([tabsize])
- Return a copy of the string where all tab characters are replaced by one or
- more spaces, depending on the current column and the given tab size. The
- column number is reset to zero after each newline occurring in the string.
- If *tabsize* is not given, a tab size of ``8`` characters is assumed. This
- doesn't understand other non-printing characters or escape sequences.
- .. method:: str.find(sub[, start[, end]])
- Return the lowest index in the string where substring *sub* is found, such that
- *sub* is contained in the range [*start*, *end*]. Optional arguments *start*
- and *end* are interpreted as in slice notation. Return ``-1`` if *sub* is not
- found.
- .. method:: str.format(format_string, *args, **kwargs)
- Perform a string formatting operation. The *format_string* argument can
- contain literal text or replacement fields delimited by braces ``{}``. Each
- replacement field contains either the numeric index of a positional argument,
- or the name of a keyword argument. Returns a copy of *format_string* where
- each replacement field is replaced with the string value of the corresponding
- argument.
- >>> "The sum of 1 + 2 is {0}".format(1+2)
- 'The sum of 1 + 2 is 3'
- See :ref:`formatstrings` for a description of the various formatting options
- that can be specified in format strings.
- This method of string formatting is the new standard in Python 3.0, and
- should be preferred to the ``%`` formatting described in
- :ref:`string-formatting` in new code.
- .. versionadded:: 2.6
- .. method:: str.index(sub[, start[, end]])
- Like :meth:`find`, but raise :exc:`ValueError` when the substring is not found.
- .. method:: str.isalnum()
- Return true if all characters in the string are alphanumeric and there is at
- least one character, false otherwise.
- For 8-bit strings, this method is locale-dependent.
- .. method:: str.isalpha()
- Return true if all characters in the string are alphabetic and there is at least
- one character, false otherwise.
- For 8-bit strings, this method is locale-dependent.
- .. method:: str.isdigit()
- Return true if all characters in the string are digits and there is at least one
- character, false otherwise.
- For 8-bit strings, this method is locale-dependent.
- .. method:: str.islower()
- Return true if all cased characters in the string are lowercase and there is at
- least one cased character, false otherwise.
- For 8-bit strings, this method is locale-dependent.
- .. method:: str.isspace()
- Return true if there are only whitespace characters in the string and there is
- at least one character, false otherwise.
- For 8-bit strings, this method is locale-dependent.
- .. method:: str.istitle()
- Return true if the string is a titlecased string and there is at least one
- character, for example uppercase characters may only follow uncased characters
- and lowercase characters only cased ones. Return false otherwise.
- For 8-bit strings, this method is locale-dependent.
- .. method:: str.isupper()
- Return true if all cased characters in the string are uppercase and there is at
- least one cased character, false otherwise.
- For 8-bit strings, this method is locale-dependent.
- .. method:: str.join(seq)
- Return a string which is the concatenation of the strings in the sequence *seq*.
- The separator between elements is the string providing this method.
- .. method:: str.ljust(width[, fillchar])
- Return the string left justified in a string of length *width*. Padding is done
- using the specified *fillchar* (default is a space). The original string is
- returned if *width* is less than ``len(s)``.
- .. versionchanged:: 2.4
- Support for the *fillchar* argument.
- .. method:: str.lower()
- Return a copy of the string converted to lowercase.
- For 8-bit strings, this method is locale-dependent.
- .. method:: str.lstrip([chars])
- Return a copy of the string with leading characters removed. The *chars*
- argument is a string specifying the set of characters to be removed. If omitted
- or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
- argument is not a prefix; rather, all combinations of its values are stripped:
- >>> ' spacious '.lstrip()
- 'spacious '
- >>> 'www.example.com'.lstrip('cmowz.')
- 'example.com'
- .. versionchanged:: 2.2.2
- Support for the *chars* argument.
- .. method:: str.partition(sep)
- Split the string at the first occurrence of *sep*, and return a 3-tuple
- containing the part before the separator, the separator itself, and the part
- after the separator. If the separator is not found, return a 3-tuple containing
- the string itself, followed by two empty strings.
- .. versionadded:: 2.5
- .. method:: str.replace(old, new[, count])
- Return a copy of the string with all occurrences of substring *old* replaced by
- *new*. If the optional argument *count* is given, only the first *count*
- occurrences are replaced.
- .. method:: str.rfind(sub [,start [,end]])
- Return the highest index in the string where substring *sub* is found, such that
- *sub* is contained within s[start,end]. Optional arguments *start* and *end*
- are interpreted as in slice notation. Return ``-1`` on failure.
- .. method:: str.rindex(sub[, start[, end]])
- Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not
- found.
- .. method:: str.rjust(width[, fillchar])
- Return the string right justified in a string of length *width*. Padding is done
- using the specified *fillchar* (default is a space). The original string is
- returned if *width* is less than ``len(s)``.
- .. versionchanged:: 2.4
- Support for the *fillchar* argument.
- .. method:: str.rpartition(sep)
- Split the string at the last occurrence of *sep*, and return a 3-tuple
- containing the part before the separator, the separator itself, and the part
- after the separator. If the separator is not found, return a 3-tuple containing
- two empty strings, followed by the string itself.
- .. versionadded:: 2.5
- .. method:: str.rsplit([sep [,maxsplit]])
- Return a list of the words in the string, using *sep* as the delimiter string.
- If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost*
- ones. If *sep* is not specified or ``None``, any whitespace string is a
- separator. Except for splitting from the right, :meth:`rsplit` behaves like
- :meth:`split` which is described in detail below.
- .. versionadded:: 2.4
- .. method:: str.rstrip([chars])
- Return a copy of the string with trailing characters removed. The *chars*
- argument is a string specifying the set of characters to be removed. If omitted
- or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
- argument is not a suffix; rather, all combinations of its values are stripped:
- >>> ' spacious '.rstrip()
- ' spacious'
- >>> 'mississippi'.rstrip('ipz')
- 'mississ'
- .. versionchanged:: 2.2.2
- Support for the *chars* argument.
- .. method:: str.split([sep[, maxsplit]])
- Return a list of the words in the string, using *sep* as the delimiter
- string. If *maxsplit* is given, at most *maxsplit* splits are done (thus,
- the list will have at most ``maxsplit+1`` elements). If *maxsplit* is not
- specified, then there is no limit on the number of splits (all possible
- splits are made).
- If *sep* is given, consecutive delimiters are not grouped together and are
- deemed to delimit empty strings (for example, ``'1,,2'.split(',')`` returns
- ``['1', '', '2']``). The *sep* argument may consist of multiple characters
- (for example, ``'1<>2<>3'.split('<>')`` returns ``['1', '2', '3']``).
- Splitting an empty string with a specified separator returns ``['']``.
- If *sep* is not specified or is ``None``, a different splitting algorithm is
- applied: runs of consecutive whitespace are regarded as a single separator,
- and the result will contain no empty strings at the start or end if the
- string has leading or trailing whitespace. Consequently, splitting an empty
- string or a string consisting of just whitespace with a ``None`` separator
- returns ``[]``.
- For example, ``' 1 2 3 '.split()`` returns ``['1', '2', '3']``, and
- ``' 1 2 3 '.split(None, 1)`` returns ``['1', '2 3 ']``.
- .. method:: str.splitlines([keepends])
- Return a list of the lines in the string, breaking at line boundaries. Line
- breaks are not included in the resulting list unless *keepends* is given and
- true.
- .. method:: str.startswith(prefix[, start[, end]])
- Return ``True`` if string starts with the *prefix*, otherwise return ``False``.
- *prefix* can also be a tuple of prefixes to look for. With optional *start*,
- test string beginning at that position. With optional *end*, stop comparing
- string at that position.
- .. versionchanged:: 2.5
- Accept tuples as *prefix*.
- .. method:: str.strip([chars])
- Return a copy of the string with the leading and trailing characters removed.
- The *chars* argument is a string specifying the set of characters to be removed.
- If omitted or ``None``, the *chars* argument defaults to removing whitespace.
- The *chars* argument is not a prefix or suffix; rather, all combinations of its
- values are stripped:
- >>> ' spacious '.strip()
- 'spacious'
- >>> 'www.example.com'.strip('cmowz.')
- 'example'
- .. versionchanged:: 2.2.2
- Support for the *chars* argument.
- .. method:: str.swapcase()
- Return a copy of the string with uppercase characters converted to lowercase and
- vice versa.
- For 8-bit strings, this method is locale-dependent.
- .. method:: str.title()
- Return a titlecased version of the string where words start with an uppercase
- character and the remaining characters are lowercase.
- The algorithm uses a simple language-independent definition of a word as
- groups of consecutive letters. The definition works in many contexts but
- it means that apostrophes in contractions and possessives form word
- boundaries, which may not be the desired result::
- >>> "they're bill's friends from the UK".title()
- "They'Re Bill'S Friends From The Uk"
- A workaround for apostrophes can be constructed using regular expressions::
- >>> import re
- >>> def titlecase(s):
- return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
- lambda mo: mo.group(0)[0].upper() +
- mo.group(0)[1:].lower(),
- s)
- >>> titlecase("they're bill's friends.")
- "They're Bill's Friends."
- For 8-bit strings, this method is locale-dependent.
- .. method:: str.translate(table[, deletechars])
- Return a copy of the string where all characters occurring in the optional
- argument *deletechars* are removed, and the remaining characters have been
- mapped through the given translation table, which must be a string of length
- 256.
- You can use the :func:`maketrans` helper function in the :mod:`string` module to
- create a translation table. For string objects, set the *table* argument to
- ``None`` for translations that only delete characters:
- >>> 'read this short text'.translate(None, 'aeiou')
- 'rd ths shrt txt'
- .. versionadded:: 2.6
- Support for a ``None`` *table* argument.
- For Unicode objects, the :meth:`translate` method does not accept the optional
- *deletechars* argument. Instead, it returns a copy of the *s* where all
- characters have been mapped through the given translation table which must be a
- mapping of Unicode ordinals to Unicode ordinals, Unicode strings or ``None``.
- Unmapped characters are left untouched. Characters mapped to ``None`` are
- deleted. Note, a more flexible approach is to create a custom character mapping
- codec using the :mod:`codecs` module (see :mod:`encodings.cp1251` for an
- example).
- .. method:: str.upper()
- Return a copy of the string converted to uppercase.
- For 8-bit strings, this method is locale-dependent.
- .. method:: str.zfill(width)
- Return the numeric string left filled with zeros in a string of length
- *width*. A sign prefix is handled correctly. The original string is
- returned if *width* is less than ``len(s)``.
- .. versionadded:: 2.2.2
- The following methods are present only on unicode objects:
- .. method:: unicode.isnumeric()
- Return ``True`` if there are only numeric characters in S, ``False``
- otherwise. Numeric characters include digit characters, and all characters
- that have the Unicode numeric value property, e.g. U+2155,
- VULGAR FRACTION ONE FIFTH.
- .. method:: unicode.isdecimal()
- Return ``True`` if there are only decimal characters in S, ``False``
- otherwise. Decimal characters include digit characters, and all characters
- that that can be used to form decimal-radix numbers, e.g. U+0660,
- ARABIC-INDIC DIGIT ZERO.
- .. _string-formatting:
- String Formatting Operations
- ----------------------------
- .. index::
- single: formatting, string (%)
- single: interpolation, string (%)
- single: string; formatting
- single: string; interpolation
- single: printf-style formatting
- single: sprintf-style formatting
- single: % formatting
- single: % interpolation
- String and Unicode objects have one unique built-in operation: the ``%``
- operator (modulo). This is also known as the string *formatting* or
- *interpolation* operator. Given ``format % values`` (where *format* is a string
- or Unicode object), ``%`` conversion specifications in *format* are replaced
- with zero or more elements of *values*. The effect is similar to the using
- :cfunc:`sprintf` in the C language. If *format* is a Unicode object, or if any
- of the objects being converted using the ``%s`` conversion are Unicode objects,
- the result will also be a Unicode object.
- If *format* requires a single argument, *values* may be a single non-tuple
- object. [#]_ Otherwise, *values* must be a tuple with exactly the number of
- items specified by the format string, or a single mapping object (for example, a
- dictionary).
- A conversion specifier contains two or more characters and has the following
- components, which must occur in this order:
- #. The ``'%'`` character, which marks the start of the specifier.
- #. Mapping key (optional), consisting of a parenthesised sequence of characters
- (for example, ``(somename)``).
- #. Conversion flags (optional), which affect the result of some conversion
- types.
- #. Minimum field width (optional). If specified as an ``'*'`` (asterisk), the
- actual width is read from the next element of the tuple in *values*, and the
- object to convert comes after the minimum field width and optional precision.
- #. Precision (optional), given as a ``'.'`` (dot) followed by the precision. If
- specified as ``'*'`` (an asterisk), the actual width is read from the next
- element of the tuple in *values*, and the value to convert comes after the
- precision.
- #. Length modifier (optional).
- #. Conversion type.
- When the right argument is a dictionary (or other mapping type), then the
- formats in the string *must* include a parenthesised mapping key into that
- dictionary inserted immediately after the ``'%'`` character. The mapping key
- selects the value to be formatted from the mapping. For example:
- >>> print '%(language)s has %(#)03d quote types.' % \
- ... {'language': "Python", "#": 2}
- Python has 002 quote types.
- In this case no ``*`` specifiers may occur in a format (since they require a
- sequential parameter list).
- The conversion flag characters are:
- +---------+---------------------------------------------------------------------+
- | Flag | Meaning |
- +=========+=====================================================================+
- | ``'#'`` | The value conversion will use the "alternate form" (where defined |
- | | below). |
- +---------+---------------------------------------------------------------------+
- | ``'0'`` | The conversion will be zero padded for numeric values. |
- +---------+---------------------------------------------------------------------+
- | ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` |
- | | conversion if both are given). |
- +---------+---------------------------------------------------------------------+
- | ``' '`` | (a space) A blank should be left before a positiv…