1 .. XXX: reference/datamodel and this have quite a few overlaps!
10 The following sections describe the standard types that are built into the
15 Historically (until release 2.2), Python's built-in types have differed from
16 user-defined types because it was not possible to use the built-in types as the
17 basis for object-oriented inheritance. This limitation no longer
20 .. index:: pair: built-in; types
22 The principal built-in types are numerics, sequences, mappings, files, classes,
23 instances and exceptions.
25 .. index:: statement: print
27 Some operations are supported by several object types; in particular,
28 practically all objects can be compared, tested for truth value, and converted
29 to a string (with the :func:`repr` function or the slightly different
30 :func:`str` function). The latter function is implicitly used when an object is
31 written by the :func:`print` function.
43 pair: Boolean; operations
46 Any object can be tested for truth value, for use in an :keyword:`if` or
47 :keyword:`while` condition or as operand of the Boolean operations below. The
48 following values are considered false:
50 .. index:: single: None (Built-in object)
54 .. index:: single: False (Built-in object)
58 * zero of any numeric type, for example, ``0``, ``0L``, ``0.0``, ``0j``.
60 * any empty sequence, for example, ``''``, ``()``, ``[]``.
62 * any empty mapping, for example, ``{}``.
64 * instances of user-defined classes, if the class defines a :meth:`__nonzero__`
65 or :meth:`__len__` method, when that method returns the integer zero or
66 :class:`bool` value ``False``. [#]_
68 .. index:: single: true
70 All other values are considered true --- so objects of many types are always
79 Operations and built-in functions that have a Boolean result always return ``0``
80 or ``False`` for false and ``1`` or ``True`` for true, unless otherwise stated.
81 (Important exception: the Boolean operations ``or`` and ``and`` always return
82 one of their operands.)
87 Boolean Operations --- :keyword:`and`, :keyword:`or`, :keyword:`not`
88 ====================================================================
90 .. index:: pair: Boolean; operations
92 These are the Boolean operations, ordered by ascending priority:
94 +-------------+---------------------------------+-------+
95 | Operation | Result | Notes |
96 +=============+=================================+=======+
97 | ``x or y`` | if *x* is false, then *y*, else | \(1) |
99 +-------------+---------------------------------+-------+
100 | ``x and y`` | if *x* is false, then *x*, else | \(2) |
102 +-------------+---------------------------------+-------+
103 | ``not x`` | if *x* is false, then ``True``, | \(3) |
104 | | else ``False`` | |
105 +-------------+---------------------------------+-------+
115 This is a short-circuit operator, so it only evaluates the second
116 argument if the first one is :const:`False`.
119 This is a short-circuit operator, so it only evaluates the second
120 argument if the first one is :const:`True`.
123 ``not`` has a lower priority than non-Boolean operators, so ``not a == b`` is
124 interpreted as ``not (a == b)``, and ``a == not b`` is a syntax error.
132 .. index:: pair: chaining; comparisons
134 Comparison operations are supported by all objects. They all have the same
135 priority (which is higher than that of the Boolean operations). Comparisons can
136 be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and
137 y <= z``, except that *y* is evaluated only once (but in both cases *z* is not
138 evaluated at all when ``x < y`` is found to be false).
140 This table summarizes the comparison operations:
142 +------------+-------------------------+-------+
143 | Operation | Meaning | Notes |
144 +============+=========================+=======+
145 | ``<`` | strictly less than | |
146 +------------+-------------------------+-------+
147 | ``<=`` | less than or equal | |
148 +------------+-------------------------+-------+
149 | ``>`` | strictly greater than | |
150 +------------+-------------------------+-------+
151 | ``>=`` | greater than or equal | |
152 +------------+-------------------------+-------+
154 +------------+-------------------------+-------+
155 | ``!=`` | not equal | \(1) |
156 +------------+-------------------------+-------+
157 | ``is`` | object identity | |
158 +------------+-------------------------+-------+
159 | ``is not`` | negated object identity | |
160 +------------+-------------------------+-------+
163 pair: operator; comparison
176 ``!=`` can also be written ``<>``, but this is an obsolete usage
177 kept for backwards compatibility only. New code should always use
181 pair: object; numeric
182 pair: objects; comparing
184 Objects of different types, except different numeric types and different string
185 types, never compare equal; such objects are ordered consistently but
186 arbitrarily (so that sorting a heterogeneous array yields a consistent result).
187 Furthermore, some types (for example, file objects) support only a degenerate
188 notion of comparison where any two objects of that type are unequal. Again,
189 such objects are ordered arbitrarily but consistently. The ``<``, ``<=``, ``>``
190 and ``>=`` operators will raise a :exc:`TypeError` exception when any operand is
193 .. index:: single: __cmp__() (instance method)
195 Instances of a class normally compare as non-equal unless the class defines the
196 :meth:`__cmp__` method. Refer to :ref:`customization`) for information on the
197 use of this method to effect object comparisons.
199 **Implementation note:** Objects of different types except numbers are ordered
200 by their type names; objects of the same types that don't support proper
201 comparison are ordered by their address.
207 Two more operations with the same syntactic priority, ``in`` and ``not in``, are
208 supported only by sequence types (below).
213 Numeric Types --- :class:`int`, :class:`float`, :class:`long`, :class:`complex`
214 ===============================================================================
221 object: floating point
222 object: complex number
225 There are four distinct numeric types: :dfn:`plain integers`, :dfn:`long
226 integers`, :dfn:`floating point numbers`, and :dfn:`complex numbers`. In
227 addition, Booleans are a subtype of plain integers. Plain integers (also just
228 called :dfn:`integers`) are implemented using :ctype:`long` in C, which gives
229 them at least 32 bits of precision (``sys.maxint`` is always set to the maximum
230 plain integer value for the current platform, the minimum value is
231 ``-sys.maxint - 1``). Long integers have unlimited precision. Floating point
232 numbers are implemented using :ctype:`double` in C. All bets on their precision
233 are off unless you happen to know the machine you are working with.
235 Complex numbers have a real and imaginary part, which are each implemented using
236 :ctype:`double` in C. To extract these parts from a complex number *z*, use
237 ``z.real`` and ``z.imag``.
240 pair: numeric; literals
241 pair: integer; literals
242 triple: long; integer; literals
243 pair: floating point; literals
244 pair: complex number; literals
245 pair: hexadecimal; literals
246 pair: octal; literals
248 Numbers are created by numeric literals or as the result of built-in functions
249 and operators. Unadorned integer literals (including binary, hex, and octal
250 numbers) yield plain integers unless the value they denote is too large to be
251 represented as a plain integer, in which case they yield a long integer.
252 Integer literals with an ``'L'`` or ``'l'`` suffix yield long integers (``'L'``
253 is preferred because ``1l`` looks too much like eleven!). Numeric literals
254 containing a decimal point or an exponent sign yield floating point numbers.
255 Appending ``'j'`` or ``'J'`` to a numeric literal yields a complex number with a
256 zero real part. A complex numeric literal is the sum of a real and an imaginary
266 Python fully supports mixed arithmetic: when a binary arithmetic operator has
267 operands of different numeric types, the operand with the "narrower" type is
268 widened to that of the other, where plain integer is narrower than long integer
269 is narrower than floating point is narrower than complex. Comparisons between
270 numbers of mixed type use the same rule. [#]_ The constructors :func:`int`,
271 :func:`long`, :func:`float`, and :func:`complex` can be used to produce numbers
274 All builtin numeric types support the following operations. See
275 :ref:`power` and later sections for the operators' priorities.
277 +--------------------+---------------------------------+--------+
278 | Operation | Result | Notes |
279 +====================+=================================+========+
280 | ``x + y`` | sum of *x* and *y* | |
281 +--------------------+---------------------------------+--------+
282 | ``x - y`` | difference of *x* and *y* | |
283 +--------------------+---------------------------------+--------+
284 | ``x * y`` | product of *x* and *y* | |
285 +--------------------+---------------------------------+--------+
286 | ``x / y`` | quotient of *x* and *y* | \(1) |
287 +--------------------+---------------------------------+--------+
288 | ``x // y`` | (floored) quotient of *x* and | (4)(5) |
290 +--------------------+---------------------------------+--------+
291 | ``x % y`` | remainder of ``x / y`` | \(4) |
292 +--------------------+---------------------------------+--------+
293 | ``-x`` | *x* negated | |
294 +--------------------+---------------------------------+--------+
295 | ``+x`` | *x* unchanged | |
296 +--------------------+---------------------------------+--------+
297 | ``abs(x)`` | absolute value or magnitude of | \(3) |
299 +--------------------+---------------------------------+--------+
300 | ``int(x)`` | *x* converted to integer | \(2) |
301 +--------------------+---------------------------------+--------+
302 | ``long(x)`` | *x* converted to long integer | \(2) |
303 +--------------------+---------------------------------+--------+
304 | ``float(x)`` | *x* converted to floating point | \(6) |
305 +--------------------+---------------------------------+--------+
306 | ``complex(re,im)`` | a complex number with real part | |
307 | | *re*, imaginary part *im*. | |
308 | | *im* defaults to zero. | |
309 +--------------------+---------------------------------+--------+
310 | ``c.conjugate()`` | conjugate of the complex number | |
311 | | *c*. (Identity on real numbers) | |
312 +--------------------+---------------------------------+--------+
313 | ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | (3)(4) |
314 +--------------------+---------------------------------+--------+
315 | ``pow(x, y)`` | *x* to the power *y* | (3)(7) |
316 +--------------------+---------------------------------+--------+
317 | ``x ** y`` | *x* to the power *y* | \(7) |
318 +--------------------+---------------------------------+--------+
321 triple: operations on; numeric; types
322 single: conjugate() (complex number method)
328 pair: integer; division
329 triple: long; integer; division
331 For (plain or long) integer division, the result is an integer. The result is
332 always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and
333 (-1)/(-2) is 0. Note that the result is a long integer if either operand is a
334 long integer, regardless of the numeric value.
339 single: floor() (in module math)
340 single: ceil() (in module math)
341 pair: numeric; conversions
344 Conversion from floating point to (long or plain) integer may round or
345 truncate as in C; see functions :func:`math.floor` and :func:`math.ceil` for
346 well-defined conversions.
349 Instead, convert floats to long explicitly with :func:`trunc`.
352 See :ref:`built-in-funcs` for a full description.
355 Complex floor division operator, modulo operator, and :func:`divmod`.
358 Instead convert to float using :func:`abs` if appropriate.
361 Also referred to as integer division. The resultant value is a whole integer,
362 though the result's type is not necessarily int.
365 float also accepts the strings "nan" and "inf" with an optional prefix "+"
366 or "-" for Not a Number (NaN) and positive or negative infinity.
368 .. versionadded:: 2.6
371 Python defines ``pow(0, 0)`` and ``0 ** 0`` to be ``1``, as is common for
372 programming languages.
374 All :class:`numbers.Real` types (:class:`int`, :class:`long`, and
375 :class:`float`) also include the following operations:
377 +--------------------+------------------------------------+--------+
378 | Operation | Result | Notes |
379 +====================+====================================+========+
380 | ``trunc(x)`` | *x* truncated to Integral | |
381 +--------------------+------------------------------------+--------+
382 | ``round(x[, n])`` | *x* rounded to n digits, | |
383 | | rounding half to even. If n is | |
384 | | omitted, it defaults to 0. | |
385 +--------------------+------------------------------------+--------+
386 | ``math.floor(x)`` | the greatest integral float <= *x* | |
387 +--------------------+------------------------------------+--------+
388 | ``math.ceil(x)`` | the least integral float >= *x* | |
389 +--------------------+------------------------------------+--------+
391 .. XXXJH exceptions: overflow (when? what operations?) zerodivision
396 Bit-string Operations on Integer Types
397 --------------------------------------
399 .. _bit-string-operations:
401 Plain and long integer types support additional operations that make sense only
402 for bit-strings. Negative numbers are treated as their 2's complement value
403 (for long integers, this assumes a sufficiently large number of bits that no
404 overflow occurs during the operation).
406 The priorities of the binary bitwise operations are all lower than the numeric
407 operations and higher than the comparisons; the unary operation ``~`` has the
408 same priority as the other unary numeric operations (``+`` and ``-``).
410 This table lists the bit-string operations sorted in ascending priority:
412 +------------+--------------------------------+----------+
413 | Operation | Result | Notes |
414 +============+================================+==========+
415 | ``x | y`` | bitwise :dfn:`or` of *x* and | |
417 +------------+--------------------------------+----------+
418 | ``x ^ y`` | bitwise :dfn:`exclusive or` of | |
420 +------------+--------------------------------+----------+
421 | ``x & y`` | bitwise :dfn:`and` of *x* and | |
423 +------------+--------------------------------+----------+
424 | ``x << n`` | *x* shifted left by *n* bits | (1)(2) |
425 +------------+--------------------------------+----------+
426 | ``x >> n`` | *x* shifted right by *n* bits | (1)(3) |
427 +------------+--------------------------------+----------+
428 | ``~x`` | the bits of *x* inverted | |
429 +------------+--------------------------------+----------+
432 triple: operations on; integer; types
433 pair: bit-string; operations
434 pair: shifting; operations
435 pair: masking; operations
440 Negative shift counts are illegal and cause a :exc:`ValueError` to be raised.
443 A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)``. A
444 long integer is returned if the result exceeds the range of plain integers.
447 A right shift by *n* bits is equivalent to division by ``pow(2, n)``.
450 Additional Methods on Integer Types
451 -----------------------------------
453 .. method:: int.bit_length()
454 .. method:: long.bit_length()
456 For any integer ``x``, ``x.bit_length()`` returns the number of
457 bits necessary to represent ``x`` in binary, excluding the sign
458 and any leading zeros::
469 More precisely, if ``x`` is nonzero then ``x.bit_length()`` is the
470 unique positive integer ``k`` such that ``2**(k-1) <= abs(x) <
471 2**k``. Equivalently, ``x.bit_length()`` is equal to ``1 +
472 floor(log(x, 2))`` [#]_ . If ``x`` is zero then ``x.bit_length()``
477 def bit_length(self):
478 'Number of bits necessary to represent self in binary.'
479 return len(bin(self).lstrip('-0b'))
482 .. versionadded:: 2.7
485 Additional Methods on Float
486 ---------------------------
488 The float type has some additional methods.
490 .. method:: float.as_integer_ratio()
492 Return a pair of integers whose ratio is exactly equal to the
493 original float and with a positive denominator. Raises
494 :exc:`OverflowError` on infinities and a :exc:`ValueError` on
497 .. versionadded:: 2.6
499 Two methods support conversion to
500 and from hexadecimal strings. Since Python's floats are stored
501 internally as binary numbers, converting a float to or from a
502 *decimal* string usually involves a small rounding error. In
503 contrast, hexadecimal strings allow exact representation and
504 specification of floating-point numbers. This can be useful when
505 debugging, and in numerical work.
508 .. method:: float.hex()
510 Return a representation of a floating-point number as a hexadecimal
511 string. For finite floating-point numbers, this representation
512 will always include a leading ``0x`` and a trailing ``p`` and
515 .. versionadded:: 2.6
518 .. method:: float.fromhex(s)
520 Class method to return the float represented by a hexadecimal
521 string *s*. The string *s* may have leading and trailing
524 .. versionadded:: 2.6
527 Note that :meth:`float.hex` is an instance method, while
528 :meth:`float.fromhex` is a class method.
530 A hexadecimal string takes the form::
532 [sign] ['0x'] integer ['.' fraction] ['p' exponent]
534 where the optional ``sign`` may by either ``+`` or ``-``, ``integer``
535 and ``fraction`` are strings of hexadecimal digits, and ``exponent``
536 is a decimal integer with an optional leading sign. Case is not
537 significant, and there must be at least one hexadecimal digit in
538 either the integer or the fraction. This syntax is similar to the
539 syntax specified in section 6.4.4.2 of the C99 standard, and also to
540 the syntax used in Java 1.5 onwards. In particular, the output of
541 :meth:`float.hex` is usable as a hexadecimal floating-point literal in
542 C or Java code, and hexadecimal strings produced by C's ``%a`` format
543 character or Java's ``Double.toHexString`` are accepted by
544 :meth:`float.fromhex`.
547 Note that the exponent is written in decimal rather than hexadecimal,
548 and that it gives the power of 2 by which to multiply the coefficient.
549 For example, the hexadecimal string ``0x3.a7p10`` represents the
550 floating-point number ``(3 + 10./16 + 7./16**2) * 2.0**10``, or
553 >>> float.fromhex('0x3.a7p10')
557 Applying the reverse conversion to ``3740.0`` gives a different
558 hexadecimal string representing the same number::
560 >>> float.hex(3740.0)
561 '0x1.d380000000000p+11'
569 .. versionadded:: 2.2
572 single: iterator protocol
573 single: protocol; iterator
574 single: sequence; iteration
575 single: container; iteration over
577 Python supports a concept of iteration over containers. This is implemented
578 using two distinct methods; these are used to allow user-defined classes to
579 support iteration. Sequences, described below in more detail, always support
580 the iteration methods.
582 One method needs to be defined for container objects to provide iteration
585 .. XXX duplicated in reference/datamodel!
587 .. method:: container.__iter__()
589 Return an iterator object. The object is required to support the iterator
590 protocol described below. If a container supports different types of
591 iteration, additional methods can be provided to specifically request
592 iterators for those iteration types. (An example of an object supporting
593 multiple forms of iteration would be a tree structure which supports both
594 breadth-first and depth-first traversal.) This method corresponds to the
595 :attr:`tp_iter` slot of the type structure for Python objects in the Python/C
598 The iterator objects themselves are required to support the following two
599 methods, which together form the :dfn:`iterator protocol`:
602 .. method:: iterator.__iter__()
604 Return the iterator object itself. This is required to allow both containers
605 and iterators to be used with the :keyword:`for` and :keyword:`in` statements.
606 This method corresponds to the :attr:`tp_iter` slot of the type structure for
607 Python objects in the Python/C API.
610 .. method:: iterator.next()
612 Return the next item from the container. If there are no further items, raise
613 the :exc:`StopIteration` exception. This method corresponds to the
614 :attr:`tp_iternext` slot of the type structure for Python objects in the
617 Python defines several iterator objects to support iteration over general and
618 specific sequence types, dictionaries, and other more specialized forms. The
619 specific types are not important beyond their implementation of the iterator
622 The intention of the protocol is that once an iterator's :meth:`next` method
623 raises :exc:`StopIteration`, it will continue to do so on subsequent calls.
624 Implementations that do not obey this property are deemed broken. (This
625 constraint was added in Python 2.3; in Python 2.2, various iterators are broken
626 according to this rule.)
628 Python's :term:`generator`\s provide a convenient way to implement the iterator
629 protocol. If a container object's :meth:`__iter__` method is implemented as a
630 generator, it will automatically return an iterator object (technically, a
631 generator object) supplying the :meth:`__iter__` and :meth:`next` methods.
636 Sequence Types --- :class:`str`, :class:`unicode`, :class:`list`, :class:`tuple`, :class:`buffer`, :class:`xrange`
637 ==================================================================================================================
639 There are six sequence types: strings, Unicode strings, lists, tuples, buffers,
641 (For other containers see the built in :class:`dict`, :class:`list`,
642 :class:`set`, and :class:`tuple` classes, and the :mod:`collections`
655 String literals are written in single or double quotes: ``'xyzzy'``,
656 ``"frobozz"``. See :ref:`strings` for more about string literals.
657 Unicode strings are much like strings, but are specified in the syntax
658 using a preceding ``'u'`` character: ``u'abc'``, ``u"def"``. In addition
659 to the functionality described here, there are also string-specific
660 methods described in the :ref:`string-methods` section. Lists are
661 constructed with square brackets, separating items with commas: ``[a, b, c]``.
662 Tuples are constructed by the comma operator (not within square
663 brackets), with or without enclosing parentheses, but an empty tuple
664 must have the enclosing parentheses, such as ``a, b, c`` or ``()``. A
665 single item tuple must have a trailing comma, such as ``(d,)``.
667 Buffer objects are not directly supported by Python syntax, but can be created
668 by calling the builtin function :func:`buffer`. They don't support
669 concatenation or repetition.
671 Objects of type xrange are similar to buffers in that there is no specific syntax to
672 create them, but they are created using the :func:`xrange` function. They don't
673 support slicing, concatenation or repetition, and using ``in``, ``not in``,
674 :func:`min` or :func:`max` on them is inefficient.
676 Most sequence types support the following operations. The ``in`` and ``not in``
677 operations have the same priorities as the comparison operations. The ``+`` and
678 ``*`` operations have the same priority as the corresponding numeric operations.
679 [#]_ Additional methods are provided for :ref:`typesseq-mutable`.
681 This table lists the sequence operations sorted in ascending priority
682 (operations in the same box have the same priority). In the table, *s* and *t*
683 are sequences of the same type; *n*, *i* and *j* are integers:
685 +------------------+--------------------------------+----------+
686 | Operation | Result | Notes |
687 +==================+================================+==========+
688 | ``x in s`` | ``True`` if an item of *s* is | \(1) |
689 | | equal to *x*, else ``False`` | |
690 +------------------+--------------------------------+----------+
691 | ``x not in s`` | ``False`` if an item of *s* is | \(1) |
692 | | equal to *x*, else ``True`` | |
693 +------------------+--------------------------------+----------+
694 | ``s + t`` | the concatenation of *s* and | \(6) |
696 +------------------+--------------------------------+----------+
697 | ``s * n, n * s`` | *n* shallow copies of *s* | \(2) |
699 +------------------+--------------------------------+----------+
700 | ``s[i]`` | *i*'th item of *s*, origin 0 | \(3) |
701 +------------------+--------------------------------+----------+
702 | ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) |
703 +------------------+--------------------------------+----------+
704 | ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) |
705 | | with step *k* | |
706 +------------------+--------------------------------+----------+
707 | ``len(s)`` | length of *s* | |
708 +------------------+--------------------------------+----------+
709 | ``min(s)`` | smallest item of *s* | |
710 +------------------+--------------------------------+----------+
711 | ``max(s)`` | largest item of *s* | |
712 +------------------+--------------------------------+----------+
714 Sequence types also support comparisons. In particular, tuples and lists
715 are compared lexicographically by comparing corresponding
716 elements. This means that to compare equal, every element must compare
717 equal and the two sequences must be of the same type and have the same
718 length. (For full details see :ref:`comparisons` in the language
722 triple: operations on; sequence; types
726 pair: concatenation; operation
727 pair: repetition; operation
728 pair: subscript; operation
729 pair: slice; operation
730 pair: extended slice; operation
737 When *s* is a string or Unicode string object the ``in`` and ``not in``
738 operations act like a substring test. In Python versions before 2.3, *x* had to
739 be a string of length 1. In Python 2.3 and beyond, *x* may be a string of any
743 Values of *n* less than ``0`` are treated as ``0`` (which yields an empty
744 sequence of the same type as *s*). Note also that the copies are shallow;
745 nested structures are not copied. This often haunts new Python programmers;
751 >>> lists[0].append(3)
755 What has happened is that ``[[]]`` is a one-element list containing an empty
756 list, so all three elements of ``[[]] * 3`` are (pointers to) this single empty
757 list. Modifying any of the elements of ``lists`` modifies this single list.
758 You can create a list of different lists this way:
760 >>> lists = [[] for i in range(3)]
761 >>> lists[0].append(3)
762 >>> lists[1].append(5)
763 >>> lists[2].append(7)
768 If *i* or *j* is negative, the index is relative to the end of the string:
769 ``len(s) + i`` or ``len(s) + j`` is substituted. But note that ``-0`` is still
773 The slice of *s* from *i* to *j* is defined as the sequence of items with index
774 *k* such that ``i <= k < j``. If *i* or *j* is greater than ``len(s)``, use
775 ``len(s)``. If *i* is omitted or ``None``, use ``0``. If *j* is omitted or
776 ``None``, use ``len(s)``. If *i* is greater than or equal to *j*, the slice is
780 The slice of *s* from *i* to *j* with step *k* is defined as the sequence of
781 items with index ``x = i + n*k`` such that ``0 <= n < (j-i)/k``. In other words,
782 the indices are ``i``, ``i+k``, ``i+2*k``, ``i+3*k`` and so on, stopping when
783 *j* is reached (but never including *j*). If *i* or *j* is greater than
784 ``len(s)``, use ``len(s)``. If *i* or *j* are omitted or ``None``, they become
785 "end" values (which end depends on the sign of *k*). Note, *k* cannot be zero.
786 If *k* is ``None``, it is treated like ``1``.
789 If *s* and *t* are both strings, some Python implementations such as CPython can
790 usually perform an in-place optimization for assignments of the form ``s=s+t``
791 or ``s+=t``. When applicable, this optimization makes quadratic run-time much
792 less likely. This optimization is both version and implementation dependent.
793 For performance sensitive code, it is preferable to use the :meth:`str.join`
794 method which assures consistent linear concatenation performance across versions
797 .. versionchanged:: 2.4
798 Formerly, string concatenation never occurred in-place.
806 .. index:: pair: string; methods
808 Below are listed the string methods which both 8-bit strings and Unicode objects
809 support. Note that none of these methods take keyword arguments.
811 In addition, Python's strings support the sequence type methods
812 described in the :ref:`typesseq` section. To output formatted strings
813 use template strings or the ``%`` operator described in the
814 :ref:`string-formatting` section. Also, see the :mod:`re` module for
815 string functions based on regular expressions.
817 .. method:: str.capitalize()
819 Return a copy of the string with only its first character capitalized.
821 For 8-bit strings, this method is locale-dependent.
824 .. method:: str.center(width[, fillchar])
826 Return centered in a string of length *width*. Padding is done using the
827 specified *fillchar* (default is a space).
829 .. versionchanged:: 2.4
830 Support for the *fillchar* argument.
833 .. method:: str.count(sub[, start[, end]])
835 Return the number of occurrences of substring *sub* in the range [*start*,
836 *end*]. Optional arguments *start* and *end* are interpreted as in slice
840 .. method:: str.decode([encoding[, errors]])
842 Decodes the string using the codec registered for *encoding*. *encoding*
843 defaults to the default string encoding. *errors* may be given to set a
844 different error handling scheme. The default is ``'strict'``, meaning that
845 encoding errors raise :exc:`UnicodeError`. Other possible values are
846 ``'ignore'``, ``'replace'`` and any other name registered via
847 :func:`codecs.register_error`, see section :ref:`codec-base-classes`.
849 .. versionadded:: 2.2
851 .. versionchanged:: 2.3
852 Support for other error handling schemes added.
855 .. method:: str.encode([encoding[,errors]])
857 Return an encoded version of the string. Default encoding is the current
858 default string encoding. *errors* may be given to set a different error
859 handling scheme. The default for *errors* is ``'strict'``, meaning that
860 encoding errors raise a :exc:`UnicodeError`. Other possible values are
861 ``'ignore'``, ``'replace'``, ``'xmlcharrefreplace'``, ``'backslashreplace'`` and
862 any other name registered via :func:`codecs.register_error`, see section
863 :ref:`codec-base-classes`. For a list of possible encodings, see section
864 :ref:`standard-encodings`.
866 .. versionadded:: 2.0
868 .. versionchanged:: 2.3
869 Support for ``'xmlcharrefreplace'`` and ``'backslashreplace'`` and other error
870 handling schemes added.
873 .. method:: str.endswith(suffix[, start[, end]])
875 Return ``True`` if the string ends with the specified *suffix*, otherwise return
876 ``False``. *suffix* can also be a tuple of suffixes to look for. With optional
877 *start*, test beginning at that position. With optional *end*, stop comparing
880 .. versionchanged:: 2.5
881 Accept tuples as *suffix*.
884 .. method:: str.expandtabs([tabsize])
886 Return a copy of the string where all tab characters are replaced by one or
887 more spaces, depending on the current column and the given tab size. The
888 column number is reset to zero after each newline occurring in the string.
889 If *tabsize* is not given, a tab size of ``8`` characters is assumed. This
890 doesn't understand other non-printing characters or escape sequences.
893 .. method:: str.find(sub[, start[, end]])
895 Return the lowest index in the string where substring *sub* is found, such that
896 *sub* is contained in the range [*start*, *end*]. Optional arguments *start*
897 and *end* are interpreted as in slice notation. Return ``-1`` if *sub* is not
901 .. method:: str.format(format_string, *args, **kwargs)
903 Perform a string formatting operation. The *format_string* argument can
904 contain literal text or replacement fields delimited by braces ``{}``. Each
905 replacement field contains either the numeric index of a positional argument,
906 or the name of a keyword argument. Returns a copy of *format_string* where
907 each replacement field is replaced with the string value of the corresponding
910 >>> "The sum of 1 + 2 is {0}".format(1+2)
911 'The sum of 1 + 2 is 3'
913 See :ref:`formatstrings` for a description of the various formatting options
914 that can be specified in format strings.
916 This method of string formatting is the new standard in Python 3.0, and
917 should be preferred to the ``%`` formatting described in
918 :ref:`string-formatting` in new code.
920 .. versionadded:: 2.6
923 .. method:: str.index(sub[, start[, end]])
925 Like :meth:`find`, but raise :exc:`ValueError` when the substring is not found.
928 .. method:: str.isalnum()
930 Return true if all characters in the string are alphanumeric and there is at
931 least one character, false otherwise.
933 For 8-bit strings, this method is locale-dependent.
936 .. method:: str.isalpha()
938 Return true if all characters in the string are alphabetic and there is at least
939 one character, false otherwise.
941 For 8-bit strings, this method is locale-dependent.
944 .. method:: str.isdigit()
946 Return true if all characters in the string are digits and there is at least one
947 character, false otherwise.
949 For 8-bit strings, this method is locale-dependent.
952 .. method:: str.islower()
954 Return true if all cased characters in the string are lowercase and there is at
955 least one cased character, false otherwise.
957 For 8-bit strings, this method is locale-dependent.
960 .. method:: str.isspace()
962 Return true if there are only whitespace characters in the string and there is
963 at least one character, false otherwise.
965 For 8-bit strings, this method is locale-dependent.
968 .. method:: str.istitle()
970 Return true if the string is a titlecased string and there is at least one
971 character, for example uppercase characters may only follow uncased characters
972 and lowercase characters only cased ones. Return false otherwise.
974 For 8-bit strings, this method is locale-dependent.
977 .. method:: str.isupper()
979 Return true if all cased characters in the string are uppercase and there is at
980 least one cased character, false otherwise.
982 For 8-bit strings, this method is locale-dependent.
985 .. method:: str.join(seq)
987 Return a string which is the concatenation of the strings in the sequence *seq*.
988 The separator between elements is the string providing this method.
991 .. method:: str.ljust(width[, fillchar])
993 Return the string left justified in a string of length *width*. Padding is done
994 using the specified *fillchar* (default is a space). The original string is
995 returned if *width* is less than ``len(s)``.
997 .. versionchanged:: 2.4
998 Support for the *fillchar* argument.
1001 .. method:: str.lower()
1003 Return a copy of the string converted to lowercase.
1005 For 8-bit strings, this method is locale-dependent.
1008 .. method:: str.lstrip([chars])
1010 Return a copy of the string with leading characters removed. The *chars*
1011 argument is a string specifying the set of characters to be removed. If omitted
1012 or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
1013 argument is not a prefix; rather, all combinations of its values are stripped:
1015 >>> ' spacious '.lstrip()
1017 >>> 'www.example.com'.lstrip('cmowz.')
1020 .. versionchanged:: 2.2.2
1021 Support for the *chars* argument.
1024 .. method:: str.partition(sep)
1026 Split the string at the first occurrence of *sep*, and return a 3-tuple
1027 containing the part before the separator, the separator itself, and the part
1028 after the separator. If the separator is not found, return a 3-tuple containing
1029 the string itself, followed by two empty strings.
1031 .. versionadded:: 2.5
1034 .. method:: str.replace(old, new[, count])
1036 Return a copy of the string with all occurrences of substring *old* replaced by
1037 *new*. If the optional argument *count* is given, only the first *count*
1038 occurrences are replaced.
1041 .. method:: str.rfind(sub [,start [,end]])
1043 Return the highest index in the string where substring *sub* is found, such that
1044 *sub* is contained within s[start,end]. Optional arguments *start* and *end*
1045 are interpreted as in slice notation. Return ``-1`` on failure.
1048 .. method:: str.rindex(sub[, start[, end]])
1050 Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not
1054 .. method:: str.rjust(width[, fillchar])
1056 Return the string right justified in a string of length *width*. Padding is done
1057 using the specified *fillchar* (default is a space). The original string is
1058 returned if *width* is less than ``len(s)``.
1060 .. versionchanged:: 2.4
1061 Support for the *fillchar* argument.
1064 .. method:: str.rpartition(sep)
1066 Split the string at the last occurrence of *sep*, and return a 3-tuple
1067 containing the part before the separator, the separator itself, and the part
1068 after the separator. If the separator is not found, return a 3-tuple containing
1069 two empty strings, followed by the string itself.
1071 .. versionadded:: 2.5
1074 .. method:: str.rsplit([sep [,maxsplit]])
1076 Return a list of the words in the string, using *sep* as the delimiter string.
1077 If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost*
1078 ones. If *sep* is not specified or ``None``, any whitespace string is a
1079 separator. Except for splitting from the right, :meth:`rsplit` behaves like
1080 :meth:`split` which is described in detail below.
1082 .. versionadded:: 2.4
1085 .. method:: str.rstrip([chars])
1087 Return a copy of the string with trailing characters removed. The *chars*
1088 argument is a string specifying the set of characters to be removed. If omitted
1089 or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
1090 argument is not a suffix; rather, all combinations of its values are stripped:
1092 >>> ' spacious '.rstrip()
1094 >>> 'mississippi'.rstrip('ipz')
1097 .. versionchanged:: 2.2.2
1098 Support for the *chars* argument.
1101 .. method:: str.split([sep[, maxsplit]])
1103 Return a list of the words in the string, using *sep* as the delimiter
1104 string. If *maxsplit* is given, at most *maxsplit* splits are done (thus,
1105 the list will have at most ``maxsplit+1`` elements). If *maxsplit* is not
1106 specified, then there is no limit on the number of splits (all possible
1109 If *sep* is given, consecutive delimiters are not grouped together and are
1110 deemed to delimit empty strings (for example, ``'1,,2'.split(',')`` returns
1111 ``['1', '', '2']``). The *sep* argument may consist of multiple characters
1112 (for example, ``'1<>2<>3'.split('<>')`` returns ``['1', '2', '3']``).
1113 Splitting an empty string with a specified separator returns ``['']``.
1115 If *sep* is not specified or is ``None``, a different splitting algorithm is
1116 applied: runs of consecutive whitespace are regarded as a single separator,
1117 and the result will contain no empty strings at the start or end if the
1118 string has leading or trailing whitespace. Consequently, splitting an empty
1119 string or a string consisting of just whitespace with a ``None`` separator
1122 For example, ``' 1 2 3 '.split()`` returns ``['1', '2', '3']``, and
1123 ``' 1 2 3 '.split(None, 1)`` returns ``['1', '2 3 ']``.
1126 .. method:: str.splitlines([keepends])
1128 Return a list of the lines in the string, breaking at line boundaries. Line
1129 breaks are not included in the resulting list unless *keepends* is given and
1133 .. method:: str.startswith(prefix[, start[, end]])
1135 Return ``True`` if string starts with the *prefix*, otherwise return ``False``.
1136 *prefix* can also be a tuple of prefixes to look for. With optional *start*,
1137 test string beginning at that position. With optional *end*, stop comparing
1138 string at that position.
1140 .. versionchanged:: 2.5
1141 Accept tuples as *prefix*.
1144 .. method:: str.strip([chars])
1146 Return a copy of the string with the leading and trailing characters removed.
1147 The *chars* argument is a string specifying the set of characters to be removed.
1148 If omitted or ``None``, the *chars* argument defaults to removing whitespace.
1149 The *chars* argument is not a prefix or suffix; rather, all combinations of its
1150 values are stripped:
1152 >>> ' spacious '.strip()
1154 >>> 'www.example.com'.strip('cmowz.')
1157 .. versionchanged:: 2.2.2
1158 Support for the *chars* argument.
1161 .. method:: str.swapcase()
1163 Return a copy of the string with uppercase characters converted to lowercase and
1166 For 8-bit strings, this method is locale-dependent.
1169 .. method:: str.title()
1171 Return a titlecased version of the string: words start with uppercase
1172 characters, all remaining cased characters are lowercase.
1174 For 8-bit strings, this method is locale-dependent.
1177 .. method:: str.translate(table[, deletechars])
1179 Return a copy of the string where all characters occurring in the optional
1180 argument *deletechars* are removed, and the remaining characters have been
1181 mapped through the given translation table, which must be a string of length
1184 You can use the :func:`maketrans` helper function in the :mod:`string` module to
1185 create a translation table. For string objects, set the *table* argument to
1186 ``None`` for translations that only delete characters:
1188 >>> 'read this short text'.translate(None, 'aeiou')
1191 .. versionadded:: 2.6
1192 Support for a ``None`` *table* argument.
1194 For Unicode objects, the :meth:`translate` method does not accept the optional
1195 *deletechars* argument. Instead, it returns a copy of the *s* where all
1196 characters have been mapped through the given translation table which must be a
1197 mapping of Unicode ordinals to Unicode ordinals, Unicode strings or ``None``.
1198 Unmapped characters are left untouched. Characters mapped to ``None`` are
1199 deleted. Note, a more flexible approach is to create a custom character mapping
1200 codec using the :mod:`codecs` module (see :mod:`encodings.cp1251` for an
1204 .. method:: str.upper()
1206 Return a copy of the string converted to uppercase.
1208 For 8-bit strings, this method is locale-dependent.
1211 .. method:: str.zfill(width)
1213 Return the numeric string left filled with zeros in a string of length
1214 *width*. A sign prefix is handled correctly. The original string is
1215 returned if *width* is less than ``len(s)``.
1218 .. versionadded:: 2.2.2
1220 The following methods are present only on unicode objects:
1222 .. method:: unicode.isnumeric()
1224 Return ``True`` if there are only numeric characters in S, ``False``
1225 otherwise. Numeric characters include digit characters, and all characters
1226 that have the Unicode numeric value property, e.g. U+2155,
1227 VULGAR FRACTION ONE FIFTH.
1229 .. method:: unicode.isdecimal()
1231 Return ``True`` if there are only decimal characters in S, ``False``
1232 otherwise. Decimal characters include digit characters, and all characters
1233 that that can be used to form decimal-radix numbers, e.g. U+0660,
1234 ARABIC-INDIC DIGIT ZERO.
1237 .. _string-formatting:
1239 String Formatting Operations
1240 ----------------------------
1243 single: formatting, string (%)
1244 single: interpolation, string (%)
1245 single: string; formatting
1246 single: string; interpolation
1247 single: printf-style formatting
1248 single: sprintf-style formatting
1249 single: % formatting
1250 single: % interpolation
1252 String and Unicode objects have one unique built-in operation: the ``%``
1253 operator (modulo). This is also known as the string *formatting* or
1254 *interpolation* operator. Given ``format % values`` (where *format* is a string
1255 or Unicode object), ``%`` conversion specifications in *format* are replaced
1256 with zero or more elements of *values*. The effect is similar to the using
1257 :cfunc:`sprintf` in the C language. If *format* is a Unicode object, or if any
1258 of the objects being converted using the ``%s`` conversion are Unicode objects,
1259 the result will also be a Unicode object.
1261 If *format* requires a single argument, *values* may be a single non-tuple
1262 object. [#]_ Otherwise, *values* must be a tuple with exactly the number of
1263 items specified by the format string, or a single mapping object (for example, a
1266 A conversion specifier contains two or more characters and has the following
1267 components, which must occur in this order:
1269 #. The ``'%'`` character, which marks the start of the specifier.
1271 #. Mapping key (optional), consisting of a parenthesised sequence of characters
1272 (for example, ``(somename)``).
1274 #. Conversion flags (optional), which affect the result of some conversion
1277 #. Minimum field width (optional). If specified as an ``'*'`` (asterisk), the
1278 actual width is read from the next element of the tuple in *values*, and the
1279 object to convert comes after the minimum field width and optional precision.
1281 #. Precision (optional), given as a ``'.'`` (dot) followed by the precision. If
1282 specified as ``'*'`` (an asterisk), the actual width is read from the next
1283 element of the tuple in *values*, and the value to convert comes after the
1286 #. Length modifier (optional).
1290 When the right argument is a dictionary (or other mapping type), then the
1291 formats in the string *must* include a parenthesised mapping key into that
1292 dictionary inserted immediately after the ``'%'`` character. The mapping key
1293 selects the value to be formatted from the mapping. For example:
1295 >>> print '%(language)s has %(#)03d quote types.' % \
1296 ... {'language': "Python", "#": 2}
1297 Python has 002 quote types.
1299 In this case no ``*`` specifiers may occur in a format (since they require a
1300 sequential parameter list).
1302 The conversion flag characters are:
1304 +---------+---------------------------------------------------------------------+
1306 +=========+=====================================================================+
1307 | ``'#'`` | The value conversion will use the "alternate form" (where defined |
1309 +---------+---------------------------------------------------------------------+
1310 | ``'0'`` | The conversion will be zero padded for numeric values. |
1311 +---------+---------------------------------------------------------------------+
1312 | ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` |
1313 | | conversion if both are given). |
1314 +---------+---------------------------------------------------------------------+
1315 | ``' '`` | (a space) A blank should be left before a positive number (or empty |
1316 | | string) produced by a signed conversion. |
1317 +---------+---------------------------------------------------------------------+
1318 | ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion |
1319 | | (overrides a "space" flag). |
1320 +---------+---------------------------------------------------------------------+
1322 A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it
1323 is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``.
1325 The conversion types are:
1327 +------------+-----------------------------------------------------+-------+
1328 | Conversion | Meaning | Notes |
1329 +============+=====================================================+=======+
1330 | ``'d'`` | Signed integer decimal. | |
1331 +------------+-----------------------------------------------------+-------+
1332 | ``'i'`` | Signed integer decimal. | |
1333 +------------+-----------------------------------------------------+-------+
1334 | ``'o'`` | Signed octal value. | \(1) |
1335 +------------+-----------------------------------------------------+-------+
1336 | ``'u'`` | Obselete type -- it is identical to ``'d'``. | \(7) |
1337 +------------+-----------------------------------------------------+-------+
1338 | ``'x'`` | Signed hexadecimal (lowercase). | \(2) |
1339 +------------+-----------------------------------------------------+-------+
1340 | ``'X'`` | Signed hexadecimal (uppercase). | \(2) |
1341 +------------+-----------------------------------------------------+-------+
1342 | ``'e'`` | Floating point exponential format (lowercase). | \(3) |
1343 +------------+-----------------------------------------------------+-------+
1344 | ``'E'`` | Floating point exponential format (uppercase). | \(3) |
1345 +------------+-----------------------------------------------------+-------+
1346 | ``'f'`` | Floating point decimal format. | \(3) |
1347 +------------+-----------------------------------------------------+-------+
1348 | ``'F'`` | Floating point decimal format. | \(3) |
1349 +------------+-----------------------------------------------------+-------+
1350 | ``'g'`` | Floating point format. Uses lowercase exponential | \(4) |
1351 | | format if exponent is less than -4 or not less than | |
1352 | | precision, decimal format otherwise. | |
1353 +------------+-----------------------------------------------------+-------+
1354 | ``'G'`` | Floating point format. Uses uppercase exponential | \(4) |
1355 | | format if exponent is less than -4 or not less than | |
1356 | | precision, decimal format otherwise. | |
1357 +------------+-----------------------------------------------------+-------+
1358 | ``'c'`` | Single character (accepts integer or single | |
1359 | | character string). | |
1360 +------------+-----------------------------------------------------+-------+
1361 | ``'r'`` | String (converts any python object using | \(5) |
1362 | | :func:`repr`). | |
1363 +------------+-----------------------------------------------------+-------+
1364 | ``'s'`` | String (converts any python object using | \(6) |
1365 | | :func:`str`). | |
1366 +------------+-----------------------------------------------------+-------+
1367 | ``'%'`` | No argument is converted, results in a ``'%'`` | |
1368 | | character in the result. | |
1369 +------------+-----------------------------------------------------+-------+
1374 The alternate form causes a leading zero (``'0'``) to be inserted between
1375 left-hand padding and the formatting of the number if the leading character
1376 of the result is not already a zero.
1379 The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether
1380 the ``'x'`` or ``'X'`` format was used) to be inserted between left-hand padding
1381 and the formatting of the number if the leading character of the result is not
1385 The alternate form causes the result to always contain a decimal point, even if
1386 no digits follow it.
1388 The precision determines the number of digits after the decimal point and
1392 The alternate form causes the result to always contain a decimal point, and
1393 trailing zeroes are not removed as they would otherwise be.
1395 The precision determines the number of significant digits before and after the
1396 decimal point and defaults to 6.
1399 The ``%r`` conversion was added in Python 2.0.
1401 The precision determines the maximal number of characters used.
1404 If the object or format provided is a :class:`unicode` string, the resulting
1405 string will also be :class:`unicode`.
1407 The precision determines the maximal number of characters used.
1412 Since Python strings have an explicit length, ``%s`` conversions do not assume
1413 that ``'\0'`` is the end of the string.
1417 For safety reasons, floating point precisions are clipped to 50; ``%f``
1418 conversions for numbers whose absolute value is over 1e25 are replaced by ``%g``
1419 conversions. [#]_ All other errors raise exceptions.
1425 Additional string operations are defined in standard modules :mod:`string` and
1429 .. _typesseq-xrange:
1434 .. index:: object: xrange
1436 The :class:`xrange` type is an immutable sequence which is commonly used for
1437 looping. The advantage of the :class:`xrange` type is that an :class:`xrange`
1438 object will always take the same amount of memory, no matter the size of the
1439 range it represents. There are no consistent performance advantages.
1441 XRange objects have very little behavior: they only support indexing, iteration,
1442 and the :func:`len` function.
1445 .. _typesseq-mutable:
1447 Mutable Sequence Types
1448 ----------------------
1451 triple: mutable; sequence; types
1454 List objects support additional operations that allow in-place modification of
1455 the object. Other mutable sequence types (when added to the language) should
1456 also support these operations. Strings and tuples are immutable sequence types:
1457 such objects cannot be modified once created. The following operations are
1458 defined on mutable sequence types (where *x* is an arbitrary object):
1460 +------------------------------+--------------------------------+---------------------+
1461 | Operation | Result | Notes |
1462 +==============================+================================+=====================+
1463 | ``s[i] = x`` | item *i* of *s* is replaced by | |
1465 +------------------------------+--------------------------------+---------------------+
1466 | ``s[i:j] = t`` | slice of *s* from *i* to *j* | |
1467 | | is replaced by the contents of | |
1468 | | the iterable *t* | |
1469 +------------------------------+--------------------------------+---------------------+
1470 | ``del s[i:j]`` | same as ``s[i:j] = []`` | |
1471 +------------------------------+--------------------------------+---------------------+
1472 | ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` | \(1) |
1473 | | are replaced by those of *t* | |
1474 +------------------------------+--------------------------------+---------------------+
1475 | ``del s[i:j:k]`` | removes the elements of | |
1476 | | ``s[i:j:k]`` from the list | |
1477 +------------------------------+--------------------------------+---------------------+
1478 | ``s.append(x)`` | same as ``s[len(s):len(s)] = | \(2) |
1480 +------------------------------+--------------------------------+---------------------+
1481 | ``s.extend(x)`` | same as ``s[len(s):len(s)] = | \(3) |
1483 +------------------------------+--------------------------------+---------------------+
1484 | ``s.count(x)`` | return number of *i*'s for | |
1485 | | which ``s[i] == x`` | |
1486 +------------------------------+--------------------------------+---------------------+
1487 | ``s.index(x[, i[, j]])`` | return smallest *k* such that | \(4) |
1488 | | ``s[k] == x`` and ``i <= k < | |
1490 +------------------------------+--------------------------------+---------------------+
1491 | ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | \(5) |
1492 +------------------------------+--------------------------------+---------------------+
1493 | ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | \(6) |
1495 +------------------------------+--------------------------------+---------------------+
1496 | ``s.remove(x)`` | same as ``del s[s.index(x)]`` | \(4) |
1497 +------------------------------+--------------------------------+---------------------+
1498 | ``s.reverse()`` | reverses the items of *s* in | \(7) |
1500 +------------------------------+--------------------------------+---------------------+
1501 | ``s.sort([cmp[, key[, | sort the items of *s* in place | (7)(8)(9)(10) |
1502 | reverse]]])`` | | |
1503 +------------------------------+--------------------------------+---------------------+
1506 triple: operations on; sequence; types
1507 triple: operations on; list; type
1508 pair: subscript; assignment
1509 pair: slice; assignment
1510 pair: extended slice; assignment
1512 single: append() (list method)
1513 single: extend() (list method)
1514 single: count() (list method)
1515 single: index() (list method)
1516 single: insert() (list method)
1517 single: pop() (list method)
1518 single: remove() (list method)
1519 single: reverse() (list method)
1520 single: sort() (list method)
1525 *t* must have the same length as the slice it is replacing.
1528 The C implementation of Python has historically accepted multiple parameters and
1529 implicitly joined them into a tuple; this no longer works in Python 2.0. Use of
1530 this misfeature has been deprecated since Python 1.4.
1533 *x* can be any iterable object.
1536 Raises :exc:`ValueError` when *x* is not found in *s*. When a negative index is
1537 passed as the second or third parameter to the :meth:`index` method, the list
1538 length is added, as for slice indices. If it is still negative, it is truncated
1539 to zero, as for slice indices.
1541 .. versionchanged:: 2.3
1542 Previously, :meth:`index` didn't have arguments for specifying start and stop
1546 When a negative index is passed as the first parameter to the :meth:`insert`
1547 method, the list length is added, as for slice indices. If it is still
1548 negative, it is truncated to zero, as for slice indices.
1550 .. versionchanged:: 2.3
1551 Previously, all negative indices were truncated to zero.
1554 The :meth:`pop` method is only supported by the list and array types. The
1555 optional argument *i* defaults to ``-1``, so that by default the last item is
1556 removed and returned.
1559 The :meth:`sort` and :meth:`reverse` methods modify the list in place for
1560 economy of space when sorting or reversing a large list. To remind you that
1561 they operate by side effect, they don't return the sorted or reversed list.
1564 The :meth:`sort` method takes optional arguments for controlling the
1567 *cmp* specifies a custom comparison function of two arguments (list items) which
1568 should return a negative, zero or positive number depending on whether the first
1569 argument is considered smaller than, equal to, or larger than the second
1570 argument: ``cmp=lambda x,y: cmp(x.lower(), y.lower())``. The default value
1573 *key* specifies a function of one argument that is used to extract a comparison
1574 key from each list element: ``key=str.lower``. The default value is ``None``.
1576 *reverse* is a boolean value. If set to ``True``, then the list elements are
1577 sorted as if each comparison were reversed.
1579 In general, the *key* and *reverse* conversion processes are much faster than
1580 specifying an equivalent *cmp* function. This is because *cmp* is called
1581 multiple times for each list element while *key* and *reverse* touch each
1584 .. versionchanged:: 2.3
1585 Support for ``None`` as an equivalent to omitting *cmp* was added.
1587 .. versionchanged:: 2.4
1588 Support for *key* and *reverse* was added.
1591 Starting with Python 2.3, the :meth:`sort` method is guaranteed to be stable. A
1592 sort is stable if it guarantees not to change the relative order of elements
1593 that compare equal --- this is helpful for sorting in multiple passes (for
1594 example, sort by department, then by salary grade).
1597 While a list is being sorted, the effect of attempting to mutate, or even
1598 inspect, the list is undefined. The C implementation of Python 2.3 and newer
1599 makes the list appear empty for the duration, and raises :exc:`ValueError` if it
1600 can detect that the list has been mutated during a sort.
1605 Set Types --- :class:`set`, :class:`frozenset`
1606 ==============================================
1608 .. index:: object: set
1610 A :dfn:`set` object is an unordered collection of distinct :term:`hashable` objects.
1611 Common uses include membership testing, removing duplicates from a sequence, and
1612 computing mathematical operations such as intersection, union, difference, and
1613 symmetric difference.
1614 (For other containers see the built in :class:`dict`, :class:`list`,
1615 and :class:`tuple` classes, and the :mod:`collections` module.)
1618 .. versionadded:: 2.4
1620 Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in
1621 set``. Being an unordered collection, sets do not record element position or
1622 order of insertion. Accordingly, sets do not support indexing, slicing, or
1623 other sequence-like behavior.
1625 There are currently two builtin set types, :class:`set` and :class:`frozenset`.
1626 The :class:`set` type is mutable --- the contents can be changed using methods
1627 like :meth:`add` and :meth:`remove`. Since it is mutable, it has no hash value
1628 and cannot be used as either a dictionary key or as an element of another set.
1629 The :class:`frozenset` type is immutable and :term:`hashable` --- its contents cannot be
1630 altered after it is created; it can therefore be used as a dictionary key or as
1631 an element of another set.
1633 The constructors for both classes work the same:
1635 .. class:: set([iterable])
1636 frozenset([iterable])
1638 Return a new set or frozenset object whose elements are taken from
1639 *iterable*. The elements of a set must be hashable. To represent sets of
1640 sets, the inner sets must be :class:`frozenset` objects. If *iterable* is
1641 not specified, a new empty set is returned.
1643 Instances of :class:`set` and :class:`frozenset` provide the following
1646 .. describe:: len(s)
1648 Return the cardinality of set *s*.
1650 .. describe:: x in s
1652 Test *x* for membership in *s*.
1654 .. describe:: x not in s
1656 Test *x* for non-membership in *s*.
1658 .. method:: isdisjoint(other)
1660 Return True if the set has no elements in common with *other*. Sets are
1661 disjoint if and only if their intersection is the empty set.
1663 .. versionadded:: 2.6
1665 .. method:: issubset(other)
1668 Test whether every element in the set is in *other*.
1670 .. method:: set < other
1672 Test whether the set is a true subset of *other*, that is,
1673 ``set <= other and set != other``.
1675 .. method:: issuperset(other)
1678 Test whether every element in *other* is in the set.
1680 .. method:: set > other
1682 Test whether the set is a true superset of *other*, that is, ``set >=
1683 other and set != other``.
1685 .. method:: union(other, ...)
1688 Return a new set with elements from both sets.
1690 .. versionchanged:: 2.6
1691 Accepts multiple input iterables.
1693 .. method:: intersection(other, ...)
1696 Return a new set with elements common to both sets.
1698 .. versionchanged:: 2.6
1699 Accepts multiple input iterables.
1701 .. method:: difference(other, ...)
1704 Return a new set with elements in the set that are not in the others.
1706 .. versionchanged:: 2.6
1707 Accepts multiple input iterables.
1709 .. method:: symmetric_difference(other)
1712 Return a new set with elements in either the set or *other* but not both.
1716 Return a new set with a shallow copy of *s*.
1719 Note, the non-operator versions of :meth:`union`, :meth:`intersection`,
1720 :meth:`difference`, and :meth:`symmetric_difference`, :meth:`issubset`, and
1721 :meth:`issuperset` methods will accept any iterable as an argument. In
1722 contrast, their operator based counterparts require their arguments to be
1723 sets. This precludes error-prone constructions like ``set('abc') & 'cbs'``
1724 in favor of the more readable ``set('abc').intersection('cbs')``.
1726 Both :class:`set` and :class:`frozenset` support set to set comparisons. Two
1727 sets are equal if and only if every element of each set is contained in the
1728 other (each is a subset of the other). A set is less than another set if and
1729 only if the first set is a proper subset of the second set (is a subset, but
1730 is not equal). A set is greater than another set if and only if the first set
1731 is a proper superset of the second set (is a superset, but is not equal).
1733 Instances of :class:`set` are compared to instances of :class:`frozenset`
1734 based on their members. For example, ``set('abc') == frozenset('abc')``
1735 returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``.
1737 The subset and equality comparisons do not generalize to a complete ordering
1738 function. For example, any two disjoint sets are not equal and are not
1739 subsets of each other, so *all* of the following return ``False``: ``a<b``,
1740 ``a==b``, or ``a>b``. Accordingly, sets do not implement the :meth:`__cmp__`
1743 Since sets only define partial ordering (subset relationships), the output of
1744 the :meth:`list.sort` method is undefined for lists of sets.
1746 Set elements, like dictionary keys, must be :term:`hashable`.
1748 Binary operations that mix :class:`set` instances with :class:`frozenset`
1749 return the type of the first operand. For example: ``frozenset('ab') |
1750 set('bc')`` returns an instance of :class:`frozenset`.
1752 The following table lists operations available for :class:`set` that do not
1753 apply to immutable instances of :class:`frozenset`:
1755 .. method:: update(other, ...)
1758 Update the set, adding elements from *other*.
1760 .. versionchanged:: 2.6
1761 Accepts multiple input iterables.
1763 .. method:: intersection_update(other, ...)
1766 Update the set, keeping only elements found in it and *other*.
1768 .. versionchanged:: 2.6
1769 Accepts multiple input iterables.
1771 .. method:: difference_update(other, ...)
1774 Update the set, removing elements found in others.
1776 .. versionchanged:: 2.6
1777 Accepts multiple input iterables.
1779 .. method:: symmetric_difference_update(other)
1782 Update the set, keeping only elements found in either set, but not in both.
1784 .. method:: add(elem)
1786 Add element *elem* to the set.
1788 .. method:: remove(elem)
1790 Remove element *elem* from the set. Raises :exc:`KeyError` if *elem* is
1791 not contained in the set.
1793 .. method:: discard(elem)
1795 Remove element *elem* from the set if it is present.
1799 Remove and return an arbitrary element from the set. Raises
1800 :exc:`KeyError` if the set is empty.
1804 Remove all elements from the set.
1807 Note, the non-operator versions of the :meth:`update`,
1808 :meth:`intersection_update`, :meth:`difference_update`, and
1809 :meth:`symmetric_difference_update` methods will accept any iterable as an
1812 Note, the *elem* argument to the :meth:`__contains__`, :meth:`remove`, and
1813 :meth:`discard` methods may be a set. To support searching for an equivalent
1814 frozenset, the *elem* set is temporarily mutated during the search and then
1815 restored. During the search, the *elem* set should not be read or mutated
1816 since it does not have a meaningful value.
1821 :ref:`comparison-to-builtin-set`
1822 Differences between the :mod:`sets` module and the built-in set types.
1827 Mapping Types --- :class:`dict`
1828 ===============================
1833 triple: operations on; mapping; types
1834 triple: operations on; dictionary; type
1838 A :dfn:`mapping` object maps :term:`hashable` values to arbitrary objects.
1839 Mappings are mutable objects. There is currently only one standard mapping
1840 type, the :dfn:`dictionary`. (For other containers see the built in
1841 :class:`list`, :class:`set`, and :class:`tuple` classes, and the
1842 :mod:`collections` module.)
1844 A dictionary's keys are *almost* arbitrary values. Values that are not
1845 :term:`hashable`, that is, values containing lists, dictionaries or other
1846 mutable types (that are compared by value rather than by object identity) may
1847 not be used as keys. Numeric types used for keys obey the normal rules for
1848 numeric comparison: if two numbers compare equal (such as ``1`` and ``1.0``)
1849 then they can be used interchangeably to index the same dictionary entry. (Note
1850 however, that since computers store floating-point numbers as approximations it
1851 is usually unwise to use them as dictionary keys.)
1853 Dictionaries can be created by placing a comma-separated list of ``key: value``
1854 pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098:
1855 'jack', 4127: 'sjoerd'}``, or by the :class:`dict` constructor.
1857 .. class:: dict([arg])
1859 Return a new dictionary initialized from an optional positional argument or from
1860 a set of keyword arguments. If no arguments are given, return a new empty
1861 dictionary. If the positional argument *arg* is a mapping object, return a
1862 dictionary mapping the same keys to the same values as does the mapping object.
1863 Otherwise the positional argument must be a sequence, a container that supports
1864 iteration, or an iterator object. The elements of the argument must each also
1865 be of one of those kinds, and each must in turn contain exactly two objects.
1866 The first is used as a key in the new dictionary, and the second as the key's
1867 value. If a given key is seen more than once, the last value associated with it
1868 is retained in the new dictionary.
1870 If keyword arguments are given, the keywords themselves with their associated
1871 values are added as items to the dictionary. If a key is specified both in the
1872 positional argument and as a keyword argument, the value associated with the
1873 keyword is retained in the dictionary. For example, these all return a
1874 dictionary equal to ``{"one": 2, "two": 3}``:
1876 * ``dict(one=2, two=3)``
1878 * ``dict({'one': 2, 'two': 3})``
1880 * ``dict(zip(('one', 'two'), (2, 3)))``
1882 * ``dict([['two', 3], ['one', 2]])``
1884 The first example only works for keys that are valid Python
1885 identifiers; the others work with any valid keys.
1887 .. versionadded:: 2.2
1889 .. versionchanged:: 2.3
1890 Support for building a dictionary from keyword arguments added.
1893 These are the operations that dictionaries support (and therefore, custom
1894 mapping types should support too):
1896 .. describe:: len(d)
1898 Return the number of items in the dictionary *d*.
1900 .. describe:: d[key]
1902 Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key*
1905 .. versionadded:: 2.5
1906 If a subclass of dict defines a method :meth:`__missing__`, if the key
1907 *key* is not present, the ``d[key]`` operation calls that method with
1908 the key *key* as argument. The ``d[key]`` operation then returns or
1909 raises whatever is returned or raised by the ``__missing__(key)`` call
1910 if the key is not present. No other operations or methods invoke
1911 :meth:`__missing__`. If :meth:`__missing__` is not defined,
1912 :exc:`KeyError` is raised. :meth:`__missing__` must be a method; it
1913 cannot be an instance variable. For an example, see
1914 :class:`collections.defaultdict`.
1916 .. describe:: d[key] = value
1918 Set ``d[key]`` to *value*.
1920 .. describe:: del d[key]
1922 Remove ``d[key]`` from *d*. Raises a :exc:`KeyError` if *key* is not in the
1925 .. describe:: key in d
1927 Return ``True`` if *d* has a key *key*, else ``False``.
1929 .. versionadded:: 2.2
1931 .. describe:: key not in d
1933 Equivalent to ``not key in d``.
1935 .. versionadded:: 2.2
1939 Remove all items from the dictionary.
1943 Return a shallow copy of the dictionary.
1945 .. method:: fromkeys(seq[, value])
1947 Create a new dictionary with keys from *seq* and values set to *value*.
1949 :func:`fromkeys` is a class method that returns a new dictionary. *value*
1950 defaults to ``None``.
1952 .. versionadded:: 2.3
1954 .. method:: get(key[, default])
1956 Return the value for *key* if *key* is in the dictionary, else *default*.
1957 If *default* is not given, it defaults to ``None``, so that this method
1958 never raises a :exc:`KeyError`.
1960 .. method:: has_key(key)
1962 Test for the presence of *key* in the dictionary. :meth:`has_key` is
1963 deprecated in favor of ``key in d``.
1967 Return a copy of the dictionary's list of ``(key, value)`` pairs.
1971 Keys and values are listed in an arbitrary order which is non-random,
1972 varies across Python implementations, and depends on the dictionary's
1973 history of insertions and deletions. If :meth:`items`, :meth:`keys`,
1974 :meth:`values`, :meth:`iteritems`, :meth:`iterkeys`, and
1975 :meth:`itervalues` are called with no intervening modifications to the
1976 dictionary, the lists will directly correspond. This allows the
1977 creation of ``(value, key)`` pairs using :func:`zip`: ``pairs =
1978 zip(d.values(), d.keys())``. The same relationship holds for the
1979 :meth:`iterkeys` and :meth:`itervalues` methods: ``pairs =
1980 zip(d.itervalues(), d.iterkeys())`` provides the same value for
1981 ``pairs``. Another way to create the same list is ``pairs = [(v, k) for
1982 (k, v) in d.iteritems()]``.
1984 .. method:: iteritems()
1986 Return an iterator over the dictionary's ``(key, value)`` pairs. See the
1987 note for :meth:`dict.items`.
1989 .. versionadded:: 2.2
1991 .. method:: iterkeys()
1993 Return an iterator over the dictionary's keys. See the note for
1996 .. versionadded:: 2.2
1998 .. method:: itervalues()
2000 Return an iterator over the dictionary's values. See the note for
2003 .. versionadded:: 2.2
2007 Return a copy of the dictionary's list of keys. See the note for
2010 .. method:: pop(key[, default])
2012 If *key* is in the dictionary, remove it and return its value, else return
2013 *default*. If *default* is not given and *key* is not in the dictionary,
2014 a :exc:`KeyError` is raised.
2016 .. versionadded:: 2.3
2018 .. method:: popitem()
2020 Remove and return an arbitrary ``(key, value)`` pair from the dictionary.
2022 :func:`popitem` is useful to destructively iterate over a dictionary, as
2023 often used in set algorithms. If the dictionary is empty, calling
2024 :func:`popitem` raises a :exc:`KeyError`.
2026 .. method:: setdefault(key[, default])
2028 If *key* is in the dictionary, return its value. If not, insert *key*
2029 with a value of *default* and return *default*. *default* defaults to
2032 .. method:: update([other])
2034 Update the dictionary with the key/value pairs from *other*, overwriting
2035 existing keys. Return ``None``.
2037 :func:`update` accepts either another dictionary object or an iterable of
2038 key/value pairs (as a tuple or other iterable of length two). If keyword
2039 arguments are specified, the dictionary is then is updated with those
2040 key/value pairs: ``d.update(red=1, blue=2)``.
2042 .. versionchanged:: 2.4
2043 Allowed the argument to be an iterable of key/value pairs and allowed
2046 .. method:: values()
2048 Return a copy of the dictionary's list of values. See the note for
2052 .. _bltin-file-objects:
2063 File objects are implemented using C's ``stdio`` package and can be
2064 created with the built-in :func:`open` function. File
2065 objects are also returned by some other built-in functions and methods,
2066 such as :func:`os.popen` and :func:`os.fdopen` and the :meth:`makefile`
2067 method of socket objects. Temporary files can be created using the
2068 :mod:`tempfile` module, and high-level file operations such as copying,
2069 moving, and deleting files and directories can be achieved with the
2070 :mod:`shutil` module.
2072 When a file operation fails for an I/O-related reason, the exception
2073 :exc:`IOError` is raised. This includes situations where the operation is not
2074 defined for some reason, like :meth:`seek` on a tty device or writing a file
2077 Files have the following methods:
2080 .. method:: file.close()
2082 Close the file. A closed file cannot be read or written any more. Any operation
2083 which requires that the file be open will raise a :exc:`ValueError` after the
2084 file has been closed. Calling :meth:`close` more than once is allowed.
2086 As of Python 2.5, you can avoid having to call this method explicitly if you use
2087 the :keyword:`with` statement. For example, the following code will
2088 automatically close *f* when the :keyword:`with` block is exited::
2090 from __future__ import with_statement # This isn't required in Python 2.6
2092 with open("hello.txt") as f:
2096 In older versions of Python, you would have needed to do this to get the same
2099 f = open("hello.txt")
2108 Not all "file-like" types in Python support use as a context manager for the
2109 :keyword:`with` statement. If your code is intended to work with any file-like
2110 object, you can use the function :func:`contextlib.closing` instead of using
2111 the object directly.
2114 .. method:: file.flush()
2116 Flush the internal buffer, like ``stdio``'s :cfunc:`fflush`. This may be a
2117 no-op on some file-like objects.
2120 .. method:: file.fileno()
2123 pair: file; descriptor
2126 Return the integer "file descriptor" that is used by the underlying
2127 implementation to request I/O operations from the operating system. This can be
2128 useful for other, lower level interfaces that use file descriptors, such as the
2129 :mod:`fcntl` module or :func:`os.read` and friends.
2133 File-like objects which do not have a real file descriptor should *not* provide
2137 .. method:: file.isatty()
2139 Return ``True`` if the file is connected to a tty(-like) device, else ``False``.
2143 If a file-like object is not associated with a real file, this method should
2144 *not* be implemented.
2147 .. method:: file.next()
2149 A file object is its own iterator, for example ``iter(f)`` returns *f* (unless
2150 *f* is closed). When a file is used as an iterator, typically in a
2151 :keyword:`for` loop (for example, ``for line in f: print line``), the
2152 :meth:`next` method is called repeatedly. This method returns the next input
2153 line, or raises :exc:`StopIteration` when EOF is hit when the file is open for
2154 reading (behavior is undefined when the file is open for writing). In order to
2155 make a :keyword:`for` loop the most efficient way of looping over the lines of a
2156 file (a very common operation), the :meth:`next` method uses a hidden read-ahead
2157 buffer. As a consequence of using a read-ahead buffer, combining :meth:`next`
2158 with other file methods (like :meth:`readline`) does not work right. However,
2159 using :meth:`seek` to reposition the file to an absolute position will flush the
2162 .. versionadded:: 2.3
2165 .. method:: file.read([size])
2167 Read at most *size* bytes from the file (less if the read hits EOF before
2168 obtaining *size* bytes). If the *size* argument is negative or omitted, read
2169 all data until EOF is reached. The bytes are returned as a string object. An
2170 empty string is returned when EOF is encountered immediately. (For certain
2171 files, like ttys, it makes sense to continue reading after an EOF is hit.) Note
2172 that this method may call the underlying C function :cfunc:`fread` more than
2173 once in an effort to acquire as close to *size* bytes as possible. Also note
2174 that when in non-blocking mode, less data than was requested may be
2175 returned, even if no *size* parameter was given.
2178 This function is simply a wrapper for the underlying
2179 :cfunc:`fread` C function, and will behave the same in corner cases,
2180 such as whether the EOF value is cached.
2183 .. method:: file.readline([size])
2185 Read one entire line from the file. A trailing newline character is kept in the
2186 string (but may be absent when a file ends with an incomplete line). [#]_ If
2187 the *size* argument is present and non-negative, it is a maximum byte count
2188 (including the trailing newline) and an incomplete line may be returned. An
2189 empty string is returned *only* when EOF is encountered immediately.
2193 Unlike ``stdio``'s :cfunc:`fgets`, the returned string contains null characters
2194 (``'\0'``) if they occurred in the input.
2197 .. method:: file.readlines([sizehint])
2199 Read until EOF using :meth:`readline` and return a list containing the lines
2200 thus read. If the optional *sizehint* argument is present, instead of
2201 reading up to EOF, whole lines totalling approximately *sizehint* bytes
2202 (possibly after rounding up to an internal buffer size) are read. Objects
2203 implementing a file-like interface may choose to ignore *sizehint* if it
2204 cannot be implemented, or cannot be implemented efficiently.
2207 .. method:: file.xreadlines()
2209 This method returns the same thing as ``iter(f)``.
2211 .. versionadded:: 2.1
2214 Use ``for line in file`` instead.
2217 .. method:: file.seek(offset[, whence])
2219 Set the file's current position, like ``stdio``'s :cfunc:`fseek`. The *whence*
2220 argument is optional and defaults to ``os.SEEK_SET`` or ``0`` (absolute file
2221 positioning); other values are ``os.SEEK_CUR`` or ``1`` (seek relative to the
2222 current position) and ``os.SEEK_END`` or ``2`` (seek relative to the file's
2223 end). There is no return value.
2225 For example, ``f.seek(2, os.SEEK_CUR)`` advances the position by two and
2226 ``f.seek(-3, os.SEEK_END)`` sets the position to the third to last.
2228 Note that if the file is opened for appending
2229 (mode ``'a'`` or ``'a+'``), any :meth:`seek` operations will be undone at the
2230 next write. If the file is only opened for writing in append mode (mode
2231 ``'a'``), this method is essentially a no-op, but it remains useful for files
2232 opened in append mode with reading enabled (mode ``'a+'``). If the file is
2233 opened in text mode (without ``'b'``), only offsets returned by :meth:`tell` are
2234 legal. Use of other offsets causes undefined behavior.
2236 Note that not all file objects are seekable.
2238 .. versionchanged:: 2.6
2239 Passing float values as offset has been deprecated.
2242 .. method:: file.tell()
2244 Return the file's current position, like ``stdio``'s :cfunc:`ftell`.
2248 On Windows, :meth:`tell` can return illegal values (after an :cfunc:`fgets`)
2249 when reading files with Unix-style line-endings. Use binary mode (``'rb'``) to
2250 circumvent this problem.
2253 .. method:: file.truncate([size])
2255 Truncate the file's size. If the optional *size* argument is present, the file
2256 is truncated to (at most) that size. The size defaults to the current position.
2257 The current file position is not changed. Note that if a specified size exceeds
2258 the file's current size, the result is platform-dependent: possibilities
2259 include that the file may remain unchanged, increase to the specified size as if
2260 zero-filled, or increase to the specified size with undefined new content.
2261 Availability: Windows, many Unix variants.
2264 .. method:: file.write(str)
2266 Write a string to the file. There is no return value. Due to buffering, the
2267 string may not actually show up in the file until the :meth:`flush` or
2268 :meth:`close` method is called.
2271 .. method:: file.writelines(sequence)
2273 Write a sequence of strings to the file. The sequence can be any iterable
2274 object producing strings, typically a list of strings. There is no return value.
2275 (The name is intended to match :meth:`readlines`; :meth:`writelines` does not
2276 add line separators.)
2278 Files support the iterator protocol. Each iteration returns the same result as
2279 ``file.readline()``, and iteration ends when the :meth:`readline` method returns
2282 File objects also offer a number of other interesting attributes. These are not
2283 required for file-like objects, but should be implemented if they make sense for
2284 the particular object.
2287 .. attribute:: file.closed
2289 bool indicating the current state of the file object. This is a read-only
2290 attribute; the :meth:`close` method changes the value. It may not be available
2291 on all file-like objects.
2294 .. attribute:: file.encoding
2296 The encoding that this file uses. When Unicode strings are written to a file,
2297 they will be converted to byte strings using this encoding. In addition, when
2298 the file is connected to a terminal, the attribute gives the encoding that the
2299 terminal is likely to use (that information might be incorrect if the user has
2300 misconfigured the terminal). The attribute is read-only and may not be present
2301 on all file-like objects. It may also be ``None``, in which case the file uses
2302 the system default encoding for converting Unicode strings.
2304 .. versionadded:: 2.3
2307 .. attribute:: file.errors
2309 The Unicode error handler used along with the encoding.
2311 .. versionadded:: 2.6
2314 .. attribute:: file.mode
2316 The I/O mode for the file. If the file was created using the :func:`open`
2317 built-in function, this will be the value of the *mode* parameter. This is a
2318 read-only attribute and may not be present on all file-like objects.
2321 .. attribute:: file.name
2323 If the file object was created using :func:`open`, the name of the file.
2324 Otherwise, some string that indicates the source of the file object, of the
2325 form ``<...>``. This is a read-only attribute and may not be present on all
2329 .. attribute:: file.newlines
2331 If Python was built with the :option:`--with-universal-newlines` option to
2332 :program:`configure` (the default) this read-only attribute exists, and for
2333 files opened in universal newline read mode it keeps track of the types of
2334 newlines encountered while reading the file. The values it can take are
2335 ``'\r'``, ``'\n'``, ``'\r\n'``, ``None`` (unknown, no newlines read yet) or a
2336 tuple containing all the newline types seen, to indicate that multiple newline
2337 conventions were encountered. For files not opened in universal newline read
2338 mode the value of this attribute will be ``None``.
2341 .. attribute:: file.softspace
2343 Boolean that indicates whether a space character needs to be printed before
2344 another value when using the :keyword:`print` statement. Classes that are trying
2345 to simulate a file object should also have a writable :attr:`softspace`
2346 attribute, which should be initialized to zero. This will be automatic for most
2347 classes implemented in Python (care may be needed for objects that override
2348 attribute access); types implemented in C will have to provide a writable
2349 :attr:`softspace` attribute.
2353 This attribute is not used to control the :keyword:`print` statement, but to
2354 allow the implementation of :keyword:`print` to keep track of its internal
2358 .. _typecontextmanager:
2360 Context Manager Types
2361 =====================
2363 .. versionadded:: 2.5
2366 single: context manager
2367 single: context management protocol
2368 single: protocol; context management
2370 Python's :keyword:`with` statement supports the concept of a runtime context
2371 defined by a context manager. This is implemented using two separate methods
2372 that allow user-defined classes to define a runtime context that is entered
2373 before the statement body is executed and exited when the statement ends.
2375 The :dfn:`context management protocol` consists of a pair of methods that need
2376 to be provided for a context manager object to define a runtime context:
2379 .. method:: contextmanager.__enter__()
2381 Enter the runtime context and return either this object or another object
2382 related to the runtime context. The value returned by this method is bound to
2383 the identifier in the :keyword:`as` clause of :keyword:`with` statements using
2384 this context manager.
2386 An example of a context manager that returns itself is a file object. File
2387 objects return themselves from __enter__() to allow :func:`open` to be used as
2388 the context expression in a :keyword:`with` statement.
2390 An example of a context manager that returns a related object is the one
2391 returned by :func:`decimal.localcontext`. These managers set the active
2392 decimal context to a copy of the original decimal context and then return the
2393 copy. This allows changes to be made to the current decimal context in the body
2394 of the :keyword:`with` statement without affecting code outside the
2395 :keyword:`with` statement.
2398 .. method:: contextmanager.__exit__(exc_type, exc_val, exc_tb)
2400 Exit the runtime context and return a Boolean flag indicating if any exception
2401 that occurred should be suppressed. If an exception occurred while executing the
2402 body of the :keyword:`with` statement, the arguments contain the exception type,
2403 value and traceback information. Otherwise, all three arguments are ``None``.
2405 Returning a true value from this method will cause the :keyword:`with` statement
2406 to suppress the exception and continue execution with the statement immediately
2407 following the :keyword:`with` statement. Otherwise the exception continues
2408 propagating after this method has finished executing. Exceptions that occur
2409 during execution of this method will replace any exception that occurred in the
2410 body of the :keyword:`with` statement.
2412 The exception passed in should never be reraised explicitly - instead, this
2413 method should return a false value to indicate that the method completed
2414 successfully and does not want to suppress the raised exception. This allows
2415 context management code (such as ``contextlib.nested``) to easily detect whether
2416 or not an :meth:`__exit__` method has actually failed.
2418 Python defines several context managers to support easy thread synchronisation,
2419 prompt closure of files or other objects, and simpler manipulation of the active
2420 decimal arithmetic context. The specific types are not treated specially beyond
2421 their implementation of the context management protocol. See the
2422 :mod:`contextlib` module for some examples.
2424 Python's :term:`generator`\s and the ``contextlib.contextfactory`` :term:`decorator`
2425 provide a convenient way to implement these protocols. If a generator function is
2426 decorated with the ``contextlib.contextfactory`` decorator, it will return a
2427 context manager implementing the necessary :meth:`__enter__` and
2428 :meth:`__exit__` methods, rather than the iterator produced by an undecorated
2431 Note that there is no specific slot for any of these methods in the type
2432 structure for Python objects in the Python/C API. Extension types wanting to
2433 define these methods must provide them as a normal Python accessible method.
2434 Compared to the overhead of setting up the runtime context, the overhead of a
2435 single class dictionary lookup is negligible.
2440 Other Built-in Types
2441 ====================
2443 The interpreter supports several other kinds of objects. Most of these support
2444 only one or two operations.
2452 The only special operation on a module is attribute access: ``m.name``, where
2453 *m* is a module and *name* accesses a name defined in *m*'s symbol table.
2454 Module attributes can be assigned to. (Note that the :keyword:`import`
2455 statement is not, strictly speaking, an operation on a module object; ``import
2456 foo`` does not require a module object named *foo* to exist, rather it requires
2457 an (external) *definition* for a module named *foo* somewhere.)
2459 A special member of every module is :attr:`__dict__`. This is the dictionary
2460 containing the module's symbol table. Modifying this dictionary will actually
2461 change the module's symbol table, but direct assignment to the :attr:`__dict__`
2462 attribute is not possible (you can write ``m.__dict__['a'] = 1``, which defines
2463 ``m.a`` to be ``1``, but you can't write ``m.__dict__ = {}``). Modifying
2464 :attr:`__dict__` directly is not recommended.
2466 Modules built into the interpreter are written like this: ``<module 'sys'
2467 (built-in)>``. If loaded from a file, they are written as ``<module 'os' from
2468 '/usr/local/lib/pythonX.Y/os.pyc'>``.
2473 Classes and Class Instances
2474 ---------------------------
2476 See :ref:`objects` and :ref:`class` for these.
2484 Function objects are created by function definitions. The only operation on a
2485 function object is to call it: ``func(argument-list)``.
2487 There are really two flavors of function objects: built-in functions and
2488 user-defined functions. Both support the same operation (to call the function),
2489 but the implementation is different, hence the different object types.
2491 See :ref:`function` for more information.
2499 .. index:: object: method
2501 Methods are functions that are called using the attribute notation. There are
2502 two flavors: built-in methods (such as :meth:`append` on lists) and class
2503 instance methods. Built-in methods are described with the types that support
2506 The implementation adds two special read-only attributes to class instance
2507 methods: ``m.im_self`` is the object on which the method operates, and
2508 ``m.im_func`` is the function implementing the method. Calling ``m(arg-1,
2509 arg-2, ..., arg-n)`` is completely equivalent to calling ``m.im_func(m.im_self,
2510 arg-1, arg-2, ..., arg-n)``.
2512 Class instance methods are either *bound* or *unbound*, referring to whether the
2513 method was accessed through an instance or a class, respectively. When a method
2514 is unbound, its ``im_self`` attribute will be ``None`` and if called, an
2515 explicit ``self`` object must be passed as the first argument. In this case,
2516 ``self`` must be an instance of the unbound method's class (or a subclass of
2517 that class), otherwise a :exc:`TypeError` is raised.
2519 Like function objects, methods objects support getting arbitrary attributes.
2520 However, since method attributes are actually stored on the underlying function
2521 object (``meth.im_func``), setting method attributes on either bound or unbound
2522 methods is disallowed. Attempting to set a method attribute results in a
2523 :exc:`TypeError` being raised. In order to set a method attribute, you need to
2524 explicitly set it on the underlying function object::
2531 c.method.im_func.whoami = 'my name is c'
2533 See :ref:`types` for more information.
2536 .. _bltin-code-objects:
2541 .. index:: object: code
2545 single: func_code (function object attribute)
2547 Code objects are used by the implementation to represent "pseudo-compiled"
2548 executable Python code such as a function body. They differ from function
2549 objects because they don't contain a reference to their global execution
2550 environment. Code objects are returned by the built-in :func:`compile` function
2551 and can be extracted from function objects through their :attr:`func_code`
2552 attribute. See also the :mod:`code` module.
2558 A code object can be executed or evaluated by passing it (instead of a source
2559 string) to the :keyword:`exec` statement or the built-in :func:`eval` function.
2561 See :ref:`types` for more information.
2564 .. _bltin-type-objects:
2573 Type objects represent the various object types. An object's type is accessed
2574 by the built-in function :func:`type`. There are no special operations on
2575 types. The standard module :mod:`types` defines names for all standard built-in
2578 Types are written like this: ``<type 'int'>``.
2581 .. _bltin-null-object:
2586 This object is returned by functions that don't explicitly return a value. It
2587 supports no special operations. There is exactly one null object, named
2588 ``None`` (a built-in name).
2590 It is written as ``None``.
2593 .. _bltin-ellipsis-object:
2598 This object is used by extended slice notation (see :ref:`slicings`). It
2599 supports no special operations. There is exactly one ellipsis object, named
2600 :const:`Ellipsis` (a built-in name).
2602 It is written as ``Ellipsis``.
2608 Boolean values are the two constant objects ``False`` and ``True``. They are
2609 used to represent truth values (although other values can also be considered
2610 false or true). In numeric contexts (for example when used as the argument to
2611 an arithmetic operator), they behave like the integers 0 and 1, respectively.
2612 The built-in function :func:`bool` can be used to cast any value to a Boolean,
2613 if the value can be interpreted as a truth value (see section Truth Value
2619 pair: Boolean; values
2621 They are written as ``False`` and ``True``, respectively.
2629 See :ref:`types` for this information. It describes stack frame objects,
2630 traceback objects, and slice objects.
2638 The implementation adds a few special read-only attributes to several object
2639 types, where they are relevant. Some of these are not reported by the
2640 :func:`dir` built-in function.
2643 .. attribute:: object.__dict__
2645 A dictionary or other mapping object used to store an object's (writable)
2649 .. attribute:: object.__methods__
2652 Use the built-in function :func:`dir` to get a list of an object's attributes.
2653 This attribute is no longer available.
2656 .. attribute:: object.__members__
2659 Use the built-in function :func:`dir` to get a list of an object's attributes.
2660 This attribute is no longer available.
2663 .. attribute:: instance.__class__
2665 The class to which a class instance belongs.
2668 .. attribute:: class.__bases__
2670 The tuple of base classes of a class object. If there are no base classes, this
2671 will be an empty tuple.
2674 .. attribute:: class.__name__
2676 The name of the class or type.
2678 .. rubric:: Footnotes
2680 .. [#] Additional information on these special methods may be found in the Python
2681 Reference Manual (:ref:`customization`).
2683 .. [#] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and
2684 similarly for tuples.
2686 .. [#] Beware of this formula! It's mathematically valid, but as a
2687 Python expression it will not give correct results for all ``x``,
2688 as a consequence of the limited precision of floating-point
2691 .. [#] They must have since the parser can't tell the type of the operands.
2693 .. [#] To format only a tuple you should therefore provide a singleton tuple whose only
2694 element is the tuple to be formatted.
2696 .. [#] These numbers are fairly arbitrary. They are intended to avoid printing endless
2697 strings of meaningless digits without hampering correct use and without having
2698 to know the exact precision of floating point values on a particular machine.
2700 .. [#] The advantage of leaving the newline on is that returning an empty string is
2701 then an unambiguous EOF indication. It is also possible (in cases where it
2702 might matter, for example, if you want to make an exact copy of a file while
2703 scanning its lines) to tell whether the last line of a file ended in a newline
2704 or not (yes this happens!).