blob: aba58ec27f82c7c58f785a1db342b60158e10ecb [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. XXX: reference/datamodel and this have quite a few overlaps!
2
3
4.. _bltin-types:
5
6**************
7Built-in Types
8**************
9
10The following sections describe the standard types that are built into the
11interpreter.
12
Georg Brandl116aa622007-08-15 14:28:22 +000013.. index:: pair: built-in; types
14
Antoine Pitroue231e392009-12-19 18:22:15 +000015The principal built-in types are numerics, sequences, mappings, classes,
Georg Brandl116aa622007-08-15 14:28:22 +000016instances and exceptions.
17
Georg Brandl116aa622007-08-15 14:28:22 +000018Some operations are supported by several object types; in particular,
19practically all objects can be compared, tested for truth value, and converted
20to a string (with the :func:`repr` function or the slightly different
21:func:`str` function). The latter function is implicitly used when an object is
22written by the :func:`print` function.
23
24
25.. _truth:
26
27Truth Value Testing
28===================
29
30.. index::
31 statement: if
32 statement: while
33 pair: truth; value
34 pair: Boolean; operations
35 single: false
36
37Any object can be tested for truth value, for use in an :keyword:`if` or
38:keyword:`while` condition or as operand of the Boolean operations below. The
39following values are considered false:
40
41 .. index:: single: None (Built-in object)
42
43* ``None``
44
45 .. index:: single: False (Built-in object)
46
47* ``False``
48
Mark Summerfieldbbfd71d2008-07-01 15:50:04 +000049* zero of any numeric type, for example, ``0``, ``0.0``, ``0j``.
Georg Brandl116aa622007-08-15 14:28:22 +000050
51* any empty sequence, for example, ``''``, ``()``, ``[]``.
52
53* any empty mapping, for example, ``{}``.
54
55* instances of user-defined classes, if the class defines a :meth:`__bool__` or
56 :meth:`__len__` method, when that method returns the integer zero or
Ezio Melotti0656a562011-08-15 14:27:19 +030057 :class:`bool` value ``False``. [1]_
Georg Brandl116aa622007-08-15 14:28:22 +000058
59.. index:: single: true
60
61All other values are considered true --- so objects of many types are always
62true.
63
64.. index::
65 operator: or
66 operator: and
67 single: False
68 single: True
69
70Operations and built-in functions that have a Boolean result always return ``0``
71or ``False`` for false and ``1`` or ``True`` for true, unless otherwise stated.
72(Important exception: the Boolean operations ``or`` and ``and`` always return
73one of their operands.)
74
75
76.. _boolean:
77
78Boolean Operations --- :keyword:`and`, :keyword:`or`, :keyword:`not`
79====================================================================
80
81.. index:: pair: Boolean; operations
82
83These are the Boolean operations, ordered by ascending priority:
84
85+-------------+---------------------------------+-------+
86| Operation | Result | Notes |
87+=============+=================================+=======+
88| ``x or y`` | if *x* is false, then *y*, else | \(1) |
89| | *x* | |
90+-------------+---------------------------------+-------+
91| ``x and y`` | if *x* is false, then *x*, else | \(2) |
92| | *y* | |
93+-------------+---------------------------------+-------+
94| ``not x`` | if *x* is false, then ``True``, | \(3) |
95| | else ``False`` | |
96+-------------+---------------------------------+-------+
97
98.. index::
99 operator: and
100 operator: or
101 operator: not
102
103Notes:
104
105(1)
106 This is a short-circuit operator, so it only evaluates the second
107 argument if the first one is :const:`False`.
108
109(2)
110 This is a short-circuit operator, so it only evaluates the second
111 argument if the first one is :const:`True`.
112
113(3)
114 ``not`` has a lower priority than non-Boolean operators, so ``not a == b`` is
115 interpreted as ``not (a == b)``, and ``a == not b`` is a syntax error.
116
117
118.. _stdcomparisons:
119
120Comparisons
121===========
122
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +0000123.. index::
124 pair: chaining; comparisons
125 pair: operator; comparison
126 operator: ==
127 operator: <
128 operator: <=
129 operator: >
130 operator: >=
131 operator: !=
132 operator: is
133 operator: is not
Georg Brandl116aa622007-08-15 14:28:22 +0000134
Georg Brandl905ec322007-09-28 13:39:25 +0000135There are eight comparison operations in Python. They all have the same
136priority (which is higher than that of the Boolean operations). Comparisons can
Georg Brandl116aa622007-08-15 14:28:22 +0000137be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and
138y <= z``, except that *y* is evaluated only once (but in both cases *z* is not
139evaluated at all when ``x < y`` is found to be false).
140
141This table summarizes the comparison operations:
142
Georg Brandlfd855162008-01-07 09:13:03 +0000143+------------+-------------------------+
144| Operation | Meaning |
145+============+=========================+
146| ``<`` | strictly less than |
147+------------+-------------------------+
148| ``<=`` | less than or equal |
149+------------+-------------------------+
150| ``>`` | strictly greater than |
151+------------+-------------------------+
152| ``>=`` | greater than or equal |
153+------------+-------------------------+
154| ``==`` | equal |
155+------------+-------------------------+
156| ``!=`` | not equal |
157+------------+-------------------------+
158| ``is`` | object identity |
159+------------+-------------------------+
160| ``is not`` | negated object identity |
161+------------+-------------------------+
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000162
163.. index::
Georg Brandl116aa622007-08-15 14:28:22 +0000164 pair: object; numeric
165 pair: objects; comparing
166
Georg Brandl905ec322007-09-28 13:39:25 +0000167Objects of different types, except different numeric types, never compare equal.
Antoine Pitroue231e392009-12-19 18:22:15 +0000168Furthermore, some types (for example, function objects) support only a degenerate
Georg Brandl905ec322007-09-28 13:39:25 +0000169notion of comparison where any two objects of that type are unequal. The ``<``,
170``<=``, ``>`` and ``>=`` operators will raise a :exc:`TypeError` exception when
Mark Dickinsonf673f0c2010-03-13 09:48:39 +0000171comparing a complex number with another built-in numeric type, when the objects
172are of different types that cannot be compared, or in other cases where there is
173no defined ordering.
Georg Brandl116aa622007-08-15 14:28:22 +0000174
Georg Brandl48310cd2009-01-03 21:18:54 +0000175.. index::
Georg Brandl905ec322007-09-28 13:39:25 +0000176 single: __eq__() (instance method)
177 single: __ne__() (instance method)
178 single: __lt__() (instance method)
179 single: __le__() (instance method)
180 single: __gt__() (instance method)
181 single: __ge__() (instance method)
Georg Brandl116aa622007-08-15 14:28:22 +0000182
Georg Brandl05f5ab72008-09-24 09:11:47 +0000183Non-identical instances of a class normally compare as non-equal unless the
184class defines the :meth:`__eq__` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000185
Georg Brandl905ec322007-09-28 13:39:25 +0000186Instances of a class cannot be ordered with respect to other instances of the
187same class, or other types of object, unless the class defines enough of the
Georg Brandl05f5ab72008-09-24 09:11:47 +0000188methods :meth:`__lt__`, :meth:`__le__`, :meth:`__gt__`, and :meth:`__ge__` (in
189general, :meth:`__lt__` and :meth:`__eq__` are sufficient, if you want the
190conventional meanings of the comparison operators).
Georg Brandl905ec322007-09-28 13:39:25 +0000191
192The behavior of the :keyword:`is` and :keyword:`is not` operators cannot be
193customized; also they can be applied to any two objects and never raise an
194exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000195
196.. index::
197 operator: in
198 operator: not in
199
Georg Brandl375aec22011-01-15 17:03:02 +0000200Two more operations with the same syntactic priority, :keyword:`in` and
201:keyword:`not in`, are supported only by sequence types (below).
Georg Brandl116aa622007-08-15 14:28:22 +0000202
203
204.. _typesnumeric:
205
Georg Brandl905ec322007-09-28 13:39:25 +0000206Numeric Types --- :class:`int`, :class:`float`, :class:`complex`
207================================================================
Georg Brandl116aa622007-08-15 14:28:22 +0000208
209.. index::
210 object: numeric
211 object: Boolean
212 object: integer
Georg Brandl116aa622007-08-15 14:28:22 +0000213 object: floating point
214 object: complex number
215 pair: C; language
216
Mark Summerfieldbbfd71d2008-07-01 15:50:04 +0000217There are three distinct numeric types: :dfn:`integers`, :dfn:`floating
218point numbers`, and :dfn:`complex numbers`. In addition, Booleans are a
219subtype of integers. Integers have unlimited precision. Floating point
Georg Brandl60203b42010-10-06 10:11:56 +0000220numbers are usually implemented using :c:type:`double` in C; information
Mark Dickinson74f59022010-08-04 18:42:43 +0000221about the precision and internal representation of floating point
222numbers for the machine on which your program is running is available
223in :data:`sys.float_info`. Complex numbers have a real and imaginary
224part, which are each a floating point number. To extract these parts
225from a complex number *z*, use ``z.real`` and ``z.imag``. (The standard
226library includes additional numeric types, :mod:`fractions` that hold
227rationals, and :mod:`decimal` that hold floating-point numbers with
228user-definable precision.)
Georg Brandl116aa622007-08-15 14:28:22 +0000229
230.. index::
231 pair: numeric; literals
232 pair: integer; literals
Georg Brandl116aa622007-08-15 14:28:22 +0000233 pair: floating point; literals
234 pair: complex number; literals
235 pair: hexadecimal; literals
236 pair: octal; literals
Neal Norwitz1d2aef52007-10-02 07:26:14 +0000237 pair: binary; literals
Georg Brandl116aa622007-08-15 14:28:22 +0000238
239Numbers are created by numeric literals or as the result of built-in functions
Georg Brandl905ec322007-09-28 13:39:25 +0000240and operators. Unadorned integer literals (including hex, octal and binary
241numbers) yield integers. Numeric literals containing a decimal point or an
242exponent sign yield floating point numbers. Appending ``'j'`` or ``'J'`` to a
243numeric literal yields an imaginary number (a complex number with a zero real
244part) which you can add to an integer or float to get a complex number with real
245and imaginary parts.
Georg Brandl116aa622007-08-15 14:28:22 +0000246
247.. index::
248 single: arithmetic
249 builtin: int
Georg Brandl116aa622007-08-15 14:28:22 +0000250 builtin: float
251 builtin: complex
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +0000252 operator: +
253 operator: -
254 operator: *
255 operator: /
256 operator: //
257 operator: %
258 operator: **
Georg Brandl116aa622007-08-15 14:28:22 +0000259
260Python fully supports mixed arithmetic: when a binary arithmetic operator has
261operands of different numeric types, the operand with the "narrower" type is
Georg Brandl905ec322007-09-28 13:39:25 +0000262widened to that of the other, where integer is narrower than floating point,
263which is narrower than complex. Comparisons between numbers of mixed type use
Ezio Melotti0656a562011-08-15 14:27:19 +0300264the same rule. [2]_ The constructors :func:`int`, :func:`float`, and
Georg Brandl905ec322007-09-28 13:39:25 +0000265:func:`complex` can be used to produce numbers of a specific type.
Georg Brandl116aa622007-08-15 14:28:22 +0000266
267All numeric types (except complex) support the following operations, sorted by
268ascending priority (operations in the same box have the same priority; all
269numeric operations have a higher priority than comparison operations):
270
Raymond Hettingerc706dbf2011-03-22 17:33:17 -0700271+---------------------+---------------------------------+---------+--------------------+
272| Operation | Result | Notes | Full documentation |
273+=====================+=================================+=========+====================+
274| ``x + y`` | sum of *x* and *y* | | |
275+---------------------+---------------------------------+---------+--------------------+
276| ``x - y`` | difference of *x* and *y* | | |
277+---------------------+---------------------------------+---------+--------------------+
278| ``x * y`` | product of *x* and *y* | | |
279+---------------------+---------------------------------+---------+--------------------+
280| ``x / y`` | quotient of *x* and *y* | | |
281+---------------------+---------------------------------+---------+--------------------+
282| ``x // y`` | floored quotient of *x* and | \(1) | |
283| | *y* | | |
284+---------------------+---------------------------------+---------+--------------------+
285| ``x % y`` | remainder of ``x / y`` | \(2) | |
286+---------------------+---------------------------------+---------+--------------------+
287| ``-x`` | *x* negated | | |
288+---------------------+---------------------------------+---------+--------------------+
289| ``+x`` | *x* unchanged | | |
290+---------------------+---------------------------------+---------+--------------------+
291| ``abs(x)`` | absolute value or magnitude of | | :func:`abs` |
292| | *x* | | |
293+---------------------+---------------------------------+---------+--------------------+
294| ``int(x)`` | *x* converted to integer | \(3)\(6)| :func:`int` |
295+---------------------+---------------------------------+---------+--------------------+
296| ``float(x)`` | *x* converted to floating point | \(4)\(6)| :func:`float` |
297+---------------------+---------------------------------+---------+--------------------+
298| ``complex(re, im)`` | a complex number with real part | \(6) | :func:`complex` |
299| | *re*, imaginary part *im*. | | |
300| | *im* defaults to zero. | | |
301+---------------------+---------------------------------+---------+--------------------+
302| ``c.conjugate()`` | conjugate of the complex number | | |
303| | *c* | | |
304+---------------------+---------------------------------+---------+--------------------+
305| ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | \(2) | :func:`divmod` |
306+---------------------+---------------------------------+---------+--------------------+
307| ``pow(x, y)`` | *x* to the power *y* | \(5) | :func:`pow` |
308+---------------------+---------------------------------+---------+--------------------+
309| ``x ** y`` | *x* to the power *y* | \(5) | |
310+---------------------+---------------------------------+---------+--------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000311
312.. index::
313 triple: operations on; numeric; types
314 single: conjugate() (complex number method)
315
316Notes:
317
318(1)
Georg Brandl905ec322007-09-28 13:39:25 +0000319 Also referred to as integer division. The resultant value is a whole
320 integer, though the result's type is not necessarily int. The result is
321 always rounded towards minus infinity: ``1//2`` is ``0``, ``(-1)//2`` is
322 ``-1``, ``1//(-2)`` is ``-1``, and ``(-1)//(-2)`` is ``0``.
Georg Brandl116aa622007-08-15 14:28:22 +0000323
324(2)
Georg Brandl905ec322007-09-28 13:39:25 +0000325 Not for complex numbers. Instead convert to floats using :func:`abs` if
326 appropriate.
327
328(3)
Georg Brandl116aa622007-08-15 14:28:22 +0000329 .. index::
330 module: math
331 single: floor() (in module math)
332 single: ceil() (in module math)
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000333 single: trunc() (in module math)
Georg Brandl116aa622007-08-15 14:28:22 +0000334 pair: numeric; conversions
335 pair: C; language
336
Georg Brandlba956ae2007-11-29 17:24:34 +0000337 Conversion from floating point to integer may round or truncate
Georg Brandl116aa622007-08-15 14:28:22 +0000338 as in C; see functions :func:`floor` and :func:`ceil` in the :mod:`math` module
339 for well-defined conversions.
340
Georg Brandl74f36692008-01-06 17:39:49 +0000341(4)
Georg Brandl48310cd2009-01-03 21:18:54 +0000342 float also accepts the strings "nan" and "inf" with an optional prefix "+"
Christian Heimes99170a52007-12-19 02:07:34 +0000343 or "-" for Not a Number (NaN) and positive or negative infinity.
Christian Heimes7f044312008-01-06 17:05:40 +0000344
Georg Brandl74f36692008-01-06 17:39:49 +0000345(5)
Christian Heimes7f044312008-01-06 17:05:40 +0000346 Python defines ``pow(0, 0)`` and ``0 ** 0`` to be ``1``, as is common for
347 programming languages.
348
Raymond Hettingerc706dbf2011-03-22 17:33:17 -0700349(6)
350 The numeric literals accepted include the digits ``0`` to ``9`` or any
351 Unicode equivalent (code points with the ``Nd`` property).
352
353 See http://www.unicode.org/Public/6.0.0/ucd/extracted/DerivedNumericType.txt
354 for a complete list of code points with the ``Nd`` property.
Georg Brandl48310cd2009-01-03 21:18:54 +0000355
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000356
Benjamin Peterson10116d42011-05-01 17:38:17 -0500357All :class:`numbers.Real` types (:class:`int` and :class:`float`) also include
358the following operations:
Christian Heimesfaf2f632008-01-06 16:59:19 +0000359
Benjamin Petersonb58dda72009-01-18 22:27:04 +0000360+--------------------+------------------------------------+--------+
361| Operation | Result | Notes |
362+====================+====================================+========+
363| ``math.trunc(x)`` | *x* truncated to Integral | |
364+--------------------+------------------------------------+--------+
365| ``round(x[, n])`` | *x* rounded to n digits, | |
366| | rounding half to even. If n is | |
367| | omitted, it defaults to 0. | |
368+--------------------+------------------------------------+--------+
369| ``math.floor(x)`` | the greatest integral float <= *x* | |
370+--------------------+------------------------------------+--------+
371| ``math.ceil(x)`` | the least integral float >= *x* | |
372+--------------------+------------------------------------+--------+
Christian Heimesfaf2f632008-01-06 16:59:19 +0000373
Mark Summerfieldbbfd71d2008-07-01 15:50:04 +0000374For additional numeric operations see the :mod:`math` and :mod:`cmath`
375modules.
376
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000377.. XXXJH exceptions: overflow (when? what operations?) zerodivision
Georg Brandl116aa622007-08-15 14:28:22 +0000378
379
380.. _bitstring-ops:
381
Benjamin Petersone9fca252012-01-25 16:29:03 -0500382Bitwise Operations on Integer Types
Georg Brandl116aa622007-08-15 14:28:22 +0000383--------------------------------------
384
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +0000385.. index::
386 triple: operations on; integer; types
Benjamin Petersone9fca252012-01-25 16:29:03 -0500387 pair: bitwise; operations
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +0000388 pair: shifting; operations
389 pair: masking; operations
390 operator: ^
391 operator: &
392 operator: <<
393 operator: >>
Georg Brandl116aa622007-08-15 14:28:22 +0000394
Benjamin Petersone9fca252012-01-25 16:29:03 -0500395Bitwise operations only make sense only for integers. Negative numbers are
396treated as their 2's complement value (this assumes a sufficiently large number
397of bits that no overflow occurs during the operation).
Georg Brandl116aa622007-08-15 14:28:22 +0000398
Christian Heimesfaf2f632008-01-06 16:59:19 +0000399The priorities of the binary bitwise operations are all lower than the numeric
Georg Brandl116aa622007-08-15 14:28:22 +0000400operations and higher than the comparisons; the unary operation ``~`` has the
401same priority as the other unary numeric operations (``+`` and ``-``).
402
Benjamin Petersone9fca252012-01-25 16:29:03 -0500403This table lists the bitwise operations sorted in ascending priority
Georg Brandl116aa622007-08-15 14:28:22 +0000404(operations in the same box have the same priority):
405
406+------------+--------------------------------+----------+
407| Operation | Result | Notes |
408+============+================================+==========+
409| ``x | y`` | bitwise :dfn:`or` of *x* and | |
410| | *y* | |
411+------------+--------------------------------+----------+
412| ``x ^ y`` | bitwise :dfn:`exclusive or` of | |
413| | *x* and *y* | |
414+------------+--------------------------------+----------+
415| ``x & y`` | bitwise :dfn:`and` of *x* and | |
416| | *y* | |
417+------------+--------------------------------+----------+
Christian Heimes043d6f62008-01-07 17:19:16 +0000418| ``x << n`` | *x* shifted left by *n* bits | (1)(2) |
Georg Brandl116aa622007-08-15 14:28:22 +0000419+------------+--------------------------------+----------+
Christian Heimes043d6f62008-01-07 17:19:16 +0000420| ``x >> n`` | *x* shifted right by *n* bits | (1)(3) |
Georg Brandl116aa622007-08-15 14:28:22 +0000421+------------+--------------------------------+----------+
422| ``~x`` | the bits of *x* inverted | |
423+------------+--------------------------------+----------+
424
Georg Brandl116aa622007-08-15 14:28:22 +0000425Notes:
426
427(1)
428 Negative shift counts are illegal and cause a :exc:`ValueError` to be raised.
429
430(2)
431 A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)``
432 without overflow check.
433
434(3)
435 A right shift by *n* bits is equivalent to division by ``pow(2, n)`` without
436 overflow check.
437
438
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000439Additional Methods on Integer Types
440-----------------------------------
441
Raymond Hettinger9b2fd322011-05-01 18:14:49 -0700442The int type implements the :class:`numbers.Integral` :term:`abstract base
Éric Araujob79c2342011-05-02 13:10:18 +0200443class`. In addition, it provides one more method:
Benjamin Peterson10116d42011-05-01 17:38:17 -0500444
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000445.. method:: int.bit_length()
446
Raymond Hettingerd3e18b72008-12-19 09:11:49 +0000447 Return the number of bits necessary to represent an integer in binary,
448 excluding the sign and leading zeros::
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000449
Raymond Hettingerd3e18b72008-12-19 09:11:49 +0000450 >>> n = -37
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000451 >>> bin(n)
Raymond Hettingerd3e18b72008-12-19 09:11:49 +0000452 '-0b100101'
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000453 >>> n.bit_length()
454 6
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000455
Raymond Hettingerd3e18b72008-12-19 09:11:49 +0000456 More precisely, if ``x`` is nonzero, then ``x.bit_length()`` is the
457 unique positive integer ``k`` such that ``2**(k-1) <= abs(x) < 2**k``.
458 Equivalently, when ``abs(x)`` is small enough to have a correctly
459 rounded logarithm, then ``k = 1 + int(log(abs(x), 2))``.
460 If ``x`` is zero, then ``x.bit_length()`` returns ``0``.
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000461
462 Equivalent to::
463
464 def bit_length(self):
Senthil Kumaran0aae6dc2010-06-22 02:57:23 +0000465 s = bin(self) # binary representation: bin(-37) --> '-0b100101'
Raymond Hettingerd3e18b72008-12-19 09:11:49 +0000466 s = s.lstrip('-0b') # remove leading zeros and minus sign
467 return len(s) # len('100101') --> 6
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000468
469 .. versionadded:: 3.1
470
Georg Brandl67b21b72010-08-17 15:07:14 +0000471.. method:: int.to_bytes(length, byteorder, \*, signed=False)
Alexandre Vassalottic36c3782010-01-09 20:35:09 +0000472
473 Return an array of bytes representing an integer.
474
475 >>> (1024).to_bytes(2, byteorder='big')
476 b'\x04\x00'
477 >>> (1024).to_bytes(10, byteorder='big')
478 b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'
479 >>> (-1024).to_bytes(10, byteorder='big', signed=True)
480 b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
481 >>> x = 1000
482 >>> x.to_bytes((x.bit_length() // 8) + 1, byteorder='little')
483 b'\xe8\x03'
484
485 The integer is represented using *length* bytes. An :exc:`OverflowError`
486 is raised if the integer is not representable with the given number of
487 bytes.
488
489 The *byteorder* argument determines the byte order used to represent the
490 integer. If *byteorder* is ``"big"``, the most significant byte is at the
491 beginning of the byte array. If *byteorder* is ``"little"``, the most
492 significant byte is at the end of the byte array. To request the native
493 byte order of the host system, use :data:`sys.byteorder` as the byte order
494 value.
495
496 The *signed* argument determines whether two's complement is used to
497 represent the integer. If *signed* is ``False`` and a negative integer is
498 given, an :exc:`OverflowError` is raised. The default value for *signed*
499 is ``False``.
500
501 .. versionadded:: 3.2
502
Georg Brandl67b21b72010-08-17 15:07:14 +0000503.. classmethod:: int.from_bytes(bytes, byteorder, \*, signed=False)
Alexandre Vassalottic36c3782010-01-09 20:35:09 +0000504
505 Return the integer represented by the given array of bytes.
506
507 >>> int.from_bytes(b'\x00\x10', byteorder='big')
508 16
509 >>> int.from_bytes(b'\x00\x10', byteorder='little')
510 4096
511 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)
512 -1024
513 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False)
514 64512
515 >>> int.from_bytes([255, 0, 0], byteorder='big')
516 16711680
517
518 The argument *bytes* must either support the buffer protocol or be an
519 iterable producing bytes. :class:`bytes` and :class:`bytearray` are
520 examples of built-in objects that support the buffer protocol.
521
522 The *byteorder* argument determines the byte order used to represent the
523 integer. If *byteorder* is ``"big"``, the most significant byte is at the
524 beginning of the byte array. If *byteorder* is ``"little"``, the most
525 significant byte is at the end of the byte array. To request the native
526 byte order of the host system, use :data:`sys.byteorder` as the byte order
527 value.
528
529 The *signed* argument indicates whether two's complement is used to
530 represent the integer.
531
532 .. versionadded:: 3.2
533
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000534
Mark Dickinson65fe25e2008-07-16 11:30:51 +0000535Additional Methods on Float
536---------------------------
537
Benjamin Peterson10116d42011-05-01 17:38:17 -0500538The float type implements the :class:`numbers.Real` :term:`abstract base
539class`. float also has the following additional methods.
Benjamin Petersond7b03282008-09-13 15:58:53 +0000540
541.. method:: float.as_integer_ratio()
542
Mark Dickinson4a3c7c42010-11-07 12:48:18 +0000543 Return a pair of integers whose ratio is exactly equal to the
544 original float and with a positive denominator. Raises
545 :exc:`OverflowError` on infinities and a :exc:`ValueError` on
546 NaNs.
547
548.. method:: float.is_integer()
549
550 Return ``True`` if the float instance is finite with integral
551 value, and ``False`` otherwise::
552
553 >>> (-2.0).is_integer()
554 True
555 >>> (3.2).is_integer()
556 False
Georg Brandl48310cd2009-01-03 21:18:54 +0000557
Benjamin Petersond7b03282008-09-13 15:58:53 +0000558Two methods support conversion to
Mark Dickinson65fe25e2008-07-16 11:30:51 +0000559and from hexadecimal strings. Since Python's floats are stored
560internally as binary numbers, converting a float to or from a
561*decimal* string usually involves a small rounding error. In
562contrast, hexadecimal strings allow exact representation and
563specification of floating-point numbers. This can be useful when
564debugging, and in numerical work.
565
566
567.. method:: float.hex()
568
569 Return a representation of a floating-point number as a hexadecimal
570 string. For finite floating-point numbers, this representation
571 will always include a leading ``0x`` and a trailing ``p`` and
572 exponent.
573
574
Georg Brandlabc38772009-04-12 15:51:51 +0000575.. classmethod:: float.fromhex(s)
Mark Dickinson65fe25e2008-07-16 11:30:51 +0000576
577 Class method to return the float represented by a hexadecimal
578 string *s*. The string *s* may have leading and trailing
579 whitespace.
580
581
582Note that :meth:`float.hex` is an instance method, while
583:meth:`float.fromhex` is a class method.
584
585A hexadecimal string takes the form::
586
587 [sign] ['0x'] integer ['.' fraction] ['p' exponent]
588
589where the optional ``sign`` may by either ``+`` or ``-``, ``integer``
590and ``fraction`` are strings of hexadecimal digits, and ``exponent``
591is a decimal integer with an optional leading sign. Case is not
592significant, and there must be at least one hexadecimal digit in
593either the integer or the fraction. This syntax is similar to the
594syntax specified in section 6.4.4.2 of the C99 standard, and also to
595the syntax used in Java 1.5 onwards. In particular, the output of
596:meth:`float.hex` is usable as a hexadecimal floating-point literal in
597C or Java code, and hexadecimal strings produced by C's ``%a`` format
598character or Java's ``Double.toHexString`` are accepted by
599:meth:`float.fromhex`.
600
601
602Note that the exponent is written in decimal rather than hexadecimal,
603and that it gives the power of 2 by which to multiply the coefficient.
604For example, the hexadecimal string ``0x3.a7p10`` represents the
605floating-point number ``(3 + 10./16 + 7./16**2) * 2.0**10``, or
606``3740.0``::
607
608 >>> float.fromhex('0x3.a7p10')
609 3740.0
610
611
612Applying the reverse conversion to ``3740.0`` gives a different
613hexadecimal string representing the same number::
614
615 >>> float.hex(3740.0)
616 '0x1.d380000000000p+11'
617
618
Mark Dickinsondc787d22010-05-23 13:33:13 +0000619.. _numeric-hash:
620
621Hashing of numeric types
622------------------------
623
624For numbers ``x`` and ``y``, possibly of different types, it's a requirement
625that ``hash(x) == hash(y)`` whenever ``x == y`` (see the :meth:`__hash__`
626method documentation for more details). For ease of implementation and
627efficiency across a variety of numeric types (including :class:`int`,
628:class:`float`, :class:`decimal.Decimal` and :class:`fractions.Fraction`)
629Python's hash for numeric types is based on a single mathematical function
630that's defined for any rational number, and hence applies to all instances of
631:class:`int` and :class:`fraction.Fraction`, and all finite instances of
632:class:`float` and :class:`decimal.Decimal`. Essentially, this function is
633given by reduction modulo ``P`` for a fixed prime ``P``. The value of ``P`` is
634made available to Python as the :attr:`modulus` attribute of
635:data:`sys.hash_info`.
636
637.. impl-detail::
638
639 Currently, the prime used is ``P = 2**31 - 1`` on machines with 32-bit C
640 longs and ``P = 2**61 - 1`` on machines with 64-bit C longs.
641
642Here are the rules in detail:
643
644 - If ``x = m / n`` is a nonnegative rational number and ``n`` is not divisible
645 by ``P``, define ``hash(x)`` as ``m * invmod(n, P) % P``, where ``invmod(n,
646 P)`` gives the inverse of ``n`` modulo ``P``.
647
648 - If ``x = m / n`` is a nonnegative rational number and ``n`` is
649 divisible by ``P`` (but ``m`` is not) then ``n`` has no inverse
650 modulo ``P`` and the rule above doesn't apply; in this case define
651 ``hash(x)`` to be the constant value ``sys.hash_info.inf``.
652
653 - If ``x = m / n`` is a negative rational number define ``hash(x)``
654 as ``-hash(-x)``. If the resulting hash is ``-1``, replace it with
655 ``-2``.
656
657 - The particular values ``sys.hash_info.inf``, ``-sys.hash_info.inf``
658 and ``sys.hash_info.nan`` are used as hash values for positive
659 infinity, negative infinity, or nans (respectively). (All hashable
660 nans have the same hash value.)
661
662 - For a :class:`complex` number ``z``, the hash values of the real
663 and imaginary parts are combined by computing ``hash(z.real) +
664 sys.hash_info.imag * hash(z.imag)``, reduced modulo
665 ``2**sys.hash_info.width`` so that it lies in
666 ``range(-2**(sys.hash_info.width - 1), 2**(sys.hash_info.width -
667 1))``. Again, if the result is ``-1``, it's replaced with ``-2``.
668
669
670To clarify the above rules, here's some example Python code,
671equivalent to the builtin hash, for computing the hash of a rational
672number, :class:`float`, or :class:`complex`::
673
674
675 import sys, math
676
677 def hash_fraction(m, n):
678 """Compute the hash of a rational number m / n.
679
680 Assumes m and n are integers, with n positive.
681 Equivalent to hash(fractions.Fraction(m, n)).
682
683 """
684 P = sys.hash_info.modulus
685 # Remove common factors of P. (Unnecessary if m and n already coprime.)
686 while m % P == n % P == 0:
687 m, n = m // P, n // P
688
689 if n % P == 0:
690 hash_ = sys.hash_info.inf
691 else:
692 # Fermat's Little Theorem: pow(n, P-1, P) is 1, so
693 # pow(n, P-2, P) gives the inverse of n modulo P.
694 hash_ = (abs(m) % P) * pow(n, P - 2, P) % P
695 if m < 0:
696 hash_ = -hash_
697 if hash_ == -1:
698 hash_ = -2
699 return hash_
700
701 def hash_float(x):
702 """Compute the hash of a float x."""
703
704 if math.isnan(x):
705 return sys.hash_info.nan
706 elif math.isinf(x):
707 return sys.hash_info.inf if x > 0 else -sys.hash_info.inf
708 else:
709 return hash_fraction(*x.as_integer_ratio())
710
711 def hash_complex(z):
712 """Compute the hash of a complex number z."""
713
714 hash_ = hash_float(z.real) + sys.hash_info.imag * hash_float(z.imag)
715 # do a signed reduction modulo 2**sys.hash_info.width
716 M = 2**(sys.hash_info.width - 1)
717 hash_ = (hash_ & (M - 1)) - (hash & M)
718 if hash_ == -1:
719 hash_ == -2
720 return hash_
721
Georg Brandl6ea420b2008-07-16 12:58:29 +0000722.. _typeiter:
723
Georg Brandl116aa622007-08-15 14:28:22 +0000724Iterator Types
725==============
726
Georg Brandl116aa622007-08-15 14:28:22 +0000727.. index::
728 single: iterator protocol
729 single: protocol; iterator
730 single: sequence; iteration
731 single: container; iteration over
732
733Python supports a concept of iteration over containers. This is implemented
734using two distinct methods; these are used to allow user-defined classes to
735support iteration. Sequences, described below in more detail, always support
736the iteration methods.
737
738One method needs to be defined for container objects to provide iteration
739support:
740
Christian Heimes790c8232008-01-07 21:14:23 +0000741.. XXX duplicated in reference/datamodel!
Georg Brandl116aa622007-08-15 14:28:22 +0000742
Christian Heimes790c8232008-01-07 21:14:23 +0000743.. method:: container.__iter__()
Georg Brandl116aa622007-08-15 14:28:22 +0000744
745 Return an iterator object. The object is required to support the iterator
746 protocol described below. If a container supports different types of
747 iteration, additional methods can be provided to specifically request
748 iterators for those iteration types. (An example of an object supporting
749 multiple forms of iteration would be a tree structure which supports both
750 breadth-first and depth-first traversal.) This method corresponds to the
751 :attr:`tp_iter` slot of the type structure for Python objects in the Python/C
752 API.
753
754The iterator objects themselves are required to support the following two
755methods, which together form the :dfn:`iterator protocol`:
756
757
758.. method:: iterator.__iter__()
759
760 Return the iterator object itself. This is required to allow both containers
761 and iterators to be used with the :keyword:`for` and :keyword:`in` statements.
762 This method corresponds to the :attr:`tp_iter` slot of the type structure for
763 Python objects in the Python/C API.
764
765
Georg Brandl905ec322007-09-28 13:39:25 +0000766.. method:: iterator.__next__()
Georg Brandl116aa622007-08-15 14:28:22 +0000767
768 Return the next item from the container. If there are no further items, raise
769 the :exc:`StopIteration` exception. This method corresponds to the
770 :attr:`tp_iternext` slot of the type structure for Python objects in the
771 Python/C API.
772
773Python defines several iterator objects to support iteration over general and
774specific sequence types, dictionaries, and other more specialized forms. The
775specific types are not important beyond their implementation of the iterator
776protocol.
777
Georg Brandl905ec322007-09-28 13:39:25 +0000778Once an iterator's :meth:`__next__` method raises :exc:`StopIteration`, it must
779continue to do so on subsequent calls. Implementations that do not obey this
780property are deemed broken.
Georg Brandl116aa622007-08-15 14:28:22 +0000781
Benjamin Peterson0289b152009-06-28 17:22:03 +0000782
783.. _generator-types:
784
785Generator Types
786---------------
787
Georg Brandl9afde1c2007-11-01 20:32:30 +0000788Python's :term:`generator`\s provide a convenient way to implement the iterator
789protocol. If a container object's :meth:`__iter__` method is implemented as a
790generator, it will automatically return an iterator object (technically, a
791generator object) supplying the :meth:`__iter__` and :meth:`__next__` methods.
Benjamin Peterson0289b152009-06-28 17:22:03 +0000792More information about generators can be found in :ref:`the documentation for
793the yield expression <yieldexpr>`.
Georg Brandl116aa622007-08-15 14:28:22 +0000794
795
796.. _typesseq:
797
Georg Brandl95414632007-11-22 11:00:28 +0000798Sequence Types --- :class:`str`, :class:`bytes`, :class:`bytearray`, :class:`list`, :class:`tuple`, :class:`range`
799==================================================================================================================
Georg Brandl116aa622007-08-15 14:28:22 +0000800
Georg Brandle17d5862009-01-18 10:40:25 +0000801There are six sequence types: strings, byte sequences (:class:`bytes` objects),
Benjamin Petersonb58dda72009-01-18 22:27:04 +0000802byte arrays (:class:`bytearray` objects), lists, tuples, and range objects. For
803other containers see the built in :class:`dict` and :class:`set` classes, and
804the :mod:`collections` module.
Georg Brandle17d5862009-01-18 10:40:25 +0000805
Georg Brandl116aa622007-08-15 14:28:22 +0000806
807.. index::
808 object: sequence
809 object: string
Georg Brandl4b491312007-08-31 09:22:56 +0000810 object: bytes
Georg Brandle17d5862009-01-18 10:40:25 +0000811 object: bytearray
Georg Brandl116aa622007-08-15 14:28:22 +0000812 object: tuple
813 object: list
Georg Brandl116aa622007-08-15 14:28:22 +0000814 object: range
815
Georg Brandl7c676132007-10-23 18:17:00 +0000816Strings contain Unicode characters. Their literals are written in single or
817double quotes: ``'xyzzy'``, ``"frobozz"``. See :ref:`strings` for more about
818string literals. In addition to the functionality described here, there are
819also string-specific methods described in the :ref:`string-methods` section.
820
Georg Brandl95414632007-11-22 11:00:28 +0000821Bytes and bytearray objects contain single bytes -- the former is immutable
Georg Brandl18da8f02008-07-01 20:08:02 +0000822while the latter is a mutable sequence. Bytes objects can be constructed the
823constructor, :func:`bytes`, and from literals; use a ``b`` prefix with normal
824string syntax: ``b'xyzzy'``. To construct byte arrays, use the
825:func:`bytearray` function.
Georg Brandl4b491312007-08-31 09:22:56 +0000826
Raymond Hettingerf4477702010-11-04 02:39:07 +0000827While string objects are sequences of characters (represented by strings of
828length 1), bytes and bytearray objects are sequences of *integers* (between 0
829and 255), representing the ASCII value of single bytes. That means that for
830a bytes or bytearray object *b*, ``b[0]`` will be an integer, while
831``b[0:1]`` will be a bytes or bytearray object of length 1. The
832representation of bytes objects uses the literal format (``b'...'``) since it
833is generally more useful than e.g. ``bytes([50, 19, 100])``. You can always
834convert a bytes object into a list of integers using ``list(b)``.
Georg Brandl4b491312007-08-31 09:22:56 +0000835
Raymond Hettingerf4477702010-11-04 02:39:07 +0000836Also, while in previous Python versions, byte strings and Unicode strings
837could be exchanged for each other rather freely (barring encoding issues),
838strings and bytes are now completely separate concepts. There's no implicit
839en-/decoding if you pass an object of the wrong type. A string always
840compares unequal to a bytes or bytearray object.
Georg Brandl2326a792007-09-01 12:08:51 +0000841
Georg Brandl4b491312007-08-31 09:22:56 +0000842Lists are constructed with square brackets, separating items with commas: ``[a,
843b, c]``. Tuples are constructed by the comma operator (not within square
844brackets), with or without enclosing parentheses, but an empty tuple must have
845the enclosing parentheses, such as ``a, b, c`` or ``()``. A single item tuple
846must have a trailing comma, such as ``(d,)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000847
Georg Brandl95414632007-11-22 11:00:28 +0000848Objects of type range are created using the :func:`range` function. They don't
Daniel Stutzbach2a1e3e62010-12-17 20:53:03 +0000849support concatenation or repetition, and using :func:`min` or :func:`max` on
850them is inefficient.
Georg Brandl116aa622007-08-15 14:28:22 +0000851
852Most sequence types support the following operations. The ``in`` and ``not in``
853operations have the same priorities as the comparison operations. The ``+`` and
854``*`` operations have the same priority as the corresponding numeric operations.
Ezio Melotti0656a562011-08-15 14:27:19 +0300855[3]_ Additional methods are provided for :ref:`typesseq-mutable`.
Georg Brandl116aa622007-08-15 14:28:22 +0000856
857This table lists the sequence operations sorted in ascending priority
858(operations in the same box have the same priority). In the table, *s* and *t*
Raymond Hettinger2a07d6e2010-11-21 23:51:45 +0000859are sequences of the same type; *n*, *i*, *j* and *k* are integers.
Georg Brandl116aa622007-08-15 14:28:22 +0000860
861+------------------+--------------------------------+----------+
862| Operation | Result | Notes |
863+==================+================================+==========+
864| ``x in s`` | ``True`` if an item of *s* is | \(1) |
865| | equal to *x*, else ``False`` | |
866+------------------+--------------------------------+----------+
867| ``x not in s`` | ``False`` if an item of *s* is | \(1) |
868| | equal to *x*, else ``True`` | |
869+------------------+--------------------------------+----------+
870| ``s + t`` | the concatenation of *s* and | \(6) |
871| | *t* | |
872+------------------+--------------------------------+----------+
873| ``s * n, n * s`` | *n* shallow copies of *s* | \(2) |
874| | concatenated | |
875+------------------+--------------------------------+----------+
Georg Brandl3b65fd72012-01-23 20:19:33 +0100876| ``s[i]`` | *i*\ th item of *s*, origin 0 | \(3) |
Georg Brandl116aa622007-08-15 14:28:22 +0000877+------------------+--------------------------------+----------+
Christian Heimes043d6f62008-01-07 17:19:16 +0000878| ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) |
Georg Brandl116aa622007-08-15 14:28:22 +0000879+------------------+--------------------------------+----------+
Christian Heimes043d6f62008-01-07 17:19:16 +0000880| ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) |
Georg Brandl116aa622007-08-15 14:28:22 +0000881| | with step *k* | |
882+------------------+--------------------------------+----------+
883| ``len(s)`` | length of *s* | |
884+------------------+--------------------------------+----------+
885| ``min(s)`` | smallest item of *s* | |
886+------------------+--------------------------------+----------+
887| ``max(s)`` | largest item of *s* | |
888+------------------+--------------------------------+----------+
Éric Araujo0f441792010-11-20 23:56:22 +0000889| ``s.index(i)`` | index of the first occurence | |
890| | of *i* in *s* | |
891+------------------+--------------------------------+----------+
892| ``s.count(i)`` | total number of occurences of | |
893| | *i* in *s* | |
894+------------------+--------------------------------+----------+
Georg Brandl116aa622007-08-15 14:28:22 +0000895
Georg Brandl7c676132007-10-23 18:17:00 +0000896Sequence types also support comparisons. In particular, tuples and lists are
897compared lexicographically by comparing corresponding elements. This means that
Georg Brandl4b491312007-08-31 09:22:56 +0000898to compare equal, every element must compare equal and the two sequences must be
Georg Brandl7c676132007-10-23 18:17:00 +0000899of the same type and have the same length. (For full details see
Georg Brandl4b491312007-08-31 09:22:56 +0000900:ref:`comparisons` in the language reference.)
Georg Brandl116aa622007-08-15 14:28:22 +0000901
902.. index::
903 triple: operations on; sequence; types
904 builtin: len
905 builtin: min
906 builtin: max
907 pair: concatenation; operation
908 pair: repetition; operation
909 pair: subscript; operation
910 pair: slice; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000911 operator: in
912 operator: not in
913
914Notes:
915
916(1)
Georg Brandl4b491312007-08-31 09:22:56 +0000917 When *s* is a string object, the ``in`` and ``not in`` operations act like a
918 substring test.
Georg Brandl116aa622007-08-15 14:28:22 +0000919
920(2)
921 Values of *n* less than ``0`` are treated as ``0`` (which yields an empty
922 sequence of the same type as *s*). Note also that the copies are shallow;
923 nested structures are not copied. This often haunts new Python programmers;
Christian Heimesfe337bf2008-03-23 21:54:12 +0000924 consider:
Georg Brandl116aa622007-08-15 14:28:22 +0000925
926 >>> lists = [[]] * 3
927 >>> lists
928 [[], [], []]
929 >>> lists[0].append(3)
930 >>> lists
931 [[3], [3], [3]]
932
933 What has happened is that ``[[]]`` is a one-element list containing an empty
Christian Heimesfe337bf2008-03-23 21:54:12 +0000934 list, so all three elements of ``[[]] * 3`` are (pointers to) this single empty
935 list. Modifying any of the elements of ``lists`` modifies this single list.
936 You can create a list of different lists this way:
Georg Brandl116aa622007-08-15 14:28:22 +0000937
938 >>> lists = [[] for i in range(3)]
939 >>> lists[0].append(3)
940 >>> lists[1].append(5)
941 >>> lists[2].append(7)
942 >>> lists
943 [[3], [5], [7]]
944
945(3)
946 If *i* or *j* is negative, the index is relative to the end of the string:
Georg Brandl7c676132007-10-23 18:17:00 +0000947 ``len(s) + i`` or ``len(s) + j`` is substituted. But note that ``-0`` is
948 still ``0``.
Georg Brandl116aa622007-08-15 14:28:22 +0000949
950(4)
951 The slice of *s* from *i* to *j* is defined as the sequence of items with index
952 *k* such that ``i <= k < j``. If *i* or *j* is greater than ``len(s)``, use
953 ``len(s)``. If *i* is omitted or ``None``, use ``0``. If *j* is omitted or
954 ``None``, use ``len(s)``. If *i* is greater than or equal to *j*, the slice is
955 empty.
956
957(5)
958 The slice of *s* from *i* to *j* with step *k* is defined as the sequence of
Christian Heimes2c181612007-12-17 20:04:13 +0000959 items with index ``x = i + n*k`` such that ``0 <= n < (j-i)/k``. In other words,
Georg Brandl116aa622007-08-15 14:28:22 +0000960 the indices are ``i``, ``i+k``, ``i+2*k``, ``i+3*k`` and so on, stopping when
961 *j* is reached (but never including *j*). If *i* or *j* is greater than
962 ``len(s)``, use ``len(s)``. If *i* or *j* are omitted or ``None``, they become
963 "end" values (which end depends on the sign of *k*). Note, *k* cannot be zero.
964 If *k* is ``None``, it is treated like ``1``.
965
966(6)
Antoine Pitroufd9ebd42011-11-25 16:33:53 +0100967 Concatenating immutable strings always results in a new object. This means
968 that building up a string by repeated concatenation will have a quadratic
969 runtime cost in the total string length. To get a linear runtime cost,
970 you must switch to one of the alternatives below:
Georg Brandl495f7b52009-10-27 15:28:25 +0000971
Antoine Pitroufd9ebd42011-11-25 16:33:53 +0100972 * if concatenating :class:`str` objects, you can build a list and use
973 :meth:`str.join` at the end;
974
975 * if concatenating :class:`bytes` objects, you can similarly use
976 :meth:`bytes.join`, or you can do in-place concatenation with a
977 :class:`bytearray` object. :class:`bytearray` objects are mutable and
978 have an efficient overallocation mechanism.
Georg Brandl116aa622007-08-15 14:28:22 +0000979
Georg Brandl116aa622007-08-15 14:28:22 +0000980
981.. _string-methods:
982
983String Methods
984--------------
985
986.. index:: pair: string; methods
987
Benjamin Peterson308d6372009-09-18 21:42:35 +0000988String objects support the methods listed below.
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000989
Benjamin Peterson308d6372009-09-18 21:42:35 +0000990In addition, Python's strings support the sequence type methods described in the
991:ref:`typesseq` section. To output formatted strings, see the
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000992:ref:`string-formatting` section. Also, see the :mod:`re` module for string
993functions based on regular expressions.
Georg Brandl116aa622007-08-15 14:28:22 +0000994
995.. method:: str.capitalize()
996
Senthil Kumaranfa897982010-07-05 11:41:42 +0000997 Return a copy of the string with its first character capitalized and the
Senthil Kumaran37c63a32010-07-06 02:08:36 +0000998 rest lowercased.
Georg Brandl116aa622007-08-15 14:28:22 +0000999
Georg Brandl116aa622007-08-15 14:28:22 +00001000
1001.. method:: str.center(width[, fillchar])
1002
1003 Return centered in a string of length *width*. Padding is done using the
1004 specified *fillchar* (default is a space).
1005
Georg Brandl116aa622007-08-15 14:28:22 +00001006
1007.. method:: str.count(sub[, start[, end]])
1008
Benjamin Petersonad3d5c22009-02-26 03:38:59 +00001009 Return the number of non-overlapping occurrences of substring *sub* in the
1010 range [*start*, *end*]. Optional arguments *start* and *end* are
1011 interpreted as in slice notation.
Georg Brandl116aa622007-08-15 14:28:22 +00001012
1013
Victor Stinnere14e2122010-11-07 18:41:46 +00001014.. method:: str.encode(encoding="utf-8", errors="strict")
Georg Brandl116aa622007-08-15 14:28:22 +00001015
Victor Stinnere14e2122010-11-07 18:41:46 +00001016 Return an encoded version of the string as a bytes object. Default encoding
1017 is ``'utf-8'``. *errors* may be given to set a different error handling scheme.
1018 The default for *errors* is ``'strict'``, meaning that encoding errors raise
1019 a :exc:`UnicodeError`. Other possible
Georg Brandl4f5f98d2009-05-04 21:01:20 +00001020 values are ``'ignore'``, ``'replace'``, ``'xmlcharrefreplace'``,
1021 ``'backslashreplace'`` and any other name registered via
1022 :func:`codecs.register_error`, see section :ref:`codec-base-classes`. For a
1023 list of possible encodings, see section :ref:`standard-encodings`.
Georg Brandl116aa622007-08-15 14:28:22 +00001024
Benjamin Peterson308d6372009-09-18 21:42:35 +00001025 .. versionchanged:: 3.1
Georg Brandl67b21b72010-08-17 15:07:14 +00001026 Support for keyword arguments added.
1027
Georg Brandl116aa622007-08-15 14:28:22 +00001028
1029.. method:: str.endswith(suffix[, start[, end]])
1030
1031 Return ``True`` if the string ends with the specified *suffix*, otherwise return
1032 ``False``. *suffix* can also be a tuple of suffixes to look for. With optional
1033 *start*, test beginning at that position. With optional *end*, stop comparing
1034 at that position.
1035
Georg Brandl116aa622007-08-15 14:28:22 +00001036
1037.. method:: str.expandtabs([tabsize])
1038
Eli Benderskyc2c89602011-11-11 10:40:14 +02001039 Return a copy of the string where all tab characters are replaced by zero or
Georg Brandl9afde1c2007-11-01 20:32:30 +00001040 more spaces, depending on the current column and the given tab size. The
1041 column number is reset to zero after each newline occurring in the string.
1042 If *tabsize* is not given, a tab size of ``8`` characters is assumed. This
1043 doesn't understand other non-printing characters or escape sequences.
Georg Brandl116aa622007-08-15 14:28:22 +00001044
1045
1046.. method:: str.find(sub[, start[, end]])
1047
Benjamin Petersond99cd812010-04-27 22:58:50 +00001048 Return the lowest index in the string where substring *sub* is found, such
1049 that *sub* is contained in the slice ``s[start:end]``. Optional arguments
1050 *start* and *end* are interpreted as in slice notation. Return ``-1`` if
1051 *sub* is not found.
Georg Brandl116aa622007-08-15 14:28:22 +00001052
Ezio Melotti0ed8c682011-05-09 03:54:30 +03001053 .. note::
1054
1055 The :meth:`~str.find` method should be used only if you need to know the
1056 position of *sub*. To check if *sub* is a substring or not, use the
1057 :keyword:`in` operator::
1058
1059 >>> 'Py' in 'Python'
1060 True
1061
Georg Brandl116aa622007-08-15 14:28:22 +00001062
Benjamin Petersonad3d5c22009-02-26 03:38:59 +00001063.. method:: str.format(*args, **kwargs)
Georg Brandl4b491312007-08-31 09:22:56 +00001064
Georg Brandl1f70cdf2010-03-21 09:04:24 +00001065 Perform a string formatting operation. The string on which this method is
1066 called can contain literal text or replacement fields delimited by braces
1067 ``{}``. Each replacement field contains either the numeric index of a
1068 positional argument, or the name of a keyword argument. Returns a copy of
1069 the string where each replacement field is replaced with the string value of
1070 the corresponding argument.
Georg Brandl4b491312007-08-31 09:22:56 +00001071
1072 >>> "The sum of 1 + 2 is {0}".format(1+2)
1073 'The sum of 1 + 2 is 3'
1074
1075 See :ref:`formatstrings` for a description of the various formatting options
1076 that can be specified in format strings.
1077
Georg Brandl4b491312007-08-31 09:22:56 +00001078
Eric Smith27bbca62010-11-04 17:06:58 +00001079.. method:: str.format_map(mapping)
1080
Éric Araujo2642ad02010-11-06 04:59:27 +00001081 Similar to ``str.format(**mapping)``, except that ``mapping`` is
Eric Smith27bbca62010-11-04 17:06:58 +00001082 used directly and not copied to a :class:`dict` . This is useful
Eric Smith5ad85f82010-11-06 13:22:13 +00001083 if for example ``mapping`` is a dict subclass:
Eric Smith27bbca62010-11-04 17:06:58 +00001084
Eric Smith5ad85f82010-11-06 13:22:13 +00001085 >>> class Default(dict):
1086 ... def __missing__(self, key):
1087 ... return key
1088 ...
1089 >>> '{name} was born in {country}'.format_map(Default(name='Guido'))
1090 'Guido was born in country'
1091
1092 .. versionadded:: 3.2
1093
Eric Smith27bbca62010-11-04 17:06:58 +00001094
Georg Brandl116aa622007-08-15 14:28:22 +00001095.. method:: str.index(sub[, start[, end]])
1096
1097 Like :meth:`find`, but raise :exc:`ValueError` when the substring is not found.
1098
1099
1100.. method:: str.isalnum()
1101
1102 Return true if all characters in the string are alphanumeric and there is at
Alexander Belopolsky0d267982010-12-23 02:58:25 +00001103 least one character, false otherwise. A character ``c`` is alphanumeric if one
1104 of the following returns ``True``: ``c.isalpha()``, ``c.isdecimal()``,
1105 ``c.isdigit()``, or ``c.isnumeric()``.
Georg Brandl116aa622007-08-15 14:28:22 +00001106
Georg Brandl116aa622007-08-15 14:28:22 +00001107
1108.. method:: str.isalpha()
1109
1110 Return true if all characters in the string are alphabetic and there is at least
Alexander Belopolsky0d267982010-12-23 02:58:25 +00001111 one character, false otherwise. Alphabetic characters are those characters defined
1112 in the Unicode character database as "Letter", i.e., those with general category
1113 property being one of "Lm", "Lt", "Lu", "Ll", or "Lo". Note that this is different
1114 from the "Alphabetic" property defined in the Unicode Standard.
Georg Brandl116aa622007-08-15 14:28:22 +00001115
Georg Brandl116aa622007-08-15 14:28:22 +00001116
Mark Summerfieldbbfd71d2008-07-01 15:50:04 +00001117.. method:: str.isdecimal()
1118
1119 Return true if all characters in the string are decimal
1120 characters and there is at least one character, false
Alexander Belopolsky0d267982010-12-23 02:58:25 +00001121 otherwise. Decimal characters are those from general category "Nd". This category
1122 includes digit characters, and all characters
Ezio Melottie130a522011-10-19 10:58:56 +03001123 that can be used to form decimal-radix numbers, e.g. U+0660,
Mark Summerfieldbbfd71d2008-07-01 15:50:04 +00001124 ARABIC-INDIC DIGIT ZERO.
Georg Brandl48310cd2009-01-03 21:18:54 +00001125
Mark Summerfieldbbfd71d2008-07-01 15:50:04 +00001126
Georg Brandl116aa622007-08-15 14:28:22 +00001127.. method:: str.isdigit()
1128
1129 Return true if all characters in the string are digits and there is at least one
Alexander Belopolsky0d267982010-12-23 02:58:25 +00001130 character, false otherwise. Digits include decimal characters and digits that need
1131 special handling, such as the compatibility superscript digits. Formally, a digit
1132 is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.
Georg Brandl116aa622007-08-15 14:28:22 +00001133
Georg Brandl116aa622007-08-15 14:28:22 +00001134
1135.. method:: str.isidentifier()
1136
1137 Return true if the string is a valid identifier according to the language
Georg Brandl4b491312007-08-31 09:22:56 +00001138 definition, section :ref:`identifiers`.
Georg Brandl116aa622007-08-15 14:28:22 +00001139
1140
1141.. method:: str.islower()
1142
Ezio Melotti0656a562011-08-15 14:27:19 +03001143 Return true if all cased characters [4]_ in the string are lowercase and
1144 there is at least one cased character, false otherwise.
Georg Brandl116aa622007-08-15 14:28:22 +00001145
Georg Brandl116aa622007-08-15 14:28:22 +00001146
Mark Summerfieldbbfd71d2008-07-01 15:50:04 +00001147.. method:: str.isnumeric()
1148
1149 Return true if all characters in the string are numeric
1150 characters, and there is at least one character, false
1151 otherwise. Numeric characters include digit characters, and all characters
1152 that have the Unicode numeric value property, e.g. U+2155,
Alexander Belopolsky0d267982010-12-23 02:58:25 +00001153 VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property
1154 value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.
Mark Summerfieldbbfd71d2008-07-01 15:50:04 +00001155
Georg Brandl48310cd2009-01-03 21:18:54 +00001156
Georg Brandl559e5d72008-06-11 18:37:52 +00001157.. method:: str.isprintable()
1158
1159 Return true if all characters in the string are printable or the string is
1160 empty, false otherwise. Nonprintable characters are those characters defined
1161 in the Unicode character database as "Other" or "Separator", excepting the
1162 ASCII space (0x20) which is considered printable. (Note that printable
1163 characters in this context are those which should not be escaped when
1164 :func:`repr` is invoked on a string. It has no bearing on the handling of
1165 strings written to :data:`sys.stdout` or :data:`sys.stderr`.)
1166
1167
Georg Brandl116aa622007-08-15 14:28:22 +00001168.. method:: str.isspace()
1169
1170 Return true if there are only whitespace characters in the string and there is
Alexander Belopolsky0d267982010-12-23 02:58:25 +00001171 at least one character, false otherwise. Whitespace characters are those
1172 characters defined in the Unicode character database as "Other" or "Separator"
1173 and those with bidirectional property being one of "WS", "B", or "S".
Georg Brandl116aa622007-08-15 14:28:22 +00001174
1175.. method:: str.istitle()
1176
1177 Return true if the string is a titlecased string and there is at least one
1178 character, for example uppercase characters may only follow uncased characters
1179 and lowercase characters only cased ones. Return false otherwise.
1180
Georg Brandl116aa622007-08-15 14:28:22 +00001181
1182.. method:: str.isupper()
1183
Ezio Melotti0656a562011-08-15 14:27:19 +03001184 Return true if all cased characters [4]_ in the string are uppercase and
1185 there is at least one cased character, false otherwise.
Georg Brandl116aa622007-08-15 14:28:22 +00001186
Georg Brandl116aa622007-08-15 14:28:22 +00001187
Georg Brandl495f7b52009-10-27 15:28:25 +00001188.. method:: str.join(iterable)
Georg Brandl116aa622007-08-15 14:28:22 +00001189
Georg Brandl495f7b52009-10-27 15:28:25 +00001190 Return a string which is the concatenation of the strings in the
1191 :term:`iterable` *iterable*. A :exc:`TypeError` will be raised if there are
Terry Jan Reedyf4ec3c52012-01-11 03:29:42 -05001192 any non-string values in *iterable*, including :class:`bytes` objects. The
Georg Brandl495f7b52009-10-27 15:28:25 +00001193 separator between elements is the string providing this method.
Georg Brandl116aa622007-08-15 14:28:22 +00001194
1195
1196.. method:: str.ljust(width[, fillchar])
1197
1198 Return the string left justified in a string of length *width*. Padding is done
1199 using the specified *fillchar* (default is a space). The original string is
Terry Jan Reedyf4ec3c52012-01-11 03:29:42 -05001200 returned if *width* is less than or equal to ``len(s)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001201
Georg Brandl116aa622007-08-15 14:28:22 +00001202
1203.. method:: str.lower()
1204
Ezio Melotti0656a562011-08-15 14:27:19 +03001205 Return a copy of the string with all the cased characters [4]_ converted to
1206 lowercase.
Georg Brandl116aa622007-08-15 14:28:22 +00001207
Georg Brandl116aa622007-08-15 14:28:22 +00001208
1209.. method:: str.lstrip([chars])
1210
1211 Return a copy of the string with leading characters removed. The *chars*
1212 argument is a string specifying the set of characters to be removed. If omitted
1213 or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
Christian Heimesfe337bf2008-03-23 21:54:12 +00001214 argument is not a prefix; rather, all combinations of its values are stripped:
Georg Brandl116aa622007-08-15 14:28:22 +00001215
1216 >>> ' spacious '.lstrip()
1217 'spacious '
1218 >>> 'www.example.com'.lstrip('cmowz.')
1219 'example.com'
1220
Georg Brandl116aa622007-08-15 14:28:22 +00001221
Georg Brandlabc38772009-04-12 15:51:51 +00001222.. staticmethod:: str.maketrans(x[, y[, z]])
Georg Brandlceee0772007-11-27 23:48:05 +00001223
1224 This static method returns a translation table usable for :meth:`str.translate`.
1225
1226 If there is only one argument, it must be a dictionary mapping Unicode
1227 ordinals (integers) or characters (strings of length 1) to Unicode ordinals,
1228 strings (of arbitrary lengths) or None. Character keys will then be
1229 converted to ordinals.
1230
1231 If there are two arguments, they must be strings of equal length, and in the
1232 resulting dictionary, each character in x will be mapped to the character at
1233 the same position in y. If there is a third argument, it must be a string,
1234 whose characters will be mapped to None in the result.
1235
1236
Georg Brandl116aa622007-08-15 14:28:22 +00001237.. method:: str.partition(sep)
1238
1239 Split the string at the first occurrence of *sep*, and return a 3-tuple
1240 containing the part before the separator, the separator itself, and the part
1241 after the separator. If the separator is not found, return a 3-tuple containing
1242 the string itself, followed by two empty strings.
1243
Georg Brandl116aa622007-08-15 14:28:22 +00001244
1245.. method:: str.replace(old, new[, count])
1246
1247 Return a copy of the string with all occurrences of substring *old* replaced by
1248 *new*. If the optional argument *count* is given, only the first *count*
1249 occurrences are replaced.
1250
1251
Georg Brandl226878c2007-08-31 10:15:37 +00001252.. method:: str.rfind(sub[, start[, end]])
Georg Brandl116aa622007-08-15 14:28:22 +00001253
Benjamin Petersond99cd812010-04-27 22:58:50 +00001254 Return the highest index in the string where substring *sub* is found, such
1255 that *sub* is contained within ``s[start:end]``. Optional arguments *start*
1256 and *end* are interpreted as in slice notation. Return ``-1`` on failure.
Georg Brandl116aa622007-08-15 14:28:22 +00001257
1258
1259.. method:: str.rindex(sub[, start[, end]])
1260
1261 Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not
1262 found.
1263
1264
1265.. method:: str.rjust(width[, fillchar])
1266
1267 Return the string right justified in a string of length *width*. Padding is done
1268 using the specified *fillchar* (default is a space). The original string is
Terry Jan Reedyf4ec3c52012-01-11 03:29:42 -05001269 returned if *width* is less than or equal to ``len(s)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001270
Georg Brandl116aa622007-08-15 14:28:22 +00001271
1272.. method:: str.rpartition(sep)
1273
1274 Split the string at the last occurrence of *sep*, and return a 3-tuple
1275 containing the part before the separator, the separator itself, and the part
1276 after the separator. If the separator is not found, return a 3-tuple containing
1277 two empty strings, followed by the string itself.
1278
Georg Brandl116aa622007-08-15 14:28:22 +00001279
Georg Brandl226878c2007-08-31 10:15:37 +00001280.. method:: str.rsplit([sep[, maxsplit]])
Georg Brandl116aa622007-08-15 14:28:22 +00001281
1282 Return a list of the words in the string, using *sep* as the delimiter string.
1283 If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost*
1284 ones. If *sep* is not specified or ``None``, any whitespace string is a
1285 separator. Except for splitting from the right, :meth:`rsplit` behaves like
1286 :meth:`split` which is described in detail below.
1287
Georg Brandl116aa622007-08-15 14:28:22 +00001288
1289.. method:: str.rstrip([chars])
1290
1291 Return a copy of the string with trailing characters removed. The *chars*
1292 argument is a string specifying the set of characters to be removed. If omitted
1293 or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
Christian Heimesfe337bf2008-03-23 21:54:12 +00001294 argument is not a suffix; rather, all combinations of its values are stripped:
Georg Brandl116aa622007-08-15 14:28:22 +00001295
1296 >>> ' spacious '.rstrip()
1297 ' spacious'
1298 >>> 'mississippi'.rstrip('ipz')
1299 'mississ'
1300
Georg Brandl116aa622007-08-15 14:28:22 +00001301
Georg Brandl226878c2007-08-31 10:15:37 +00001302.. method:: str.split([sep[, maxsplit]])
Georg Brandl116aa622007-08-15 14:28:22 +00001303
Georg Brandl226878c2007-08-31 10:15:37 +00001304 Return a list of the words in the string, using *sep* as the delimiter
1305 string. If *maxsplit* is given, at most *maxsplit* splits are done (thus,
1306 the list will have at most ``maxsplit+1`` elements). If *maxsplit* is not
1307 specified, then there is no limit on the number of splits (all possible
Georg Brandl9afde1c2007-11-01 20:32:30 +00001308 splits are made).
1309
Guido van Rossum2cc30da2007-11-02 23:46:40 +00001310 If *sep* is given, consecutive delimiters are not grouped together and are
Georg Brandl226878c2007-08-31 10:15:37 +00001311 deemed to delimit empty strings (for example, ``'1,,2'.split(',')`` returns
1312 ``['1', '', '2']``). The *sep* argument may consist of multiple characters
Georg Brandl9afde1c2007-11-01 20:32:30 +00001313 (for example, ``'1<>2<>3'.split('<>')`` returns ``['1', '2', '3']``).
Georg Brandl226878c2007-08-31 10:15:37 +00001314 Splitting an empty string with a specified separator returns ``['']``.
Georg Brandl116aa622007-08-15 14:28:22 +00001315
1316 If *sep* is not specified or is ``None``, a different splitting algorithm is
Georg Brandl9afde1c2007-11-01 20:32:30 +00001317 applied: runs of consecutive whitespace are regarded as a single separator,
1318 and the result will contain no empty strings at the start or end if the
1319 string has leading or trailing whitespace. Consequently, splitting an empty
1320 string or a string consisting of just whitespace with a ``None`` separator
1321 returns ``[]``.
1322
1323 For example, ``' 1 2 3 '.split()`` returns ``['1', '2', '3']``, and
1324 ``' 1 2 3 '.split(None, 1)`` returns ``['1', '2 3 ']``.
Georg Brandl116aa622007-08-15 14:28:22 +00001325
1326
1327.. method:: str.splitlines([keepends])
1328
1329 Return a list of the lines in the string, breaking at line boundaries. Line
1330 breaks are not included in the resulting list unless *keepends* is given and
1331 true.
1332
1333
1334.. method:: str.startswith(prefix[, start[, end]])
1335
1336 Return ``True`` if string starts with the *prefix*, otherwise return ``False``.
1337 *prefix* can also be a tuple of prefixes to look for. With optional *start*,
1338 test string beginning at that position. With optional *end*, stop comparing
1339 string at that position.
1340
Georg Brandl116aa622007-08-15 14:28:22 +00001341
1342.. method:: str.strip([chars])
1343
1344 Return a copy of the string with the leading and trailing characters removed.
1345 The *chars* argument is a string specifying the set of characters to be removed.
1346 If omitted or ``None``, the *chars* argument defaults to removing whitespace.
1347 The *chars* argument is not a prefix or suffix; rather, all combinations of its
Christian Heimesfe337bf2008-03-23 21:54:12 +00001348 values are stripped:
Georg Brandl116aa622007-08-15 14:28:22 +00001349
1350 >>> ' spacious '.strip()
1351 'spacious'
1352 >>> 'www.example.com'.strip('cmowz.')
1353 'example'
1354
Georg Brandl116aa622007-08-15 14:28:22 +00001355
1356.. method:: str.swapcase()
1357
1358 Return a copy of the string with uppercase characters converted to lowercase and
1359 vice versa.
1360
Georg Brandl116aa622007-08-15 14:28:22 +00001361
1362.. method:: str.title()
1363
Raymond Hettingerb8b0ba12009-09-29 06:22:28 +00001364 Return a titlecased version of the string where words start with an uppercase
1365 character and the remaining characters are lowercase.
1366
1367 The algorithm uses a simple language-independent definition of a word as
1368 groups of consecutive letters. The definition works in many contexts but
1369 it means that apostrophes in contractions and possessives form word
1370 boundaries, which may not be the desired result::
1371
1372 >>> "they're bill's friends from the UK".title()
1373 "They'Re Bill'S Friends From The Uk"
1374
1375 A workaround for apostrophes can be constructed using regular expressions::
1376
1377 >>> import re
1378 >>> def titlecase(s):
1379 return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
1380 lambda mo: mo.group(0)[0].upper() +
1381 mo.group(0)[1:].lower(),
1382 s)
1383
1384 >>> titlecase("they're bill's friends.")
1385 "They're Bill's Friends."
Georg Brandl116aa622007-08-15 14:28:22 +00001386
Georg Brandl116aa622007-08-15 14:28:22 +00001387
Georg Brandl4b491312007-08-31 09:22:56 +00001388.. method:: str.translate(map)
Georg Brandl116aa622007-08-15 14:28:22 +00001389
Georg Brandl226878c2007-08-31 10:15:37 +00001390 Return a copy of the *s* where all characters have been mapped through the
Georg Brandl454636f2008-12-27 23:33:20 +00001391 *map* which must be a dictionary of Unicode ordinals (integers) to Unicode
Georg Brandlceee0772007-11-27 23:48:05 +00001392 ordinals, strings or ``None``. Unmapped characters are left untouched.
1393 Characters mapped to ``None`` are deleted.
1394
Georg Brandl454636f2008-12-27 23:33:20 +00001395 You can use :meth:`str.maketrans` to create a translation map from
1396 character-to-character mappings in different formats.
Christian Heimesfe337bf2008-03-23 21:54:12 +00001397
Georg Brandl4b491312007-08-31 09:22:56 +00001398 .. note::
Georg Brandl116aa622007-08-15 14:28:22 +00001399
Georg Brandlceee0772007-11-27 23:48:05 +00001400 An even more flexible approach is to create a custom character mapping
1401 codec using the :mod:`codecs` module (see :mod:`encodings.cp1251` for an
Georg Brandl4b491312007-08-31 09:22:56 +00001402 example).
Georg Brandl116aa622007-08-15 14:28:22 +00001403
1404
1405.. method:: str.upper()
1406
Ezio Melotti0656a562011-08-15 14:27:19 +03001407 Return a copy of the string with all the cased characters [4]_ converted to
1408 uppercase. Note that ``str.upper().isupper()`` might be ``False`` if ``s``
1409 contains uncased characters or if the Unicode category of the resulting
1410 character(s) is not "Lu" (Letter, uppercase), but e.g. "Lt" (Letter, titlecase).
Georg Brandl116aa622007-08-15 14:28:22 +00001411
Georg Brandl116aa622007-08-15 14:28:22 +00001412
1413.. method:: str.zfill(width)
1414
Georg Brandl9afde1c2007-11-01 20:32:30 +00001415 Return the numeric string left filled with zeros in a string of length
1416 *width*. A sign prefix is handled correctly. The original string is
Terry Jan Reedyf4ec3c52012-01-11 03:29:42 -05001417 returned if *width* is less than or equal to ``len(s)``.
Christian Heimesb186d002008-03-18 15:15:01 +00001418
1419
Georg Brandl116aa622007-08-15 14:28:22 +00001420
Georg Brandl4b491312007-08-31 09:22:56 +00001421.. _old-string-formatting:
Georg Brandl116aa622007-08-15 14:28:22 +00001422
Georg Brandl4b491312007-08-31 09:22:56 +00001423Old String Formatting Operations
1424--------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001425
1426.. index::
1427 single: formatting, string (%)
1428 single: interpolation, string (%)
1429 single: string; formatting
1430 single: string; interpolation
1431 single: printf-style formatting
1432 single: sprintf-style formatting
1433 single: % formatting
1434 single: % interpolation
1435
Georg Brandl81ac1ce2007-08-31 17:17:17 +00001436.. XXX is the note enough?
Georg Brandl4b491312007-08-31 09:22:56 +00001437
1438.. note::
1439
Georg Brandl226878c2007-08-31 10:15:37 +00001440 The formatting operations described here are obsolete and may go away in future
Georg Brandl4b491312007-08-31 09:22:56 +00001441 versions of Python. Use the new :ref:`string-formatting` in new code.
1442
1443String objects have one unique built-in operation: the ``%`` operator (modulo).
1444This is also known as the string *formatting* or *interpolation* operator.
1445Given ``format % values`` (where *format* is a string), ``%`` conversion
1446specifications in *format* are replaced with zero or more elements of *values*.
Georg Brandl60203b42010-10-06 10:11:56 +00001447The effect is similar to the using :c:func:`sprintf` in the C language.
Georg Brandl116aa622007-08-15 14:28:22 +00001448
1449If *format* requires a single argument, *values* may be a single non-tuple
Ezio Melotti0656a562011-08-15 14:27:19 +03001450object. [5]_ Otherwise, *values* must be a tuple with exactly the number of
Georg Brandl116aa622007-08-15 14:28:22 +00001451items specified by the format string, or a single mapping object (for example, a
1452dictionary).
1453
1454A conversion specifier contains two or more characters and has the following
1455components, which must occur in this order:
1456
1457#. The ``'%'`` character, which marks the start of the specifier.
1458
1459#. Mapping key (optional), consisting of a parenthesised sequence of characters
1460 (for example, ``(somename)``).
1461
1462#. Conversion flags (optional), which affect the result of some conversion
1463 types.
1464
1465#. Minimum field width (optional). If specified as an ``'*'`` (asterisk), the
1466 actual width is read from the next element of the tuple in *values*, and the
1467 object to convert comes after the minimum field width and optional precision.
1468
1469#. Precision (optional), given as a ``'.'`` (dot) followed by the precision. If
Eli Benderskyef4902a2011-07-29 09:30:42 +03001470 specified as ``'*'`` (an asterisk), the actual precision is read from the next
Georg Brandl116aa622007-08-15 14:28:22 +00001471 element of the tuple in *values*, and the value to convert comes after the
1472 precision.
1473
1474#. Length modifier (optional).
1475
1476#. Conversion type.
1477
1478When the right argument is a dictionary (or other mapping type), then the
1479formats in the string *must* include a parenthesised mapping key into that
1480dictionary inserted immediately after the ``'%'`` character. The mapping key
Christian Heimesfe337bf2008-03-23 21:54:12 +00001481selects the value to be formatted from the mapping. For example:
Georg Brandl116aa622007-08-15 14:28:22 +00001482
Georg Brandledc9e7f2010-10-17 09:19:03 +00001483 >>> print('%(language)s has %(number)03d quote types.' %
1484 ... {'language': "Python", "number": 2})
Georg Brandl116aa622007-08-15 14:28:22 +00001485 Python has 002 quote types.
1486
1487In this case no ``*`` specifiers may occur in a format (since they require a
1488sequential parameter list).
1489
1490The conversion flag characters are:
1491
1492+---------+---------------------------------------------------------------------+
1493| Flag | Meaning |
1494+=========+=====================================================================+
1495| ``'#'`` | The value conversion will use the "alternate form" (where defined |
1496| | below). |
1497+---------+---------------------------------------------------------------------+
1498| ``'0'`` | The conversion will be zero padded for numeric values. |
1499+---------+---------------------------------------------------------------------+
1500| ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` |
1501| | conversion if both are given). |
1502+---------+---------------------------------------------------------------------+
1503| ``' '`` | (a space) A blank should be left before a positive number (or empty |
1504| | string) produced by a signed conversion. |
1505+---------+---------------------------------------------------------------------+
1506| ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion |
1507| | (overrides a "space" flag). |
1508+---------+---------------------------------------------------------------------+
1509
1510A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001511is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``.
Georg Brandl116aa622007-08-15 14:28:22 +00001512
1513The conversion types are:
1514
1515+------------+-----------------------------------------------------+-------+
1516| Conversion | Meaning | Notes |
1517+============+=====================================================+=======+
1518| ``'d'`` | Signed integer decimal. | |
1519+------------+-----------------------------------------------------+-------+
1520| ``'i'`` | Signed integer decimal. | |
1521+------------+-----------------------------------------------------+-------+
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001522| ``'o'`` | Signed octal value. | \(1) |
Georg Brandl116aa622007-08-15 14:28:22 +00001523+------------+-----------------------------------------------------+-------+
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001524| ``'u'`` | Obsolete type -- it is identical to ``'d'``. | \(7) |
Georg Brandl116aa622007-08-15 14:28:22 +00001525+------------+-----------------------------------------------------+-------+
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001526| ``'x'`` | Signed hexadecimal (lowercase). | \(2) |
Georg Brandl116aa622007-08-15 14:28:22 +00001527+------------+-----------------------------------------------------+-------+
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001528| ``'X'`` | Signed hexadecimal (uppercase). | \(2) |
Georg Brandl116aa622007-08-15 14:28:22 +00001529+------------+-----------------------------------------------------+-------+
1530| ``'e'`` | Floating point exponential format (lowercase). | \(3) |
1531+------------+-----------------------------------------------------+-------+
1532| ``'E'`` | Floating point exponential format (uppercase). | \(3) |
1533+------------+-----------------------------------------------------+-------+
Eric Smith22b85b32008-07-17 19:18:29 +00001534| ``'f'`` | Floating point decimal format. | \(3) |
Georg Brandl116aa622007-08-15 14:28:22 +00001535+------------+-----------------------------------------------------+-------+
Eric Smith22b85b32008-07-17 19:18:29 +00001536| ``'F'`` | Floating point decimal format. | \(3) |
Georg Brandl116aa622007-08-15 14:28:22 +00001537+------------+-----------------------------------------------------+-------+
Christian Heimes8dc226f2008-05-06 23:45:46 +00001538| ``'g'`` | Floating point format. Uses lowercase exponential | \(4) |
1539| | format if exponent is less than -4 or not less than | |
1540| | precision, decimal format otherwise. | |
Georg Brandl116aa622007-08-15 14:28:22 +00001541+------------+-----------------------------------------------------+-------+
Christian Heimes8dc226f2008-05-06 23:45:46 +00001542| ``'G'`` | Floating point format. Uses uppercase exponential | \(4) |
1543| | format if exponent is less than -4 or not less than | |
1544| | precision, decimal format otherwise. | |
Georg Brandl116aa622007-08-15 14:28:22 +00001545+------------+-----------------------------------------------------+-------+
1546| ``'c'`` | Single character (accepts integer or single | |
1547| | character string). | |
1548+------------+-----------------------------------------------------+-------+
Ezio Melotti0639d5a2009-12-19 23:26:38 +00001549| ``'r'`` | String (converts any Python object using | \(5) |
Georg Brandl116aa622007-08-15 14:28:22 +00001550| | :func:`repr`). | |
1551+------------+-----------------------------------------------------+-------+
Eli Benderskyef4902a2011-07-29 09:30:42 +03001552| ``'s'`` | String (converts any Python object using | \(5) |
Georg Brandl116aa622007-08-15 14:28:22 +00001553| | :func:`str`). | |
1554+------------+-----------------------------------------------------+-------+
Eli Benderskyef4902a2011-07-29 09:30:42 +03001555| ``'a'`` | String (converts any Python object using | \(5) |
1556| | :func:`ascii`). | |
1557+------------+-----------------------------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +00001558| ``'%'`` | No argument is converted, results in a ``'%'`` | |
1559| | character in the result. | |
1560+------------+-----------------------------------------------------+-------+
1561
1562Notes:
1563
1564(1)
1565 The alternate form causes a leading zero (``'0'``) to be inserted between
1566 left-hand padding and the formatting of the number if the leading character
1567 of the result is not already a zero.
1568
1569(2)
1570 The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether
1571 the ``'x'`` or ``'X'`` format was used) to be inserted between left-hand padding
1572 and the formatting of the number if the leading character of the result is not
1573 already a zero.
1574
1575(3)
1576 The alternate form causes the result to always contain a decimal point, even if
1577 no digits follow it.
1578
1579 The precision determines the number of digits after the decimal point and
1580 defaults to 6.
1581
1582(4)
1583 The alternate form causes the result to always contain a decimal point, and
1584 trailing zeroes are not removed as they would otherwise be.
1585
1586 The precision determines the number of significant digits before and after the
1587 decimal point and defaults to 6.
1588
1589(5)
Eli Benderskyef4902a2011-07-29 09:30:42 +03001590 If precision is ``N``, the output is truncated to ``N`` characters.
Georg Brandl116aa622007-08-15 14:28:22 +00001591
Georg Brandl116aa622007-08-15 14:28:22 +00001592
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001593(7)
1594 See :pep:`237`.
1595
Georg Brandl116aa622007-08-15 14:28:22 +00001596Since Python strings have an explicit length, ``%s`` conversions do not assume
1597that ``'\0'`` is the end of the string.
1598
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001599.. XXX Examples?
1600
Mark Dickinson33841c32009-05-01 15:37:04 +00001601.. versionchanged:: 3.1
1602 ``%f`` conversions for numbers whose absolute value is over 1e50 are no
1603 longer replaced by ``%g`` conversions.
Georg Brandl116aa622007-08-15 14:28:22 +00001604
1605.. index::
1606 module: string
1607 module: re
1608
1609Additional string operations are defined in standard modules :mod:`string` and
1610:mod:`re`.
1611
1612
1613.. _typesseq-range:
1614
Georg Brandl905ec322007-09-28 13:39:25 +00001615Range Type
1616----------
Georg Brandl116aa622007-08-15 14:28:22 +00001617
1618.. index:: object: range
1619
1620The :class:`range` type is an immutable sequence which is commonly used for
1621looping. The advantage of the :class:`range` type is that an :class:`range`
1622object will always take the same amount of memory, no matter the size of the
Raymond Hettingerfe502ea2010-11-21 00:07:55 +00001623range it represents.
Georg Brandl116aa622007-08-15 14:28:22 +00001624
Raymond Hettingerfe502ea2010-11-21 00:07:55 +00001625Range objects have relatively little behavior: they support indexing, contains,
1626iteration, the :func:`len` function, and the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001627
Daniel Stutzbach9f0cbf12010-09-13 21:16:29 +00001628.. method:: range.count(x)
1629
Raymond Hettingerfe502ea2010-11-21 00:07:55 +00001630 Return the number of *i*'s for which ``s[i] == x``.
Daniel Stutzbach9f0cbf12010-09-13 21:16:29 +00001631
1632 .. versionadded:: 3.2
1633
1634.. method:: range.index(x)
1635
1636 Return the smallest *i* such that ``s[i] == x``. Raises
1637 :exc:`ValueError` when *x* is not in the range.
1638
1639 .. versionadded:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +00001640
1641.. _typesseq-mutable:
1642
1643Mutable Sequence Types
1644----------------------
1645
1646.. index::
1647 triple: mutable; sequence; types
1648 object: list
Georg Brandl95414632007-11-22 11:00:28 +00001649 object: bytearray
Georg Brandl116aa622007-08-15 14:28:22 +00001650
Georg Brandl95414632007-11-22 11:00:28 +00001651List and bytearray objects support additional operations that allow in-place
Georg Brandl226878c2007-08-31 10:15:37 +00001652modification of the object. Other mutable sequence types (when added to the
1653language) should also support these operations. Strings and tuples are
1654immutable sequence types: such objects cannot be modified once created. The
1655following operations are defined on mutable sequence types (where *x* is an
1656arbitrary object).
1657
Georg Brandl95414632007-11-22 11:00:28 +00001658Note that while lists allow their items to be of any type, bytearray object
Georg Brandl226878c2007-08-31 10:15:37 +00001659"items" are all integers in the range 0 <= x < 256.
Georg Brandl116aa622007-08-15 14:28:22 +00001660
Senthil Kumaran7cafd262010-10-02 03:16:04 +00001661.. index::
1662 triple: operations on; sequence; types
1663 triple: operations on; list; type
1664 pair: subscript; assignment
1665 pair: slice; assignment
1666 statement: del
1667 single: append() (sequence method)
1668 single: extend() (sequence method)
1669 single: count() (sequence method)
1670 single: index() (sequence method)
1671 single: insert() (sequence method)
1672 single: pop() (sequence method)
1673 single: remove() (sequence method)
1674 single: reverse() (sequence method)
1675 single: sort() (sequence method)
1676
Georg Brandl116aa622007-08-15 14:28:22 +00001677+------------------------------+--------------------------------+---------------------+
1678| Operation | Result | Notes |
1679+==============================+================================+=====================+
1680| ``s[i] = x`` | item *i* of *s* is replaced by | |
1681| | *x* | |
1682+------------------------------+--------------------------------+---------------------+
1683| ``s[i:j] = t`` | slice of *s* from *i* to *j* | |
1684| | is replaced by the contents of | |
1685| | the iterable *t* | |
1686+------------------------------+--------------------------------+---------------------+
1687| ``del s[i:j]`` | same as ``s[i:j] = []`` | |
1688+------------------------------+--------------------------------+---------------------+
1689| ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` | \(1) |
1690| | are replaced by those of *t* | |
1691+------------------------------+--------------------------------+---------------------+
1692| ``del s[i:j:k]`` | removes the elements of | |
1693| | ``s[i:j:k]`` from the list | |
1694+------------------------------+--------------------------------+---------------------+
Georg Brandl226878c2007-08-31 10:15:37 +00001695| ``s.append(x)`` | same as ``s[len(s):len(s)] = | |
Georg Brandl116aa622007-08-15 14:28:22 +00001696| | [x]`` | |
1697+------------------------------+--------------------------------+---------------------+
Georg Brandl226878c2007-08-31 10:15:37 +00001698| ``s.extend(x)`` | same as ``s[len(s):len(s)] = | \(2) |
Georg Brandl116aa622007-08-15 14:28:22 +00001699| | x`` | |
1700+------------------------------+--------------------------------+---------------------+
1701| ``s.count(x)`` | return number of *i*'s for | |
1702| | which ``s[i] == x`` | |
1703+------------------------------+--------------------------------+---------------------+
Georg Brandl226878c2007-08-31 10:15:37 +00001704| ``s.index(x[, i[, j]])`` | return smallest *k* such that | \(3) |
Georg Brandl116aa622007-08-15 14:28:22 +00001705| | ``s[k] == x`` and ``i <= k < | |
1706| | j`` | |
1707+------------------------------+--------------------------------+---------------------+
Georg Brandl226878c2007-08-31 10:15:37 +00001708| ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | \(4) |
Georg Brandl116aa622007-08-15 14:28:22 +00001709+------------------------------+--------------------------------+---------------------+
Georg Brandl226878c2007-08-31 10:15:37 +00001710| ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | \(5) |
Georg Brandl116aa622007-08-15 14:28:22 +00001711| | return x`` | |
1712+------------------------------+--------------------------------+---------------------+
Georg Brandl226878c2007-08-31 10:15:37 +00001713| ``s.remove(x)`` | same as ``del s[s.index(x)]`` | \(3) |
Georg Brandl116aa622007-08-15 14:28:22 +00001714+------------------------------+--------------------------------+---------------------+
Georg Brandl226878c2007-08-31 10:15:37 +00001715| ``s.reverse()`` | reverses the items of *s* in | \(6) |
Georg Brandl116aa622007-08-15 14:28:22 +00001716| | place | |
1717+------------------------------+--------------------------------+---------------------+
Raymond Hettinger7f732952008-02-14 13:34:38 +00001718| ``s.sort([key[, reverse]])`` | sort the items of *s* in place | (6), (7), (8) |
Georg Brandl116aa622007-08-15 14:28:22 +00001719+------------------------------+--------------------------------+---------------------+
1720
Georg Brandl116aa622007-08-15 14:28:22 +00001721
1722Notes:
1723
1724(1)
Georg Brandl226878c2007-08-31 10:15:37 +00001725 *t* must have the same length as the slice it is replacing.
Georg Brandl116aa622007-08-15 14:28:22 +00001726
1727(2)
Georg Brandl116aa622007-08-15 14:28:22 +00001728 *x* can be any iterable object.
1729
Georg Brandl226878c2007-08-31 10:15:37 +00001730(3)
Georg Brandl116aa622007-08-15 14:28:22 +00001731 Raises :exc:`ValueError` when *x* is not found in *s*. When a negative index is
Georg Brandl226878c2007-08-31 10:15:37 +00001732 passed as the second or third parameter to the :meth:`index` method, the sequence
Georg Brandl116aa622007-08-15 14:28:22 +00001733 length is added, as for slice indices. If it is still negative, it is truncated
1734 to zero, as for slice indices.
1735
Georg Brandl226878c2007-08-31 10:15:37 +00001736(4)
Georg Brandl116aa622007-08-15 14:28:22 +00001737 When a negative index is passed as the first parameter to the :meth:`insert`
Georg Brandl226878c2007-08-31 10:15:37 +00001738 method, the sequence length is added, as for slice indices. If it is still
Georg Brandl116aa622007-08-15 14:28:22 +00001739 negative, it is truncated to zero, as for slice indices.
1740
Georg Brandl226878c2007-08-31 10:15:37 +00001741(5)
1742 The optional argument *i* defaults to ``-1``, so that by default the last
1743 item is removed and returned.
1744
Georg Brandl116aa622007-08-15 14:28:22 +00001745(6)
Georg Brandl226878c2007-08-31 10:15:37 +00001746 The :meth:`sort` and :meth:`reverse` methods modify the sequence in place for
1747 economy of space when sorting or reversing a large sequence. To remind you
1748 that they operate by side effect, they don't return the sorted or reversed
1749 sequence.
Georg Brandl116aa622007-08-15 14:28:22 +00001750
1751(7)
Georg Brandl116aa622007-08-15 14:28:22 +00001752 The :meth:`sort` method takes optional arguments for controlling the
Raymond Hettinger7f732952008-02-14 13:34:38 +00001753 comparisons. Each must be specified as a keyword argument.
Georg Brandl116aa622007-08-15 14:28:22 +00001754
Georg Brandl116aa622007-08-15 14:28:22 +00001755 *key* specifies a function of one argument that is used to extract a comparison
Christian Heimesfaf2f632008-01-06 16:59:19 +00001756 key from each list element: ``key=str.lower``. The default value is ``None``.
Raymond Hettingerc50846a2010-04-05 18:56:31 +00001757 Use :func:`functools.cmp_to_key` to convert an
1758 old-style *cmp* function to a *key* function.
1759
Georg Brandl116aa622007-08-15 14:28:22 +00001760
1761 *reverse* is a boolean value. If set to ``True``, then the list elements are
1762 sorted as if each comparison were reversed.
1763
Raymond Hettinger71161862008-02-14 13:32:18 +00001764 The :meth:`sort` method is guaranteed to be stable. A
Georg Brandl116aa622007-08-15 14:28:22 +00001765 sort is stable if it guarantees not to change the relative order of elements
1766 that compare equal --- this is helpful for sorting in multiple passes (for
1767 example, sort by department, then by salary grade).
1768
Georg Brandl495f7b52009-10-27 15:28:25 +00001769 .. impl-detail::
1770
1771 While a list is being sorted, the effect of attempting to mutate, or even
1772 inspect, the list is undefined. The C implementation of Python makes the
1773 list appear empty for the duration, and raises :exc:`ValueError` if it can
1774 detect that the list has been mutated during a sort.
Georg Brandl116aa622007-08-15 14:28:22 +00001775
Raymond Hettinger7f732952008-02-14 13:34:38 +00001776(8)
1777 :meth:`sort` is not supported by :class:`bytearray` objects.
Georg Brandl116aa622007-08-15 14:28:22 +00001778
Georg Brandl495f7b52009-10-27 15:28:25 +00001779
Georg Brandl226878c2007-08-31 10:15:37 +00001780.. _bytes-methods:
1781
Georg Brandl95414632007-11-22 11:00:28 +00001782Bytes and Byte Array Methods
1783----------------------------
Georg Brandl226878c2007-08-31 10:15:37 +00001784
1785.. index:: pair: bytes; methods
Georg Brandl95414632007-11-22 11:00:28 +00001786 pair: bytearray; methods
Georg Brandl226878c2007-08-31 10:15:37 +00001787
Georg Brandl95414632007-11-22 11:00:28 +00001788Bytes and bytearray objects, being "strings of bytes", have all methods found on
Georg Brandl7c676132007-10-23 18:17:00 +00001789strings, with the exception of :func:`encode`, :func:`format` and
Guido van Rossum98297ee2007-11-06 21:34:58 +00001790:func:`isidentifier`, which do not make sense with these types. For converting
1791the objects to strings, they have a :func:`decode` method.
1792
1793Wherever one of these methods needs to interpret the bytes as characters
1794(e.g. the :func:`is...` methods), the ASCII character set is assumed.
Georg Brandl226878c2007-08-31 10:15:37 +00001795
Georg Brandl7c676132007-10-23 18:17:00 +00001796.. note::
Georg Brandl226878c2007-08-31 10:15:37 +00001797
Georg Brandl95414632007-11-22 11:00:28 +00001798 The methods on bytes and bytearray objects don't accept strings as their
Georg Brandl7c676132007-10-23 18:17:00 +00001799 arguments, just as the methods on strings don't accept bytes as their
1800 arguments. For example, you have to write ::
Georg Brandl226878c2007-08-31 10:15:37 +00001801
Georg Brandl7c676132007-10-23 18:17:00 +00001802 a = "abc"
1803 b = a.replace("a", "f")
1804
1805 and ::
1806
1807 a = b"abc"
1808 b = a.replace(b"a", b"f")
Georg Brandl226878c2007-08-31 10:15:37 +00001809
1810
Victor Stinnere14e2122010-11-07 18:41:46 +00001811.. method:: bytes.decode(encoding="utf-8", errors="strict")
1812 bytearray.decode(encoding="utf-8", errors="strict")
Georg Brandl4f5f98d2009-05-04 21:01:20 +00001813
Victor Stinnere14e2122010-11-07 18:41:46 +00001814 Return a string decoded from the given bytes. Default encoding is
1815 ``'utf-8'``. *errors* may be given to set a different
Georg Brandl4f5f98d2009-05-04 21:01:20 +00001816 error handling scheme. The default for *errors* is ``'strict'``, meaning
1817 that encoding errors raise a :exc:`UnicodeError`. Other possible values are
1818 ``'ignore'``, ``'replace'`` and any other name registered via
1819 :func:`codecs.register_error`, see section :ref:`codec-base-classes`. For a
1820 list of possible encodings, see section :ref:`standard-encodings`.
1821
Benjamin Peterson308d6372009-09-18 21:42:35 +00001822 .. versionchanged:: 3.1
1823 Added support for keyword arguments.
1824
Georg Brandl4f5f98d2009-05-04 21:01:20 +00001825
Georg Brandl95414632007-11-22 11:00:28 +00001826The bytes and bytearray types have an additional class method:
Georg Brandl226878c2007-08-31 10:15:37 +00001827
Georg Brandlabc38772009-04-12 15:51:51 +00001828.. classmethod:: bytes.fromhex(string)
1829 bytearray.fromhex(string)
Georg Brandl226878c2007-08-31 10:15:37 +00001830
Georg Brandl18da8f02008-07-01 20:08:02 +00001831 This :class:`bytes` class method returns a bytes or bytearray object,
1832 decoding the given string object. The string must contain two hexadecimal
1833 digits per byte, spaces are ignored.
Georg Brandl226878c2007-08-31 10:15:37 +00001834
Georg Brandl18da8f02008-07-01 20:08:02 +00001835 >>> bytes.fromhex('f0 f1f2 ')
1836 b'\xf0\xf1\xf2'
Georg Brandl226878c2007-08-31 10:15:37 +00001837
Georg Brandlabc38772009-04-12 15:51:51 +00001838
1839The maketrans and translate methods differ in semantics from the versions
1840available on strings:
Georg Brandl48310cd2009-01-03 21:18:54 +00001841
Georg Brandl454636f2008-12-27 23:33:20 +00001842.. method:: bytes.translate(table[, delete])
Georg Brandl751771b2009-05-31 21:38:37 +00001843 bytearray.translate(table[, delete])
Georg Brandl226878c2007-08-31 10:15:37 +00001844
Georg Brandl454636f2008-12-27 23:33:20 +00001845 Return a copy of the bytes or bytearray object where all bytes occurring in
1846 the optional argument *delete* are removed, and the remaining bytes have been
1847 mapped through the given translation table, which must be a bytes object of
1848 length 256.
Georg Brandl226878c2007-08-31 10:15:37 +00001849
Georg Brandlabc38772009-04-12 15:51:51 +00001850 You can use the :func:`bytes.maketrans` method to create a translation table.
Georg Brandl226878c2007-08-31 10:15:37 +00001851
Georg Brandl454636f2008-12-27 23:33:20 +00001852 Set the *table* argument to ``None`` for translations that only delete
1853 characters::
Georg Brandl226878c2007-08-31 10:15:37 +00001854
Georg Brandl454636f2008-12-27 23:33:20 +00001855 >>> b'read this short text'.translate(None, b'aeiou')
1856 b'rd ths shrt txt'
Georg Brandl226878c2007-08-31 10:15:37 +00001857
1858
Georg Brandlabc38772009-04-12 15:51:51 +00001859.. staticmethod:: bytes.maketrans(from, to)
Georg Brandl751771b2009-05-31 21:38:37 +00001860 bytearray.maketrans(from, to)
Georg Brandlabc38772009-04-12 15:51:51 +00001861
1862 This static method returns a translation table usable for
1863 :meth:`bytes.translate` that will map each character in *from* into the
1864 character at the same position in *to*; *from* and *to* must be bytes objects
1865 and have the same length.
1866
1867 .. versionadded:: 3.1
1868
1869
Georg Brandl116aa622007-08-15 14:28:22 +00001870.. _types-set:
1871
1872Set Types --- :class:`set`, :class:`frozenset`
1873==============================================
1874
1875.. index:: object: set
1876
Guido van Rossum2cc30da2007-11-02 23:46:40 +00001877A :dfn:`set` object is an unordered collection of distinct :term:`hashable` objects.
Georg Brandl116aa622007-08-15 14:28:22 +00001878Common uses include membership testing, removing duplicates from a sequence, and
1879computing mathematical operations such as intersection, union, difference, and
1880symmetric difference.
1881(For other containers see the built in :class:`dict`, :class:`list`,
1882and :class:`tuple` classes, and the :mod:`collections` module.)
1883
Georg Brandl116aa622007-08-15 14:28:22 +00001884Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in
1885set``. Being an unordered collection, sets do not record element position or
1886order of insertion. Accordingly, sets do not support indexing, slicing, or
1887other sequence-like behavior.
1888
Georg Brandl22b34312009-07-26 14:54:51 +00001889There are currently two built-in set types, :class:`set` and :class:`frozenset`.
Georg Brandl116aa622007-08-15 14:28:22 +00001890The :class:`set` type is mutable --- the contents can be changed using methods
1891like :meth:`add` and :meth:`remove`. Since it is mutable, it has no hash value
1892and cannot be used as either a dictionary key or as an element of another set.
Guido van Rossum2cc30da2007-11-02 23:46:40 +00001893The :class:`frozenset` type is immutable and :term:`hashable` --- its contents cannot be
Georg Brandl116aa622007-08-15 14:28:22 +00001894altered after it is created; it can therefore be used as a dictionary key or as
1895an element of another set.
1896
Georg Brandl99cd9572010-03-21 09:10:32 +00001897Non-empty sets (not frozensets) can be created by placing a comma-separated list
Georg Brandl53b95e72010-03-21 11:53:50 +00001898of elements within braces, for example: ``{'jack', 'sjoerd'}``, in addition to the
1899:class:`set` constructor.
Georg Brandl99cd9572010-03-21 09:10:32 +00001900
Georg Brandl116aa622007-08-15 14:28:22 +00001901The constructors for both classes work the same:
1902
1903.. class:: set([iterable])
1904 frozenset([iterable])
1905
1906 Return a new set or frozenset object whose elements are taken from
1907 *iterable*. The elements of a set must be hashable. To represent sets of
1908 sets, the inner sets must be :class:`frozenset` objects. If *iterable* is
1909 not specified, a new empty set is returned.
1910
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001911 Instances of :class:`set` and :class:`frozenset` provide the following
1912 operations:
Georg Brandl116aa622007-08-15 14:28:22 +00001913
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001914 .. describe:: len(s)
Georg Brandl116aa622007-08-15 14:28:22 +00001915
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001916 Return the cardinality of set *s*.
Georg Brandl116aa622007-08-15 14:28:22 +00001917
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001918 .. describe:: x in s
Georg Brandl116aa622007-08-15 14:28:22 +00001919
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001920 Test *x* for membership in *s*.
Georg Brandl116aa622007-08-15 14:28:22 +00001921
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001922 .. describe:: x not in s
Georg Brandl116aa622007-08-15 14:28:22 +00001923
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001924 Test *x* for non-membership in *s*.
Georg Brandl116aa622007-08-15 14:28:22 +00001925
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001926 .. method:: isdisjoint(other)
Guido van Rossum58da9312007-11-10 23:39:45 +00001927
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001928 Return True if the set has no elements in common with *other*. Sets are
Georg Brandl2ee470f2008-07-16 12:55:28 +00001929 disjoint if and only if their intersection is the empty set.
Guido van Rossum58da9312007-11-10 23:39:45 +00001930
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001931 .. method:: issubset(other)
1932 set <= other
Georg Brandl116aa622007-08-15 14:28:22 +00001933
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001934 Test whether every element in the set is in *other*.
Georg Brandl116aa622007-08-15 14:28:22 +00001935
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001936 .. method:: set < other
Georg Brandla6f52782007-09-01 15:49:30 +00001937
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001938 Test whether the set is a true subset of *other*, that is,
1939 ``set <= other and set != other``.
Georg Brandla6f52782007-09-01 15:49:30 +00001940
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001941 .. method:: issuperset(other)
1942 set >= other
Georg Brandl116aa622007-08-15 14:28:22 +00001943
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001944 Test whether every element in *other* is in the set.
Georg Brandl116aa622007-08-15 14:28:22 +00001945
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001946 .. method:: set > other
Georg Brandla6f52782007-09-01 15:49:30 +00001947
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001948 Test whether the set is a true superset of *other*, that is, ``set >=
1949 other and set != other``.
Georg Brandla6f52782007-09-01 15:49:30 +00001950
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001951 .. method:: union(other, ...)
1952 set | other | ...
Georg Brandl116aa622007-08-15 14:28:22 +00001953
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001954 Return a new set with elements from the set and all others.
Georg Brandl116aa622007-08-15 14:28:22 +00001955
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001956 .. method:: intersection(other, ...)
1957 set & other & ...
Georg Brandl116aa622007-08-15 14:28:22 +00001958
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001959 Return a new set with elements common to the set and all others.
Georg Brandl116aa622007-08-15 14:28:22 +00001960
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001961 .. method:: difference(other, ...)
1962 set - other - ...
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001963
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001964 Return a new set with elements in the set that are not in the others.
Georg Brandl116aa622007-08-15 14:28:22 +00001965
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001966 .. method:: symmetric_difference(other)
1967 set ^ other
Georg Brandl116aa622007-08-15 14:28:22 +00001968
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001969 Return a new set with elements in either the set or *other* but not both.
Georg Brandl116aa622007-08-15 14:28:22 +00001970
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001971 .. method:: copy()
Georg Brandl116aa622007-08-15 14:28:22 +00001972
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001973 Return a new set with a shallow copy of *s*.
Georg Brandl116aa622007-08-15 14:28:22 +00001974
1975
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001976 Note, the non-operator versions of :meth:`union`, :meth:`intersection`,
1977 :meth:`difference`, and :meth:`symmetric_difference`, :meth:`issubset`, and
1978 :meth:`issuperset` methods will accept any iterable as an argument. In
1979 contrast, their operator based counterparts require their arguments to be
1980 sets. This precludes error-prone constructions like ``set('abc') & 'cbs'``
1981 in favor of the more readable ``set('abc').intersection('cbs')``.
Georg Brandl116aa622007-08-15 14:28:22 +00001982
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001983 Both :class:`set` and :class:`frozenset` support set to set comparisons. Two
1984 sets are equal if and only if every element of each set is contained in the
1985 other (each is a subset of the other). A set is less than another set if and
1986 only if the first set is a proper subset of the second set (is a subset, but
1987 is not equal). A set is greater than another set if and only if the first set
1988 is a proper superset of the second set (is a superset, but is not equal).
Georg Brandl116aa622007-08-15 14:28:22 +00001989
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001990 Instances of :class:`set` are compared to instances of :class:`frozenset`
1991 based on their members. For example, ``set('abc') == frozenset('abc')``
1992 returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``.
Georg Brandl116aa622007-08-15 14:28:22 +00001993
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001994 The subset and equality comparisons do not generalize to a complete ordering
1995 function. For example, any two disjoint sets are not equal and are not
1996 subsets of each other, so *all* of the following return ``False``: ``a<b``,
Georg Brandl05f5ab72008-09-24 09:11:47 +00001997 ``a==b``, or ``a>b``.
Georg Brandl116aa622007-08-15 14:28:22 +00001998
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001999 Since sets only define partial ordering (subset relationships), the output of
2000 the :meth:`list.sort` method is undefined for lists of sets.
Georg Brandl116aa622007-08-15 14:28:22 +00002001
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002002 Set elements, like dictionary keys, must be :term:`hashable`.
Georg Brandl116aa622007-08-15 14:28:22 +00002003
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002004 Binary operations that mix :class:`set` instances with :class:`frozenset`
2005 return the type of the first operand. For example: ``frozenset('ab') |
2006 set('bc')`` returns an instance of :class:`frozenset`.
Georg Brandl116aa622007-08-15 14:28:22 +00002007
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002008 The following table lists operations available for :class:`set` that do not
2009 apply to immutable instances of :class:`frozenset`:
Georg Brandl116aa622007-08-15 14:28:22 +00002010
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002011 .. method:: update(other, ...)
2012 set |= other | ...
Georg Brandl116aa622007-08-15 14:28:22 +00002013
Georg Brandla6053b42009-09-01 08:11:14 +00002014 Update the set, adding elements from all others.
Georg Brandl116aa622007-08-15 14:28:22 +00002015
Georg Brandlc28e1fa2008-06-10 19:20:26 +00002016 .. method:: intersection_update(other, ...)
2017 set &= other & ...
Georg Brandl116aa622007-08-15 14:28:22 +00002018
Georg Brandla6053b42009-09-01 08:11:14 +00002019 Update the set, keeping only elements found in it and all others.
Georg Brandl116aa622007-08-15 14:28:22 +00002020
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00002021 .. method:: difference_update(other, ...)
2022 set -= other | ...
Georg Brandl116aa622007-08-15 14:28:22 +00002023
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00002024 Update the set, removing elements found in others.
2025
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002026 .. method:: symmetric_difference_update(other)
2027 set ^= other
Georg Brandl116aa622007-08-15 14:28:22 +00002028
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002029 Update the set, keeping only elements found in either set, but not in both.
Georg Brandl116aa622007-08-15 14:28:22 +00002030
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002031 .. method:: add(elem)
Georg Brandl116aa622007-08-15 14:28:22 +00002032
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002033 Add element *elem* to the set.
Georg Brandl116aa622007-08-15 14:28:22 +00002034
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002035 .. method:: remove(elem)
Georg Brandl116aa622007-08-15 14:28:22 +00002036
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002037 Remove element *elem* from the set. Raises :exc:`KeyError` if *elem* is
2038 not contained in the set.
Georg Brandl116aa622007-08-15 14:28:22 +00002039
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002040 .. method:: discard(elem)
Georg Brandl116aa622007-08-15 14:28:22 +00002041
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002042 Remove element *elem* from the set if it is present.
Georg Brandl116aa622007-08-15 14:28:22 +00002043
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002044 .. method:: pop()
Georg Brandl116aa622007-08-15 14:28:22 +00002045
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002046 Remove and return an arbitrary element from the set. Raises
2047 :exc:`KeyError` if the set is empty.
Georg Brandl116aa622007-08-15 14:28:22 +00002048
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002049 .. method:: clear()
Georg Brandl116aa622007-08-15 14:28:22 +00002050
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002051 Remove all elements from the set.
Georg Brandl116aa622007-08-15 14:28:22 +00002052
2053
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002054 Note, the non-operator versions of the :meth:`update`,
2055 :meth:`intersection_update`, :meth:`difference_update`, and
2056 :meth:`symmetric_difference_update` methods will accept any iterable as an
2057 argument.
Georg Brandl116aa622007-08-15 14:28:22 +00002058
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002059 Note, the *elem* argument to the :meth:`__contains__`, :meth:`remove`, and
2060 :meth:`discard` methods may be a set. To support searching for an equivalent
2061 frozenset, the *elem* set is temporarily mutated during the search and then
2062 restored. During the search, the *elem* set should not be read or mutated
2063 since it does not have a meaningful value.
Benjamin Peterson699adb92008-05-08 22:27:58 +00002064
Georg Brandl116aa622007-08-15 14:28:22 +00002065
2066.. _typesmapping:
2067
2068Mapping Types --- :class:`dict`
2069===============================
2070
2071.. index::
2072 object: mapping
2073 object: dictionary
2074 triple: operations on; mapping; types
2075 triple: operations on; dictionary; type
2076 statement: del
2077 builtin: len
2078
Guido van Rossum2cc30da2007-11-02 23:46:40 +00002079A :dfn:`mapping` object maps :term:`hashable` values to arbitrary objects.
2080Mappings are mutable objects. There is currently only one standard mapping
2081type, the :dfn:`dictionary`. (For other containers see the built in
2082:class:`list`, :class:`set`, and :class:`tuple` classes, and the
2083:mod:`collections` module.)
Georg Brandl116aa622007-08-15 14:28:22 +00002084
Guido van Rossum2cc30da2007-11-02 23:46:40 +00002085A dictionary's keys are *almost* arbitrary values. Values that are not
2086:term:`hashable`, that is, values containing lists, dictionaries or other
2087mutable types (that are compared by value rather than by object identity) may
2088not be used as keys. Numeric types used for keys obey the normal rules for
2089numeric comparison: if two numbers compare equal (such as ``1`` and ``1.0``)
2090then they can be used interchangeably to index the same dictionary entry. (Note
2091however, that since computers store floating-point numbers as approximations it
2092is usually unwise to use them as dictionary keys.)
Georg Brandl116aa622007-08-15 14:28:22 +00002093
2094Dictionaries can be created by placing a comma-separated list of ``key: value``
2095pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098:
2096'jack', 4127: 'sjoerd'}``, or by the :class:`dict` constructor.
2097
2098.. class:: dict([arg])
2099
Georg Brandld22a8152007-09-04 17:43:37 +00002100 Return a new dictionary initialized from an optional positional argument or
2101 from a set of keyword arguments. If no arguments are given, return a new
2102 empty dictionary. If the positional argument *arg* is a mapping object,
2103 return a dictionary mapping the same keys to the same values as does the
2104 mapping object. Otherwise the positional argument must be a sequence, a
2105 container that supports iteration, or an iterator object. The elements of
2106 the argument must each also be of one of those kinds, and each must in turn
2107 contain exactly two objects. The first is used as a key in the new
2108 dictionary, and the second as the key's value. If a given key is seen more
2109 than once, the last value associated with it is retained in the new
2110 dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00002111
2112 If keyword arguments are given, the keywords themselves with their associated
Georg Brandld22a8152007-09-04 17:43:37 +00002113 values are added as items to the dictionary. If a key is specified both in
2114 the positional argument and as a keyword argument, the value associated with
2115 the keyword is retained in the dictionary. For example, these all return a
Georg Brandlc16e8f12010-10-17 11:23:56 +00002116 dictionary equal to ``{"one": 1, "two": 2}``:
Georg Brandl116aa622007-08-15 14:28:22 +00002117
Georg Brandlc16e8f12010-10-17 11:23:56 +00002118 * ``dict(one=1, two=2)``
2119 * ``dict({'one': 1, 'two': 2})``
2120 * ``dict(zip(('one', 'two'), (1, 2)))``
2121 * ``dict([['two', 2], ['one', 1]])``
Georg Brandl116aa622007-08-15 14:28:22 +00002122
Georg Brandld22a8152007-09-04 17:43:37 +00002123 The first example only works for keys that are valid Python identifiers; the
2124 others work with any valid keys.
Georg Brandl116aa622007-08-15 14:28:22 +00002125
Georg Brandl116aa622007-08-15 14:28:22 +00002126
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002127 These are the operations that dictionaries support (and therefore, custom
2128 mapping types should support too):
Georg Brandl116aa622007-08-15 14:28:22 +00002129
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002130 .. describe:: len(d)
Georg Brandl116aa622007-08-15 14:28:22 +00002131
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002132 Return the number of items in the dictionary *d*.
Georg Brandl116aa622007-08-15 14:28:22 +00002133
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002134 .. describe:: d[key]
Georg Brandl116aa622007-08-15 14:28:22 +00002135
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002136 Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key* is
2137 not in the map.
Georg Brandl48310cd2009-01-03 21:18:54 +00002138
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002139 If a subclass of dict defines a method :meth:`__missing__`, if the key *key*
2140 is not present, the ``d[key]`` operation calls that method with the key *key*
2141 as argument. The ``d[key]`` operation then returns or raises whatever is
2142 returned or raised by the ``__missing__(key)`` call if the key is not
2143 present. No other operations or methods invoke :meth:`__missing__`. If
2144 :meth:`__missing__` is not defined, :exc:`KeyError` is raised.
Raymond Hettinger5254e972011-01-08 09:35:38 +00002145 :meth:`__missing__` must be a method; it cannot be an instance variable::
2146
2147 >>> class Counter(dict):
2148 ... def __missing__(self, key):
2149 ... return 0
2150 >>> c = Counter()
2151 >>> c['red']
2152 0
2153 >>> c['red'] += 1
2154 >>> c['red']
2155 1
2156
2157 See :class:`collections.Counter` for a complete implementation including
2158 other methods helpful for accumulating and managing tallies.
Georg Brandl116aa622007-08-15 14:28:22 +00002159
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002160 .. describe:: d[key] = value
Georg Brandl116aa622007-08-15 14:28:22 +00002161
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002162 Set ``d[key]`` to *value*.
Georg Brandl116aa622007-08-15 14:28:22 +00002163
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002164 .. describe:: del d[key]
Georg Brandl116aa622007-08-15 14:28:22 +00002165
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002166 Remove ``d[key]`` from *d*. Raises a :exc:`KeyError` if *key* is not in the
2167 map.
Georg Brandl116aa622007-08-15 14:28:22 +00002168
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002169 .. describe:: key in d
Georg Brandl116aa622007-08-15 14:28:22 +00002170
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002171 Return ``True`` if *d* has a key *key*, else ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +00002172
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002173 .. describe:: key not in d
Georg Brandl116aa622007-08-15 14:28:22 +00002174
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002175 Equivalent to ``not key in d``.
Georg Brandl116aa622007-08-15 14:28:22 +00002176
Benjamin Petersond23f8222009-04-05 19:13:16 +00002177 .. describe:: iter(d)
2178
2179 Return an iterator over the keys of the dictionary. This is a shortcut
Georg Brandlede6c2a2010-01-05 10:22:04 +00002180 for ``iter(d.keys())``.
Benjamin Petersond23f8222009-04-05 19:13:16 +00002181
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002182 .. method:: clear()
Georg Brandl116aa622007-08-15 14:28:22 +00002183
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002184 Remove all items from the dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00002185
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002186 .. method:: copy()
Georg Brandl116aa622007-08-15 14:28:22 +00002187
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002188 Return a shallow copy of the dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00002189
Georg Brandlabc38772009-04-12 15:51:51 +00002190 .. classmethod:: fromkeys(seq[, value])
Georg Brandl116aa622007-08-15 14:28:22 +00002191
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002192 Create a new dictionary with keys from *seq* and values set to *value*.
Georg Brandl116aa622007-08-15 14:28:22 +00002193
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002194 :meth:`fromkeys` is a class method that returns a new dictionary. *value*
2195 defaults to ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +00002196
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002197 .. method:: get(key[, default])
Georg Brandl116aa622007-08-15 14:28:22 +00002198
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002199 Return the value for *key* if *key* is in the dictionary, else *default*.
2200 If *default* is not given, it defaults to ``None``, so that this method
2201 never raises a :exc:`KeyError`.
Georg Brandl116aa622007-08-15 14:28:22 +00002202
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002203 .. method:: items()
Georg Brandl116aa622007-08-15 14:28:22 +00002204
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002205 Return a new view of the dictionary's items (``(key, value)`` pairs). See
2206 below for documentation of view objects.
Georg Brandl116aa622007-08-15 14:28:22 +00002207
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002208 .. method:: keys()
Georg Brandl116aa622007-08-15 14:28:22 +00002209
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002210 Return a new view of the dictionary's keys. See below for documentation of
2211 view objects.
Georg Brandl116aa622007-08-15 14:28:22 +00002212
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002213 .. method:: pop(key[, default])
Georg Brandl116aa622007-08-15 14:28:22 +00002214
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002215 If *key* is in the dictionary, remove it and return its value, else return
2216 *default*. If *default* is not given and *key* is not in the dictionary,
2217 a :exc:`KeyError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00002218
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002219 .. method:: popitem()
Georg Brandl116aa622007-08-15 14:28:22 +00002220
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002221 Remove and return an arbitrary ``(key, value)`` pair from the dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00002222
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002223 :meth:`popitem` is useful to destructively iterate over a dictionary, as
2224 often used in set algorithms. If the dictionary is empty, calling
2225 :meth:`popitem` raises a :exc:`KeyError`.
Georg Brandl116aa622007-08-15 14:28:22 +00002226
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002227 .. method:: setdefault(key[, default])
Georg Brandl116aa622007-08-15 14:28:22 +00002228
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002229 If *key* is in the dictionary, return its value. If not, insert *key*
2230 with a value of *default* and return *default*. *default* defaults to
2231 ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +00002232
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002233 .. method:: update([other])
Georg Brandl116aa622007-08-15 14:28:22 +00002234
Éric Araujo0fc86b82010-08-18 22:29:54 +00002235 Update the dictionary with the key/value pairs from *other*, overwriting
2236 existing keys. Return ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +00002237
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002238 :meth:`update` accepts either another dictionary object or an iterable of
Georg Brandlfda21062010-09-25 16:56:36 +00002239 key/value pairs (as tuples or other iterables of length two). If keyword
Benjamin Peterson8719ad52009-09-11 22:24:02 +00002240 arguments are specified, the dictionary is then updated with those
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002241 key/value pairs: ``d.update(red=1, blue=2)``.
Georg Brandl116aa622007-08-15 14:28:22 +00002242
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002243 .. method:: values()
Georg Brandl116aa622007-08-15 14:28:22 +00002244
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00002245 Return a new view of the dictionary's values. See below for documentation of
2246 view objects.
Georg Brandld22a8152007-09-04 17:43:37 +00002247
2248
Benjamin Peterson44309e62008-11-22 00:41:45 +00002249.. _dict-views:
2250
Georg Brandld22a8152007-09-04 17:43:37 +00002251Dictionary view objects
2252-----------------------
2253
2254The objects returned by :meth:`dict.keys`, :meth:`dict.values` and
2255:meth:`dict.items` are *view objects*. They provide a dynamic view on the
2256dictionary's entries, which means that when the dictionary changes, the view
Benjamin Petersonce0506c2008-11-17 21:47:41 +00002257reflects these changes.
Georg Brandld22a8152007-09-04 17:43:37 +00002258
2259Dictionary views can be iterated over to yield their respective data, and
2260support membership tests:
2261
2262.. describe:: len(dictview)
2263
2264 Return the number of entries in the dictionary.
2265
2266.. describe:: iter(dictview)
2267
2268 Return an iterator over the keys, values or items (represented as tuples of
2269 ``(key, value)``) in the dictionary.
2270
2271 Keys and values are iterated over in an arbitrary order which is non-random,
2272 varies across Python implementations, and depends on the dictionary's history
2273 of insertions and deletions. If keys, values and items views are iterated
2274 over with no intervening modifications to the dictionary, the order of items
2275 will directly correspond. This allows the creation of ``(value, key)`` pairs
2276 using :func:`zip`: ``pairs = zip(d.values(), d.keys())``. Another way to
2277 create the same list is ``pairs = [(v, k) for (k, v) in d.items()]``.
2278
Georg Brandl81269142009-05-17 08:31:29 +00002279 Iterating views while adding or deleting entries in the dictionary may raise
2280 a :exc:`RuntimeError` or fail to iterate over all entries.
Benjamin Petersond23f8222009-04-05 19:13:16 +00002281
Georg Brandld22a8152007-09-04 17:43:37 +00002282.. describe:: x in dictview
2283
2284 Return ``True`` if *x* is in the underlying dictionary's keys, values or
2285 items (in the latter case, *x* should be a ``(key, value)`` tuple).
2286
2287
Benjamin Petersonce0506c2008-11-17 21:47:41 +00002288Keys views are set-like since their entries are unique and hashable. If all
Georg Brandlf74cf772010-10-15 16:03:02 +00002289values are hashable, so that ``(key, value)`` pairs are unique and hashable,
2290then the items view is also set-like. (Values views are not treated as set-like
2291since the entries are generally not unique.) For set-like views, all of the
2292operations defined for the abstract base class :class:`collections.Set` are
2293available (for example, ``==``, ``<``, or ``^``).
Georg Brandl116aa622007-08-15 14:28:22 +00002294
Georg Brandlc53c9662007-09-04 17:58:02 +00002295An example of dictionary view usage::
2296
2297 >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
2298 >>> keys = dishes.keys()
2299 >>> values = dishes.values()
2300
2301 >>> # iteration
2302 >>> n = 0
2303 >>> for val in values:
2304 ... n += val
2305 >>> print(n)
2306 504
2307
2308 >>> # keys and values are iterated over in the same order
2309 >>> list(keys)
2310 ['eggs', 'bacon', 'sausage', 'spam']
2311 >>> list(values)
2312 [2, 1, 1, 500]
2313
2314 >>> # view objects are dynamic and reflect dict changes
2315 >>> del dishes['eggs']
2316 >>> del dishes['sausage']
2317 >>> list(keys)
2318 ['spam', 'bacon']
2319
2320 >>> # set operations
2321 >>> keys & {'eggs', 'bacon', 'salad'}
Gregory P. Smithe8388122008-09-04 04:18:09 +00002322 {'bacon'}
Georg Brandlf74cf772010-10-15 16:03:02 +00002323 >>> keys ^ {'sausage', 'juice'}
Sandro Tosi2a8d1952011-08-02 18:42:04 +02002324 {'juice', 'sausage', 'bacon', 'spam'}
Georg Brandlc53c9662007-09-04 17:58:02 +00002325
2326
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002327.. _typememoryview:
2328
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002329memoryview type
2330===============
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002331
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002332:class:`memoryview` objects allow Python code to access the internal data
Antoine Pitroucc4edd52010-12-12 20:01:43 +00002333of an object that supports the :ref:`buffer protocol <bufferobjects>` without
2334copying. Memory is generally interpreted as simple bytes.
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002335
2336.. class:: memoryview(obj)
2337
Georg Brandl1009d392008-09-10 07:14:18 +00002338 Create a :class:`memoryview` that references *obj*. *obj* must support the
Georg Brandl12a61532011-03-06 10:57:52 +01002339 buffer protocol. Built-in objects that support the buffer protocol include
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002340 :class:`bytes` and :class:`bytearray`.
2341
Antoine Pitrouc7795152010-07-12 20:01:52 +00002342 A :class:`memoryview` has the notion of an *element*, which is the
2343 atomic memory unit handled by the originating object *obj*. For many
2344 simple types such as :class:`bytes` and :class:`bytearray`, an element
2345 is a single byte, but other types such as :class:`array.array` may have
2346 bigger elements.
2347
2348 ``len(view)`` returns the total number of elements in the memoryview,
2349 *view*. The :class:`~memoryview.itemsize` attribute will give you the
2350 number of bytes in a single element.
Benjamin Peterson5e19e442008-09-10 21:47:03 +00002351
Georg Brandl1009d392008-09-10 07:14:18 +00002352 A :class:`memoryview` supports slicing to expose its data. Taking a single
Antoine Pitrouc7795152010-07-12 20:01:52 +00002353 index will return a single element as a :class:`bytes` object. Full
2354 slicing will result in a subview::
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002355
2356 >>> v = memoryview(b'abcefg')
2357 >>> v[1]
2358 b'b'
2359 >>> v[-1]
2360 b'g'
2361 >>> v[1:4]
2362 <memory at 0x77ab28>
2363 >>> bytes(v[1:4])
2364 b'bce'
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002365
Antoine Pitrouc7795152010-07-12 20:01:52 +00002366 If the object the memoryview is over supports changing its data, the
Georg Brandl1009d392008-09-10 07:14:18 +00002367 memoryview supports slice assignment::
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002368
2369 >>> data = bytearray(b'abcefg')
2370 >>> v = memoryview(data)
2371 >>> v.readonly
2372 False
Benjamin Peterson52504012009-06-23 03:09:33 +00002373 >>> v[0] = b'z'
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002374 >>> data
2375 bytearray(b'zbcefg')
2376 >>> v[1:4] = b'123'
2377 >>> data
2378 bytearray(b'a123fg')
2379 >>> v[2] = b'spam'
2380 Traceback (most recent call last):
2381 File "<stdin>", line 1, in <module>
2382 ValueError: cannot modify size of memoryview object
2383
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00002384 Notice how the size of the memoryview object cannot be changed.
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002385
Antoine Pitrou6e6cc832010-09-09 12:59:39 +00002386 :class:`memoryview` has several methods:
2387
Georg Brandl47859162010-09-10 20:43:53 +00002388 .. method:: tobytes()
2389
2390 Return the data in the buffer as a bytestring. This is equivalent to
2391 calling the :class:`bytes` constructor on the memoryview. ::
2392
2393 >>> m = memoryview(b"abc")
2394 >>> m.tobytes()
2395 b'abc'
2396 >>> bytes(m)
2397 b'abc'
2398
2399 .. method:: tolist()
2400
2401 Return the data in the buffer as a list of integers. ::
2402
2403 >>> memoryview(b'abc').tolist()
2404 [97, 98, 99]
2405
Antoine Pitrou6e6cc832010-09-09 12:59:39 +00002406 .. method:: release()
2407
2408 Release the underlying buffer exposed by the memoryview object. Many
2409 objects take special actions when a view is held on them (for example,
2410 a :class:`bytearray` would temporarily forbid resizing); therefore,
2411 calling release() is handy to remove these restrictions (and free any
2412 dangling resources) as soon as possible.
2413
2414 After this method has been called, any further operation on the view
2415 raises a :class:`ValueError` (except :meth:`release()` itself which can
2416 be called multiple times)::
2417
2418 >>> m = memoryview(b'abc')
2419 >>> m.release()
2420 >>> m[0]
2421 Traceback (most recent call last):
2422 File "<stdin>", line 1, in <module>
2423 ValueError: operation forbidden on released memoryview object
2424
2425 The context management protocol can be used for a similar effect,
2426 using the ``with`` statement::
2427
2428 >>> with memoryview(b'abc') as m:
2429 ... m[0]
2430 ...
2431 b'a'
2432 >>> m[0]
2433 Traceback (most recent call last):
2434 File "<stdin>", line 1, in <module>
2435 ValueError: operation forbidden on released memoryview object
2436
2437 .. versionadded:: 3.2
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002438
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002439 There are also several readonly attributes available:
2440
2441 .. attribute:: format
2442
2443 A string containing the format (in :mod:`struct` module style) for each
2444 element in the view. This defaults to ``'B'``, a simple bytestring.
2445
2446 .. attribute:: itemsize
2447
Antoine Pitrouc7795152010-07-12 20:01:52 +00002448 The size in bytes of each element of the memoryview::
2449
2450 >>> m = memoryview(array.array('H', [1,2,3]))
2451 >>> m.itemsize
2452 2
2453 >>> m[0]
2454 b'\x01\x00'
2455 >>> len(m[0]) == m.itemsize
2456 True
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002457
2458 .. attribute:: shape
2459
Georg Brandl1009d392008-09-10 07:14:18 +00002460 A tuple of integers the length of :attr:`ndim` giving the shape of the
2461 memory as a N-dimensional array.
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002462
2463 .. attribute:: ndim
2464
2465 An integer indicating how many dimensions of a multi-dimensional array the
2466 memory represents.
2467
2468 .. attribute:: strides
2469
Benjamin Peterson2409dc72008-09-10 21:38:31 +00002470 A tuple of integers the length of :attr:`ndim` giving the size in bytes to
2471 access each element for each dimension of the array.
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002472
Georg Brandlc28036b2010-12-28 11:08:17 +00002473 .. attribute:: readonly
2474
2475 A bool indicating whether the memory is read only.
2476
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002477 .. memoryview.suboffsets isn't documented because it only seems useful for C
2478
2479
Georg Brandl116aa622007-08-15 14:28:22 +00002480.. _typecontextmanager:
2481
2482Context Manager Types
2483=====================
2484
Georg Brandl116aa622007-08-15 14:28:22 +00002485.. index::
2486 single: context manager
2487 single: context management protocol
2488 single: protocol; context management
2489
2490Python's :keyword:`with` statement supports the concept of a runtime context
Antoine Pitroua6540902010-12-12 20:09:18 +00002491defined by a context manager. This is implemented using a pair of methods
Georg Brandl116aa622007-08-15 14:28:22 +00002492that allow user-defined classes to define a runtime context that is entered
Antoine Pitroua6540902010-12-12 20:09:18 +00002493before the statement body is executed and exited when the statement ends:
Georg Brandl116aa622007-08-15 14:28:22 +00002494
2495
2496.. method:: contextmanager.__enter__()
2497
2498 Enter the runtime context and return either this object or another object
2499 related to the runtime context. The value returned by this method is bound to
2500 the identifier in the :keyword:`as` clause of :keyword:`with` statements using
2501 this context manager.
2502
Antoine Pitrou11cb9612010-09-15 11:11:28 +00002503 An example of a context manager that returns itself is a :term:`file object`.
2504 File objects return themselves from __enter__() to allow :func:`open` to be
2505 used as the context expression in a :keyword:`with` statement.
Georg Brandl116aa622007-08-15 14:28:22 +00002506
2507 An example of a context manager that returns a related object is the one
Christian Heimesfaf2f632008-01-06 16:59:19 +00002508 returned by :func:`decimal.localcontext`. These managers set the active
Georg Brandl116aa622007-08-15 14:28:22 +00002509 decimal context to a copy of the original decimal context and then return the
2510 copy. This allows changes to be made to the current decimal context in the body
2511 of the :keyword:`with` statement without affecting code outside the
2512 :keyword:`with` statement.
2513
2514
2515.. method:: contextmanager.__exit__(exc_type, exc_val, exc_tb)
2516
Georg Brandl9afde1c2007-11-01 20:32:30 +00002517 Exit the runtime context and return a Boolean flag indicating if any exception
Georg Brandl116aa622007-08-15 14:28:22 +00002518 that occurred should be suppressed. If an exception occurred while executing the
2519 body of the :keyword:`with` statement, the arguments contain the exception type,
2520 value and traceback information. Otherwise, all three arguments are ``None``.
2521
2522 Returning a true value from this method will cause the :keyword:`with` statement
2523 to suppress the exception and continue execution with the statement immediately
2524 following the :keyword:`with` statement. Otherwise the exception continues
2525 propagating after this method has finished executing. Exceptions that occur
2526 during execution of this method will replace any exception that occurred in the
2527 body of the :keyword:`with` statement.
2528
2529 The exception passed in should never be reraised explicitly - instead, this
2530 method should return a false value to indicate that the method completed
2531 successfully and does not want to suppress the raised exception. This allows
2532 context management code (such as ``contextlib.nested``) to easily detect whether
2533 or not an :meth:`__exit__` method has actually failed.
2534
2535Python defines several context managers to support easy thread synchronisation,
2536prompt closure of files or other objects, and simpler manipulation of the active
2537decimal arithmetic context. The specific types are not treated specially beyond
2538their implementation of the context management protocol. See the
2539:mod:`contextlib` module for some examples.
2540
Antoine Pitroua6540902010-12-12 20:09:18 +00002541Python's :term:`generator`\s and the :class:`contextlib.contextmanager` decorator
Christian Heimesd8654cf2007-12-02 15:22:16 +00002542provide a convenient way to implement these protocols. If a generator function is
Antoine Pitroua6540902010-12-12 20:09:18 +00002543decorated with the :class:`contextlib.contextmanager` decorator, it will return a
Georg Brandl116aa622007-08-15 14:28:22 +00002544context manager implementing the necessary :meth:`__enter__` and
2545:meth:`__exit__` methods, rather than the iterator produced by an undecorated
2546generator function.
2547
2548Note that there is no specific slot for any of these methods in the type
2549structure for Python objects in the Python/C API. Extension types wanting to
2550define these methods must provide them as a normal Python accessible method.
2551Compared to the overhead of setting up the runtime context, the overhead of a
2552single class dictionary lookup is negligible.
2553
2554
2555.. _typesother:
2556
2557Other Built-in Types
2558====================
2559
2560The interpreter supports several other kinds of objects. Most of these support
2561only one or two operations.
2562
2563
2564.. _typesmodules:
2565
2566Modules
2567-------
2568
2569The only special operation on a module is attribute access: ``m.name``, where
2570*m* is a module and *name* accesses a name defined in *m*'s symbol table.
2571Module attributes can be assigned to. (Note that the :keyword:`import`
2572statement is not, strictly speaking, an operation on a module object; ``import
2573foo`` does not require a module object named *foo* to exist, rather it requires
2574an (external) *definition* for a module named *foo* somewhere.)
2575
Senthil Kumarana6bac952011-07-04 11:28:30 -07002576A special attribute of every module is :attr:`__dict__`. This is the dictionary
Georg Brandl116aa622007-08-15 14:28:22 +00002577containing the module's symbol table. Modifying this dictionary will actually
2578change the module's symbol table, but direct assignment to the :attr:`__dict__`
2579attribute is not possible (you can write ``m.__dict__['a'] = 1``, which defines
2580``m.a`` to be ``1``, but you can't write ``m.__dict__ = {}``). Modifying
2581:attr:`__dict__` directly is not recommended.
2582
2583Modules built into the interpreter are written like this: ``<module 'sys'
2584(built-in)>``. If loaded from a file, they are written as ``<module 'os' from
2585'/usr/local/lib/pythonX.Y/os.pyc'>``.
2586
2587
2588.. _typesobjects:
2589
2590Classes and Class Instances
2591---------------------------
2592
2593See :ref:`objects` and :ref:`class` for these.
2594
2595
2596.. _typesfunctions:
2597
2598Functions
2599---------
2600
2601Function objects are created by function definitions. The only operation on a
2602function object is to call it: ``func(argument-list)``.
2603
2604There are really two flavors of function objects: built-in functions and
2605user-defined functions. Both support the same operation (to call the function),
2606but the implementation is different, hence the different object types.
2607
2608See :ref:`function` for more information.
2609
2610
2611.. _typesmethods:
2612
2613Methods
2614-------
2615
2616.. index:: object: method
2617
2618Methods are functions that are called using the attribute notation. There are
2619two flavors: built-in methods (such as :meth:`append` on lists) and class
2620instance methods. Built-in methods are described with the types that support
2621them.
2622
Georg Brandl2e0b7552007-11-27 12:43:08 +00002623If you access a method (a function defined in a class namespace) through an
2624instance, you get a special object: a :dfn:`bound method` (also called
2625:dfn:`instance method`) object. When called, it will add the ``self`` argument
2626to the argument list. Bound methods have two special read-only attributes:
2627``m.__self__`` is the object on which the method operates, and ``m.__func__`` is
2628the function implementing the method. Calling ``m(arg-1, arg-2, ..., arg-n)``
2629is completely equivalent to calling ``m.__func__(m.__self__, arg-1, arg-2, ...,
2630arg-n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00002631
Georg Brandl2e0b7552007-11-27 12:43:08 +00002632Like function objects, bound method objects support getting arbitrary
2633attributes. However, since method attributes are actually stored on the
2634underlying function object (``meth.__func__``), setting method attributes on
2635bound methods is disallowed. Attempting to set a method attribute results in a
Georg Brandl116aa622007-08-15 14:28:22 +00002636:exc:`TypeError` being raised. In order to set a method attribute, you need to
2637explicitly set it on the underlying function object::
2638
2639 class C:
2640 def method(self):
2641 pass
2642
2643 c = C()
Christian Heimesff737952007-11-27 10:40:20 +00002644 c.method.__func__.whoami = 'my name is c'
Georg Brandl116aa622007-08-15 14:28:22 +00002645
2646See :ref:`types` for more information.
2647
2648
2649.. _bltin-code-objects:
2650
2651Code Objects
2652------------
2653
2654.. index:: object: code
2655
2656.. index::
2657 builtin: compile
2658 single: __code__ (function object attribute)
2659
2660Code objects are used by the implementation to represent "pseudo-compiled"
2661executable Python code such as a function body. They differ from function
2662objects because they don't contain a reference to their global execution
2663environment. Code objects are returned by the built-in :func:`compile` function
2664and can be extracted from function objects through their :attr:`__code__`
2665attribute. See also the :mod:`code` module.
2666
2667.. index::
2668 builtin: exec
2669 builtin: eval
2670
2671A code object can be executed or evaluated by passing it (instead of a source
2672string) to the :func:`exec` or :func:`eval` built-in functions.
2673
2674See :ref:`types` for more information.
2675
2676
2677.. _bltin-type-objects:
2678
2679Type Objects
2680------------
2681
2682.. index::
2683 builtin: type
2684 module: types
2685
2686Type objects represent the various object types. An object's type is accessed
2687by the built-in function :func:`type`. There are no special operations on
2688types. The standard module :mod:`types` defines names for all standard built-in
2689types.
2690
Martin v. Löwis250ad612008-04-07 05:43:42 +00002691Types are written like this: ``<class 'int'>``.
Georg Brandl116aa622007-08-15 14:28:22 +00002692
2693
2694.. _bltin-null-object:
2695
2696The Null Object
2697---------------
2698
2699This object is returned by functions that don't explicitly return a value. It
2700supports no special operations. There is exactly one null object, named
2701``None`` (a built-in name).
2702
2703It is written as ``None``.
2704
2705
2706.. _bltin-ellipsis-object:
2707
2708The Ellipsis Object
2709-------------------
2710
Georg Brandlcb8ecb12007-09-04 06:35:14 +00002711This object is commonly used by slicing (see :ref:`slicings`). It supports no
2712special operations. There is exactly one ellipsis object, named
Georg Brandl116aa622007-08-15 14:28:22 +00002713:const:`Ellipsis` (a built-in name).
2714
2715It is written as ``Ellipsis`` or ``...``.
2716
Benjamin Peterson497cd652011-07-30 09:59:50 -05002717
Éric Araujo18ddf822011-09-01 23:10:36 +02002718.. _bltin-notimplemented-object:
2719
Benjamin Peterson50211fa2011-07-30 09:57:24 -05002720The NotImplemented Object
2721-------------------------
2722
2723This object is returned from comparisons and binary operations when they are
2724asked to operate on types they don't support. See :ref:`comparisons` for more
2725information.
2726
2727It is written as ``NotImplemented``.
2728
Georg Brandl116aa622007-08-15 14:28:22 +00002729
Éric Araujo18ddf822011-09-01 23:10:36 +02002730.. _bltin-boolean-values:
2731
Georg Brandl116aa622007-08-15 14:28:22 +00002732Boolean Values
2733--------------
2734
2735Boolean values are the two constant objects ``False`` and ``True``. They are
2736used to represent truth values (although other values can also be considered
2737false or true). In numeric contexts (for example when used as the argument to
2738an arithmetic operator), they behave like the integers 0 and 1, respectively.
Ezio Melottic1f26f62011-12-02 19:47:24 +02002739The built-in function :func:`bool` can be used to convert any value to a
2740Boolean, if the value can be interpreted as a truth value (see section
2741:ref:`truth` above).
Georg Brandl116aa622007-08-15 14:28:22 +00002742
2743.. index::
2744 single: False
2745 single: True
2746 pair: Boolean; values
2747
2748They are written as ``False`` and ``True``, respectively.
2749
2750
2751.. _typesinternal:
2752
2753Internal Objects
2754----------------
2755
2756See :ref:`types` for this information. It describes stack frame objects,
2757traceback objects, and slice objects.
2758
2759
2760.. _specialattrs:
2761
2762Special Attributes
2763==================
2764
2765The implementation adds a few special read-only attributes to several object
2766types, where they are relevant. Some of these are not reported by the
2767:func:`dir` built-in function.
2768
2769
2770.. attribute:: object.__dict__
2771
2772 A dictionary or other mapping object used to store an object's (writable)
2773 attributes.
2774
2775
2776.. attribute:: instance.__class__
2777
2778 The class to which a class instance belongs.
2779
2780
2781.. attribute:: class.__bases__
2782
Benjamin Peterson1baf4652009-12-31 03:11:23 +00002783 The tuple of base classes of a class object.
Georg Brandl116aa622007-08-15 14:28:22 +00002784
2785
2786.. attribute:: class.__name__
2787
2788 The name of the class or type.
2789
Georg Brandl7a51e582009-03-28 19:13:21 +00002790
Benjamin Petersond23f8222009-04-05 19:13:16 +00002791.. attribute:: class.__mro__
2792
2793 This attribute is a tuple of classes that are considered when looking for
2794 base classes during method resolution.
2795
2796
2797.. method:: class.mro()
2798
2799 This method can be overridden by a metaclass to customize the method
2800 resolution order for its instances. It is called at class instantiation, and
2801 its result is stored in :attr:`__mro__`.
2802
2803
Georg Brandl7a51e582009-03-28 19:13:21 +00002804.. method:: class.__subclasses__
2805
Florent Xicluna74e64952011-10-28 11:21:19 +02002806 Each class keeps a list of weak references to its immediate subclasses. This
2807 method returns a list of all those references still alive.
Benjamin Petersond23f8222009-04-05 19:13:16 +00002808 Example::
Georg Brandl7a51e582009-03-28 19:13:21 +00002809
2810 >>> int.__subclasses__()
Florent Xicluna74e64952011-10-28 11:21:19 +02002811 [<class 'bool'>]
Georg Brandl7a51e582009-03-28 19:13:21 +00002812
2813
Georg Brandl116aa622007-08-15 14:28:22 +00002814.. rubric:: Footnotes
2815
Ezio Melotti0656a562011-08-15 14:27:19 +03002816.. [1] Additional information on these special methods may be found in the Python
Georg Brandl116aa622007-08-15 14:28:22 +00002817 Reference Manual (:ref:`customization`).
2818
Ezio Melotti0656a562011-08-15 14:27:19 +03002819.. [2] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and
Georg Brandl116aa622007-08-15 14:28:22 +00002820 similarly for tuples.
2821
Ezio Melotti0656a562011-08-15 14:27:19 +03002822.. [3] They must have since the parser can't tell the type of the operands.
Georg Brandl116aa622007-08-15 14:28:22 +00002823
Ezio Melotti0656a562011-08-15 14:27:19 +03002824.. [4] Cased characters are those with general category property being one of
2825 "Lu" (Letter, uppercase), "Ll" (Letter, lowercase), or "Lt" (Letter, titlecase).
2826
2827.. [5] To format only a tuple you should therefore provide a singleton tuple whose only
Georg Brandl116aa622007-08-15 14:28:22 +00002828 element is the tuple to be formatted.