Debian Codegraph @

cpython27/Doc/library/stdtypes.rst

raw
1 .. XXX: reference/datamodel and this have quite a few overlaps!
2
3
4 .. _bltin-types:
5
6 **************
7 Built-in Types
8 **************
9
10 The following sections describe the standard types that are built into the
11 interpreter.
12
13 .. note::
14
15 Historically (until release 2.2), Python's built-in types have differed from
16 user-defined types because it was not possible to use the built-in types as the
17 basis for object-oriented inheritance. This limitation no longer
18 exists.
19
20 .. index:: pair: built-in; types
21
22 The principal built-in types are numerics, sequences, mappings, files, classes,
23 instances and exceptions.
24
25 .. index:: statement: print
26
27 Some operations are supported by several object types; in particular,
28 practically all objects can be compared, tested for truth value, and converted
29 to a string (with the :ref:`repr() <func-repr>` function or the slightly different
30 :func:`str` function). The latter function is implicitly used when an object is
31 written by the :func:`print` function.
32
33
34 .. _truth:
35
36 Truth Value Testing
37 ===================
38
39 .. index::
40 statement: if
41 statement: while
42 pair: truth; value
43 pair: Boolean; operations
44 single: false
45
46 Any object can be tested for truth value, for use in an :keyword:`if` or
47 :keyword:`while` condition or as operand of the Boolean operations below. The
48 following values are considered false:
49
50 .. index:: single: None (Built-in object)
51
52 * ``None``
53
54 .. index:: single: False (Built-in object)
55
56 * ``False``
57
58 * zero of any numeric type, for example, ``0``, ``0L``, ``0.0``, ``0j``.
59
60 * any empty sequence, for example, ``''``, ``()``, ``[]``.
61
62 * any empty mapping, for example, ``{}``.
63
64 * instances of user-defined classes, if the class defines a :meth:`__nonzero__`
65 or :meth:`__len__` method, when that method returns the integer zero or
66 :class:`bool` value ``False``. [1]_
67
68 .. index:: single: true
69
70 All other values are considered true --- so objects of many types are always
71 true.
72
73 .. index::
74 operator: or
75 operator: and
76 single: False
77 single: True
78
79 Operations and built-in functions that have a Boolean result always return ``0``
80 or ``False`` for false and ``1`` or ``True`` for true, unless otherwise stated.
81 (Important exception: the Boolean operations ``or`` and ``and`` always return
82 one of their operands.)
83
84
85 .. _boolean:
86
87 Boolean Operations --- :keyword:`and`, :keyword:`or`, :keyword:`not`
88 ====================================================================
89
90 .. index:: pair: Boolean; operations
91
92 These are the Boolean operations, ordered by ascending priority:
93
94 +-------------+---------------------------------+-------+
95 | Operation | Result | Notes |
96 +=============+=================================+=======+
97 | ``x or y`` | if *x* is false, then *y*, else | \(1) |
98 | | *x* | |
99 +-------------+---------------------------------+-------+
100 | ``x and y`` | if *x* is false, then *x*, else | \(2) |
101 | | *y* | |
102 +-------------+---------------------------------+-------+
103 | ``not x`` | if *x* is false, then ``True``, | \(3) |
104 | | else ``False`` | |
105 +-------------+---------------------------------+-------+
106
107 .. index::
108 operator: and
109 operator: or
110 operator: not
111
112 Notes:
113
114 (1)
115 This is a short-circuit operator, so it only evaluates the second
116 argument if the first one is false.
117
118 (2)
119 This is a short-circuit operator, so it only evaluates the second
120 argument if the first one is true.
121
122 (3)
123 ``not`` has a lower priority than non-Boolean operators, so ``not a == b`` is
124 interpreted as ``not (a == b)``, and ``a == not b`` is a syntax error.
125
126
127 .. _stdcomparisons:
128
129 Comparisons
130 ===========
131
132 .. index::
133 pair: chaining; comparisons
134 pair: operator; comparison
135 operator: ==
136 operator: <
137 operator: <=
138 operator: >
139 operator: >=
140 operator: !=
141 operator: is
142 operator: is not
143
144 Comparison operations are supported by all objects. They all have the same
145 priority (which is higher than that of the Boolean operations). Comparisons can
146 be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and
147 y <= z``, except that *y* is evaluated only once (but in both cases *z* is not
148 evaluated at all when ``x < y`` is found to be false).
149
150 This table summarizes the comparison operations:
151
152 +------------+-------------------------+-------+
153 | Operation | Meaning | Notes |
154 +============+=========================+=======+
155 | ``<`` | strictly less than | |
156 +------------+-------------------------+-------+
157 | ``<=`` | less than or equal | |
158 +------------+-------------------------+-------+
159 | ``>`` | strictly greater than | |
160 +------------+-------------------------+-------+
161 | ``>=`` | greater than or equal | |
162 +------------+-------------------------+-------+
163 | ``==`` | equal | |
164 +------------+-------------------------+-------+
165 | ``!=`` | not equal | \(1) |
166 +------------+-------------------------+-------+
167 | ``is`` | object identity | |
168 +------------+-------------------------+-------+
169 | ``is not`` | negated object identity | |
170 +------------+-------------------------+-------+
171
172 Notes:
173
174 (1)
175 ``!=`` can also be written ``<>``, but this is an obsolete usage
176 kept for backwards compatibility only. New code should always use
177 ``!=``.
178
179 .. index::
180 pair: object; numeric
181 pair: objects; comparing
182
183 Objects of different types, except different numeric types and different string
184 types, never compare equal; such objects are ordered consistently but
185 arbitrarily (so that sorting a heterogeneous array yields a consistent result).
186 Furthermore, some types (for example, file objects) support only a degenerate
187 notion of comparison where any two objects of that type are unequal. Again,
188 such objects are ordered arbitrarily but consistently. The ``<``, ``<=``, ``>``
189 and ``>=`` operators will raise a :exc:`TypeError` exception when any operand is
190 a complex number.
191
192 .. index::
193 single: __cmp__() (instance method)
194 single: __eq__() (instance method)
195 single: __ne__() (instance method)
196 single: __lt__() (instance method)
197 single: __le__() (instance method)
198 single: __gt__() (instance method)
199 single: __ge__() (instance method)
200
201 Non-identical instances of a class normally compare as non-equal unless the
202 class defines the :meth:`__eq__` method or the :meth:`__cmp__` method.
203
204 Instances of a class cannot be ordered with respect to other instances of the
205 same class, or other types of object, unless the class defines either enough of
206 the rich comparison methods (:meth:`__lt__`, :meth:`__le__`, :meth:`__gt__`, and
207 :meth:`__ge__`) or the :meth:`__cmp__` method.
208
209 .. impl-detail::
210
211 Objects of different types except numbers are ordered by their type names;
212 objects of the same types that don't support proper comparison are ordered by
213 their address.
214
215 .. index::
216 operator: in
217 operator: not in
218
219 Two more operations with the same syntactic priority, ``in`` and ``not in``, are
220 supported only by sequence types (below).
221
222
223 .. _typesnumeric:
224
225 Numeric Types --- :class:`int`, :class:`float`, :class:`long`, :class:`complex`
226 ===============================================================================
227
228 .. index::
229 object: numeric
230 object: Boolean
231 object: integer
232 object: long integer
233 object: floating point
234 object: complex number
235 pair: C; language
236
237 There are four distinct numeric types: :dfn:`plain integers`, :dfn:`long
238 integers`, :dfn:`floating point numbers`, and :dfn:`complex numbers`. In
239 addition, Booleans are a subtype of plain integers. Plain integers (also just
240 called :dfn:`integers`) are implemented using :c:type:`long` in C, which gives
241 them at least 32 bits of precision (``sys.maxint`` is always set to the maximum
242 plain integer value for the current platform, the minimum value is
243 ``-sys.maxint - 1``). Long integers have unlimited precision. Floating point
244 numbers are usually implemented using :c:type:`double` in C; information about
245 the precision and internal representation of floating point numbers for the
246 machine on which your program is running is available in
247 :data:`sys.float_info`. Complex numbers have a real and imaginary part, which
248 are each a floating point number. To extract these parts from a complex number
249 *z*, use ``z.real`` and ``z.imag``. (The standard library includes additional
250 numeric types, :mod:`fractions` that hold rationals, and :mod:`decimal` that
251 hold floating-point numbers with user-definable precision.)
252
253 .. index::
254 pair: numeric; literals
255 pair: integer; literals
256 triple: long; integer; literals
257 pair: floating point; literals
258 pair: complex number; literals
259 pair: hexadecimal; literals
260 pair: octal; literals
261
262 Numbers are created by numeric literals or as the result of built-in functions
263 and operators. Unadorned integer literals (including binary, hex, and octal
264 numbers) yield plain integers unless the value they denote is too large to be
265 represented as a plain integer, in which case they yield a long integer.
266 Integer literals with an ``'L'`` or ``'l'`` suffix yield long integers (``'L'``
267 is preferred because ``1l`` looks too much like eleven!). Numeric literals
268 containing a decimal point or an exponent sign yield floating point numbers.
269 Appending ``'j'`` or ``'J'`` to a numeric literal yields an imaginary number
270 (a complex number with a zero real part) which you can add to an integer or
271 float to get a complex number with real and imaginary parts.
272
273 .. index::
274 single: arithmetic
275 builtin: int
276 builtin: long
277 builtin: float
278 builtin: complex
279 operator: +
280 operator: -
281 operator: *
282 operator: /
283 operator: //
284 operator: %
285 operator: **
286
287 Python fully supports mixed arithmetic: when a binary arithmetic operator has
288 operands of different numeric types, the operand with the "narrower" type is
289 widened to that of the other, where plain integer is narrower than long integer
290 is narrower than floating point is narrower than complex. Comparisons between
291 numbers of mixed type use the same rule. [2]_ The constructors :func:`int`,
292 :func:`long`, :func:`float`, and :func:`complex` can be used to produce numbers
293 of a specific type.
294
295 All built-in numeric types support the following operations. See
296 :ref:`power` and later sections for the operators' priorities.
297
298 +--------------------+---------------------------------+--------+
299 | Operation | Result | Notes |
300 +====================+=================================+========+
301 | ``x + y`` | sum of *x* and *y* | |
302 +--------------------+---------------------------------+--------+
303 | ``x - y`` | difference of *x* and *y* | |
304 +--------------------+---------------------------------+--------+
305 | ``x * y`` | product of *x* and *y* | |
306 +--------------------+---------------------------------+--------+
307 | ``x / y`` | quotient of *x* and *y* | \(1) |
308 +--------------------+---------------------------------+--------+
309 | ``x // y`` | (floored) quotient of *x* and | (4)(5) |
310 | | *y* | |
311 +--------------------+---------------------------------+--------+
312 | ``x % y`` | remainder of ``x / y`` | \(4) |
313 +--------------------+---------------------------------+--------+
314 | ``-x`` | *x* negated | |
315 +--------------------+---------------------------------+--------+
316 | ``+x`` | *x* unchanged | |
317 +--------------------+---------------------------------+--------+
318 | ``abs(x)`` | absolute value or magnitude of | \(3) |
319 | | *x* | |
320 +--------------------+---------------------------------+--------+
321 | ``int(x)`` | *x* converted to integer | \(2) |
322 +--------------------+---------------------------------+--------+
323 | ``long(x)`` | *x* converted to long integer | \(2) |
324 +--------------------+---------------------------------+--------+
325 | ``float(x)`` | *x* converted to floating point | \(6) |
326 +--------------------+---------------------------------+--------+
327 | ``complex(re,im)`` | a complex number with real part | |
328 | | *re*, imaginary part *im*. | |
329 | | *im* defaults to zero. | |
330 +--------------------+---------------------------------+--------+
331 | ``c.conjugate()`` | conjugate of the complex number | |
332 | | *c*. (Identity on real numbers) | |
333 +--------------------+---------------------------------+--------+
334 | ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | (3)(4) |
335 +--------------------+---------------------------------+--------+
336 | ``pow(x, y)`` | *x* to the power *y* | (3)(7) |
337 +--------------------+---------------------------------+--------+
338 | ``x ** y`` | *x* to the power *y* | \(7) |
339 +--------------------+---------------------------------+--------+
340
341 .. index::
342 triple: operations on; numeric; types
343 single: conjugate() (complex number method)
344
345 Notes:
346
347 (1)
348 .. index::
349 pair: integer; division
350 triple: long; integer; division
351
352 For (plain or long) integer division, the result is an integer. The result is
353 always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and
354 (-1)/(-2) is 0. Note that the result is a long integer if either operand is a
355 long integer, regardless of the numeric value.
356
357 (2)
358 .. index::
359 module: math
360 single: floor() (in module math)
361 single: ceil() (in module math)
362 single: trunc() (in module math)
363 pair: numeric; conversions
364
365 Conversion from floats using :func:`int` or :func:`long` truncates toward
366 zero like the related function, :func:`math.trunc`. Use the function
367 :func:`math.floor` to round downward and :func:`math.ceil` to round
368 upward.
369
370 (3)
371 See :ref:`built-in-funcs` for a full description.
372
373 (4)
374 .. deprecated:: 2.3
375 The floor division operator, the modulo operator, and the :func:`divmod`
376 function are no longer defined for complex numbers. Instead, convert to
377 a floating point number using the :func:`abs` function if appropriate.
378
379 (5)
380 Also referred to as integer division. The resultant value is a whole integer,
381 though the result's type is not necessarily int.
382
383 (6)
384 float also accepts the strings "nan" and "inf" with an optional prefix "+"
385 or "-" for Not a Number (NaN) and positive or negative infinity.
386
387 .. versionadded:: 2.6
388
389 (7)
390 Python defines ``pow(0, 0)`` and ``0 ** 0`` to be ``1``, as is common for
391 programming languages.
392
393 All :class:`numbers.Real` types (:class:`int`, :class:`long`, and
394 :class:`float`) also include the following operations:
395
396 +--------------------+---------------------------------------------+
397 | Operation | Result |
398 +====================+=============================================+
399 | :func:`math.trunc(\| *x* truncated to :class:`~numbers.Integral` |
400 | x) <math.trunc>` | |
401 +--------------------+---------------------------------------------+
402 | :func:`round(x[, | *x* rounded to *n* digits, |
403 | n]) <round>` | rounding ties away from zero. If *n* |
404 | | is omitted, it defaults to 0. |
405 +--------------------+---------------------------------------------+
406 | :func:`math.floor(\| the greatest integer as a float <= *x* |
407 | x) <math.floor>` | |
408 +--------------------+---------------------------------------------+
409 | :func:`math.ceil(x)| the least integer as a float >= *x* |
410 | <math.ceil>` | |
411 +--------------------+---------------------------------------------+
412
413 .. XXXJH exceptions: overflow (when? what operations?) zerodivision
414
415
416 .. _bitstring-ops:
417
418 Bitwise Operations on Integer Types
419 --------------------------------------
420
421 .. index::
422 triple: operations on; integer; types
423 pair: bitwise; operations
424 pair: shifting; operations
425 pair: masking; operations
426 operator: |
427 operator: ^
428 operator: &
429 operator: <<
430 operator: >>
431 operator: ~
432
433 Bitwise operations only make sense for integers. Negative numbers are treated
434 as their 2's complement value (this assumes a sufficiently large number of bits
435 that no overflow occurs during the operation).
436
437 The priorities of the binary bitwise operations are all lower than the numeric
438 operations and higher than the comparisons; the unary operation ``~`` has the
439 same priority as the other unary numeric operations (``+`` and ``-``).
440
441 This table lists the bitwise operations sorted in ascending priority:
442
443 +------------+--------------------------------+----------+
444 | Operation | Result | Notes |
445 +============+================================+==========+
446 | ``x | y`` | bitwise :dfn:`or` of *x* and | |
447 | | *y* | |
448 +------------+--------------------------------+----------+
449 | ``x ^ y`` | bitwise :dfn:`exclusive or` of | |
450 | | *x* and *y* | |
451 +------------+--------------------------------+----------+
452 | ``x & y`` | bitwise :dfn:`and` of *x* and | |
453 | | *y* | |
454 +------------+--------------------------------+----------+
455 | ``x << n`` | *x* shifted left by *n* bits | (1)(2) |
456 +------------+--------------------------------+----------+
457 | ``x >> n`` | *x* shifted right by *n* bits | (1)(3) |
458 +------------+--------------------------------+----------+
459 | ``~x`` | the bits of *x* inverted | |
460 +------------+--------------------------------+----------+
461
462 Notes:
463
464 (1)
465 Negative shift counts are illegal and cause a :exc:`ValueError` to be raised.
466
467 (2)
468 A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)``. A
469 long integer is returned if the result exceeds the range of plain integers.
470
471 (3)
472 A right shift by *n* bits is equivalent to division by ``pow(2, n)``.
473
474
475 Additional Methods on Integer Types
476 -----------------------------------
477
478 The integer types implement the :class:`numbers.Integral` :term:`abstract base
479 class`. In addition, they provide one more method:
480
481 .. method:: int.bit_length()
482 .. method:: long.bit_length()
483
484 Return the number of bits necessary to represent an integer in binary,
485 excluding the sign and leading zeros::
486
487 >>> n = -37
488 >>> bin(n)
489 '-0b100101'
490 >>> n.bit_length()
491 6
492
493 More precisely, if ``x`` is nonzero, then ``x.bit_length()`` is the
494 unique positive integer ``k`` such that ``2**(k-1) <= abs(x) < 2**k``.
495 Equivalently, when ``abs(x)`` is small enough to have a correctly
496 rounded logarithm, then ``k = 1 + int(log(abs(x), 2))``.
497 If ``x`` is zero, then ``x.bit_length()`` returns ``0``.
498
499 Equivalent to::
500
501 def bit_length(self):
502 s = bin(self) # binary representation: bin(-37) --> '-0b100101'
503 s = s.lstrip('-0b') # remove leading zeros and minus sign
504 return len(s) # len('100101') --> 6
505
506 .. versionadded:: 2.7
507
508
509 Additional Methods on Float
510 ---------------------------
511
512 The float type implements the :class:`numbers.Real` :term:`abstract base
513 class`. float also has the following additional methods.
514
515 .. method:: float.as_integer_ratio()
516
517 Return a pair of integers whose ratio is exactly equal to the
518 original float and with a positive denominator. Raises
519 :exc:`OverflowError` on infinities and a :exc:`ValueError` on
520 NaNs.
521
522 .. versionadded:: 2.6
523
524 .. method:: float.is_integer()
525
526 Return ``True`` if the float instance is finite with integral
527 value, and ``False`` otherwise::
528
529 >>> (-2.0).is_integer()
530 True
531 >>> (3.2).is_integer()
532 False
533
534 .. versionadded:: 2.6
535
536 Two methods support conversion to
537 and from hexadecimal strings. Since Python's floats are stored
538 internally as binary numbers, converting a float to or from a
539 *decimal* string usually involves a small rounding error. In
540 contrast, hexadecimal strings allow exact representation and
541 specification of floating-point numbers. This can be useful when
542 debugging, and in numerical work.
543
544
545 .. method:: float.hex()
546
547 Return a representation of a floating-point number as a hexadecimal
548 string. For finite floating-point numbers, this representation
549 will always include a leading ``0x`` and a trailing ``p`` and
550 exponent.
551
552 .. versionadded:: 2.6
553
554
555 .. method:: float.fromhex(s)
556
557 Class method to return the float represented by a hexadecimal
558 string *s*. The string *s* may have leading and trailing
559 whitespace.
560
561 .. versionadded:: 2.6
562
563
564 Note that :meth:`float.hex` is an instance method, while
565 :meth:`float.fromhex` is a class method.
566
567 A hexadecimal string takes the form::
568
569 [sign] ['0x'] integer ['.' fraction] ['p' exponent]
570
571 where the optional ``sign`` may by either ``+`` or ``-``, ``integer``
572 and ``fraction`` are strings of hexadecimal digits, and ``exponent``
573 is a decimal integer with an optional leading sign. Case is not
574 significant, and there must be at least one hexadecimal digit in
575 either the integer or the fraction. This syntax is similar to the
576 syntax specified in section 6.4.4.2 of the C99 standard, and also to
577 the syntax used in Java 1.5 onwards. In particular, the output of
578 :meth:`float.hex` is usable as a hexadecimal floating-point literal in
579 C or Java code, and hexadecimal strings produced by C's ``%a`` format
580 character or Java's ``Double.toHexString`` are accepted by
581 :meth:`float.fromhex`.
582
583
584 Note that the exponent is written in decimal rather than hexadecimal,
585 and that it gives the power of 2 by which to multiply the coefficient.
586 For example, the hexadecimal string ``0x3.a7p10`` represents the
587 floating-point number ``(3 + 10./16 + 7./16**2) * 2.0**10``, or
588 ``3740.0``::
589
590 >>> float.fromhex('0x3.a7p10')
591 3740.0
592
593
594 Applying the reverse conversion to ``3740.0`` gives a different
595 hexadecimal string representing the same number::
596
597 >>> float.hex(3740.0)
598 '0x1.d380000000000p+11'
599
600
601 .. _typeiter:
602
603 Iterator Types
604 ==============
605
606 .. versionadded:: 2.2
607
608 .. index::
609 single: iterator protocol
610 single: protocol; iterator
611 single: sequence; iteration
612 single: container; iteration over
613
614 Python supports a concept of iteration over containers. This is implemented
615 using two distinct methods; these are used to allow user-defined classes to
616 support iteration. Sequences, described below in more detail, always support
617 the iteration methods.
618
619 One method needs to be defined for container objects to provide iteration
620 support:
621
622 .. XXX duplicated in reference/datamodel!
623
624 .. method:: container.__iter__()
625
626 Return an iterator object. The object is required to support the iterator
627 protocol described below. If a container supports different types of
628 iteration, additional methods can be provided to specifically request
629 iterators for those iteration types. (An example of an object supporting
630 multiple forms of iteration would be a tree structure which supports both
631 breadth-first and depth-first traversal.) This method corresponds to the
632 :c:member:`~PyTypeObject.tp_iter` slot of the type structure for Python objects in the Python/C
633 API.
634
635 The iterator objects themselves are required to support the following two
636 methods, which together form the :dfn:`iterator protocol`:
637
638
639 .. method:: iterator.__iter__()
640
641 Return the iterator object itself. This is required to allow both containers
642 and iterators to be used with the :keyword:`for` and :keyword:`in` statements.
643 This method corresponds to the :c:member:`~PyTypeObject.tp_iter` slot of the type structure for
644 Python objects in the Python/C API.
645
646
647 .. method:: iterator.next()
648
649 Return the next item from the container. If there are no further items, raise
650 the :exc:`StopIteration` exception. This method corresponds to the
651 :c:member:`~PyTypeObject.tp_iternext` slot of the type structure for Python objects in the
652 Python/C API.
653
654 Python defines several iterator objects to support iteration over general and
655 specific sequence types, dictionaries, and other more specialized forms. The
656 specific types are not important beyond their implementation of the iterator
657 protocol.
658
659 The intention of the protocol is that once an iterator's :meth:`~iterator.next` method
660 raises :exc:`StopIteration`, it will continue to do so on subsequent calls.
661 Implementations that do not obey this property are deemed broken. (This
662 constraint was added in Python 2.3; in Python 2.2, various iterators are broken
663 according to this rule.)
664
665
666 .. _generator-types:
667
668 Generator Types
669 ---------------
670
671 Python's :term:`generator`\s provide a convenient way to implement the iterator
672 protocol. If a container object's :meth:`__iter__` method is implemented as a
673 generator, it will automatically return an iterator object (technically, a
674 generator object) supplying the :meth:`~iterator.__iter__` and
675 :meth:`~iterator.next` methods. More information about generators can be found
676 in :ref:`the documentation for the yield expression <yieldexpr>`.
677
678
679 .. _typesseq:
680
681 Sequence Types --- :class:`str`, :class:`unicode`, :class:`list`, :class:`tuple`, :class:`bytearray`, :class:`buffer`, :class:`xrange`
682 ======================================================================================================================================
683
684 There are seven sequence types: strings, Unicode strings, lists, tuples,
685 bytearrays, buffers, and xrange objects.
686
687 For other containers see the built in :class:`dict` and :class:`set` classes,
688 and the :mod:`collections` module.
689
690
691 .. index::
692 object: sequence
693 object: string
694 object: Unicode
695 object: tuple
696 object: list
697 object: bytearray
698 object: buffer
699 object: xrange
700
701 String literals are written in single or double quotes: ``'xyzzy'``,
702 ``"frobozz"``. See :ref:`strings` for more about string literals.
703 Unicode strings are much like strings, but are specified in the syntax
704 using a preceding ``'u'`` character: ``u'abc'``, ``u"def"``. In addition
705 to the functionality described here, there are also string-specific
706 methods described in the :ref:`string-methods` section. Lists are
707 constructed with square brackets, separating items with commas: ``[a, b, c]``.
708 Tuples are constructed by the comma operator (not within square
709 brackets), with or without enclosing parentheses, but an empty tuple
710 must have the enclosing parentheses, such as ``a, b, c`` or ``()``. A
711 single item tuple must have a trailing comma, such as ``(d,)``.
712
713 Bytearray objects are created with the built-in function :func:`bytearray`.
714
715 Buffer objects are not directly supported by Python syntax, but can be created
716 by calling the built-in function :func:`buffer`. They don't support
717 concatenation or repetition.
718
719 Objects of type xrange are similar to buffers in that there is no specific syntax to
720 create them, but they are created using the :func:`xrange` function. They don't
721 support slicing, concatenation or repetition, and using ``in``, ``not in``,
722 :func:`min` or :func:`max` on them is inefficient.
723
724 Most sequence types support the following operations. The ``in`` and ``not in``
725 operations have the same priorities as the comparison operations. The ``+`` and
726 ``*`` operations have the same priority as the corresponding numeric operations.
727 [3]_ Additional methods are provided for :ref:`typesseq-mutable`.
728
729 This table lists the sequence operations sorted in ascending priority.
730 In the table, *s* and *t* are sequences of the same type; *n*, *i* and *j* are integers:
731
732 +------------------+--------------------------------+----------+
733 | Operation | Result | Notes |
734 +==================+================================+==========+
735 | ``x in s`` | ``True`` if an item of *s* is | \(1) |
736 | | equal to *x*, else ``False`` | |
737 +------------------+--------------------------------+----------+
738 | ``x not in s`` | ``False`` if an item of *s* is | \(1) |
739 | | equal to *x*, else ``True`` | |
740 +------------------+--------------------------------+----------+
741 | ``s + t`` | the concatenation of *s* and | \(6) |
742 | | *t* | |
743 +------------------+--------------------------------+----------+
744 | ``s * n, n * s`` | equivalent to adding *s* to | \(2) |
745 | | itself *n* times | |
746 +------------------+--------------------------------+----------+
747 | ``s[i]`` | *i*\ th item of *s*, origin 0 | \(3) |
748 +------------------+--------------------------------+----------+
749 | ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) |
750 +------------------+--------------------------------+----------+
751 | ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) |
752 | | with step *k* | |
753 +------------------+--------------------------------+----------+
754 | ``len(s)`` | length of *s* | |
755 +------------------+--------------------------------+----------+
756 | ``min(s)`` | smallest item of *s* | |
757 +------------------+--------------------------------+----------+
758 | ``max(s)`` | largest item of *s* | |
759 +------------------+--------------------------------+----------+
760 | ``s.index(x)`` | index of the first occurrence | |
761 | | of *x* in *s* | |
762 +------------------+--------------------------------+----------+
763 | ``s.count(x)`` | total number of occurrences of | |
764 | | *x* in *s* | |
765 +------------------+--------------------------------+----------+
766
767 Sequence types also support comparisons. In particular, tuples and lists
768 are compared lexicographically by comparing corresponding
769 elements. This means that to compare equal, every element must compare
770 equal and the two sequences must be of the same type and have the same
771 length. (For full details see :ref:`comparisons` in the language
772 reference.)
773
774 .. index::
775 triple: operations on; sequence; types
776 builtin: len
777 builtin: min
778 builtin: max
779 pair: concatenation; operation
780 pair: repetition; operation
781 pair: subscript; operation
782 pair: slice; operation
783 pair: extended slice; operation
784 operator: in
785 operator: not in
786
787 Notes:
788
789 (1)
790 When *s* is a string or Unicode string object the ``in`` and ``not in``
791 operations act like a substring test. In Python versions before 2.3, *x* had to
792 be a string of length 1. In Python 2.3 and beyond, *x* may be a string of any
793 length.
794
795 (2)
796 Values of *n* less than ``0`` are treated as ``0`` (which yields an empty
797 sequence of the same type as *s*). Note that items in the sequence *s*
798 are not copied; they are referenced multiple times. This often haunts
799 new Python programmers; consider:
800
801 >>> lists = [[]] * 3
802 >>> lists
803 [[], [], []]
804 >>> lists[0].append(3)
805 >>> lists
806 [[3], [3], [3]]
807
808 What has happened is that ``[[]]`` is a one-element list containing an empty
809 list, so all three elements of ``[[]] * 3`` are references to this single empty
810 list. Modifying any of the elements of ``lists`` modifies this single list.
811 You can create a list of different lists this way:
812
813 >>> lists = [[] for i in range(3)]
814 >>> lists[0].append(3)
815 >>> lists[1].append(5)
816 >>> lists[2].append(7)
817 >>> lists
818 [[3], [5], [7]]
819
820 Further explanation is available in the FAQ entry
821 :ref:`faq-multidimensional-list`.
822
823 (3)
824 If *i* or *j* is negative, the index is relative to the end of sequence *s*:
825 ``len(s) + i`` or ``len(s) + j`` is substituted. But note that ``-0`` is still
826 ``0``.
827
828 (4)
829 The slice of *s* from *i* to *j* is defined as the sequence of items with index
830 *k* such that ``i <= k < j``. If *i* or *j* is greater than ``len(s)``, use
831 ``len(s)``. If *i* is omitted or ``None``, use ``0``. If *j* is omitted or
832 ``None``, use ``len(s)``. If *i* is greater than or equal to *j*, the slice is
833 empty.
834
835 (5)
836 The slice of *s* from *i* to *j* with step *k* is defined as the sequence of
837 items with index ``x = i + n*k`` such that ``0 <= n < (j-i)/k``. In other words,
838 the indices are ``i``, ``i+k``, ``i+2*k``, ``i+3*k`` and so on, stopping when
839 *j* is reached (but never including *j*). When *k* is positive,
840 *i* and *j* are reduced to ``len(s)`` if they are greater.
841 When *k* is negative, *i* and *j* are reduced to ``len(s) - 1`` if
842 they are greater. If *i* or *j* are omitted or ``None``, they become
843 "end" values (which end depends on the sign of *k*). Note, *k* cannot be zero.
844 If *k* is ``None``, it is treated like ``1``.
845
846 (6)
847 .. impl-detail::
848
849 If *s* and *t* are both strings, some Python implementations such as
850 CPython can usually perform an in-place optimization for assignments of
851 the form ``s = s + t`` or ``s += t``. When applicable, this optimization
852 makes quadratic run-time much less likely. This optimization is both
853 version and implementation dependent. For performance sensitive code, it
854 is preferable to use the :meth:`str.join` method which assures consistent
855 linear concatenation performance across versions and implementations.
856
857 .. versionchanged:: 2.4
858 Formerly, string concatenation never occurred in-place.
859
860
861 .. _string-methods:
862
863 String Methods
864 --------------
865
866 .. index:: pair: string; methods
867
868 Below are listed the string methods which both 8-bit strings and
869 Unicode objects support. Some of them are also available on :class:`bytearray`
870 objects.
871
872 In addition, Python's strings support the sequence type methods
873 described in the :ref:`typesseq` section. To output formatted strings
874 use template strings or the ``%`` operator described in the
875 :ref:`string-formatting` section. Also, see the :mod:`re` module for
876 string functions based on regular expressions.
877
878 .. method:: str.capitalize()
879
880 Return a copy of the string with its first character capitalized and the
881 rest lowercased.
882
883 For 8-bit strings, this method is locale-dependent.
884
885
886 .. method:: str.center(width[, fillchar])
887
888 Return centered in a string of length *width*. Padding is done using the
889 specified *fillchar* (default is a space).
890
891 .. versionchanged:: 2.4
892 Support for the *fillchar* argument.
893
894
895 .. method:: str.count(sub[, start[, end]])
896
897 Return the number of non-overlapping occurrences of substring *sub* in the
898 range [*start*, *end*]. Optional arguments *start* and *end* are
899 interpreted as in slice notation.
900
901
902 .. method:: str.decode([encoding[, errors]])
903
904 Decodes the string using the codec registered for *encoding*. *encoding*
905 defaults to the default string encoding. *errors* may be given to set a
906 different error handling scheme. The default is ``'strict'``, meaning that
907 encoding errors raise :exc:`UnicodeError`. Other possible values are
908 ``'ignore'``, ``'replace'`` and any other name registered via
909 :func:`codecs.register_error`, see section :ref:`codec-base-classes`.
910
911 .. versionadded:: 2.2
912
913 .. versionchanged:: 2.3
914 Support for other error handling schemes added.
915
916 .. versionchanged:: 2.7
917 Support for keyword arguments added.
918
919 .. method:: str.encode([encoding[,errors]])
920
921 Return an encoded version of the string. Default encoding is the current
922 default string encoding. *errors* may be given to set a different error
923 handling scheme. The default for *errors* is ``'strict'``, meaning that
924 encoding errors raise a :exc:`UnicodeError`. Other possible values are
925 ``'ignore'``, ``'replace'``, ``'xmlcharrefreplace'``, ``'backslashreplace'`` and
926 any other name registered via :func:`codecs.register_error`, see section
927 :ref:`codec-base-classes`. For a list of possible encodings, see section
928 :ref:`standard-encodings`.
929
930 .. versionadded:: 2.0
931
932 .. versionchanged:: 2.3
933 Support for ``'xmlcharrefreplace'`` and ``'backslashreplace'`` and other error
934 handling schemes added.
935
936 .. versionchanged:: 2.7
937 Support for keyword arguments added.
938
939 .. method:: str.endswith(suffix[, start[, end]])
940
941 Return ``True`` if the string ends with the specified *suffix*, otherwise return
942 ``False``. *suffix* can also be a tuple of suffixes to look for. With optional
943 *start*, test beginning at that position. With optional *end*, stop comparing
944 at that position.
945
946 .. versionchanged:: 2.5
947 Accept tuples as *suffix*.
948
949
950 .. method:: str.expandtabs([tabsize])
951
952 Return a copy of the string where all tab characters are replaced by one or
953 more spaces, depending on the current column and the given tab size. Tab
954 positions occur every *tabsize* characters (default is 8, giving tab
955 positions at columns 0, 8, 16 and so on). To expand the string, the current
956 column is set to zero and the string is examined character by character. If
957 the character is a tab (``\t``), one or more space characters are inserted
958 in the result until the current column is equal to the next tab position.
959 (The tab character itself is not copied.) If the character is a newline
960 (``\n``) or return (``\r``), it is copied and the current column is reset to
961 zero. Any other character is copied unchanged and the current column is
962 incremented by one regardless of how the character is represented when
963 printed.
964
965 >>> '01\t012\t0123\t01234'.expandtabs()
966 '01 012 0123 01234'
967 >>> '01\t012\t0123\t01234'.expandtabs(4)
968 '01 012 0123 01234'
969
970
971 .. method:: str.find(sub[, start[, end]])
972
973 Return the lowest index in the string where substring *sub* is found within
974 the slice ``s[start:end]``. Optional arguments *start* and *end* are
975 interpreted as in slice notation. Return ``-1`` if *sub* is not found.
976
977 .. note::
978
979 The :meth:`~str.find` method should be used only if you need to know the
980 position of *sub*. To check if *sub* is a substring or not, use the
981 :keyword:`in` operator::
982
983 >>> 'Py' in 'Python'
984 True
985
986
987 .. method:: str.format(*args, **kwargs)
988
989 Perform a string formatting operation. The string on which this method is
990 called can contain literal text or replacement fields delimited by braces
991 ``{}``. Each replacement field contains either the numeric index of a
992 positional argument, or the name of a keyword argument. Returns a copy of
993 the string where each replacement field is replaced with the string value of
994 the corresponding argument.
995
996 >>> "The sum of 1 + 2 is {0}".format(1+2)
997 'The sum of 1 + 2 is 3'
998
999 See :ref:`formatstrings` for a description of the various formatting options
1000 that can be specified in format strings.
1001
1002 This method of string formatting is the new standard in Python 3, and
1003 should be preferred to the ``%`` formatting described in
1004 :ref:`string-formatting` in new code.
1005
1006 .. versionadded:: 2.6
1007
1008
1009 .. method:: str.index(sub[, start[, end]])
1010
1011 Like :meth:`find`, but raise :exc:`ValueError` when the substring is not found.
1012
1013
1014 .. method:: str.isalnum()
1015
1016 Return true if all characters in the string are alphanumeric and there is at
1017 least one character, false otherwise.
1018
1019 For 8-bit strings, this method is locale-dependent.
1020
1021
1022 .. method:: str.isalpha()
1023
1024 Return true if all characters in the string are alphabetic and there is at least
1025 one character, false otherwise.
1026
1027 For 8-bit strings, this method is locale-dependent.
1028
1029
1030 .. method:: str.isdigit()
1031
1032 Return true if all characters in the string are digits and there is at least one
1033 character, false otherwise.
1034
1035 For 8-bit strings, this method is locale-dependent.
1036
1037
1038 .. method:: str.islower()
1039
1040 Return true if all cased characters [4]_ in the string are lowercase and there is at
1041 least one cased character, false otherwise.
1042
1043 For 8-bit strings, this method is locale-dependent.
1044
1045
1046 .. method:: str.isspace()
1047
1048 Return true if there are only whitespace characters in the string and there is
1049 at least one character, false otherwise.
1050
1051 For 8-bit strings, this method is locale-dependent.
1052
1053
1054 .. method:: str.istitle()
1055
1056 Return true if the string is a titlecased string and there is at least one
1057 character, for example uppercase characters may only follow uncased characters
1058 and lowercase characters only cased ones. Return false otherwise.
1059
1060 For 8-bit strings, this method is locale-dependent.
1061
1062
1063 .. method:: str.isupper()
1064
1065 Return true if all cased characters [4]_ in the string are uppercase and there is at
1066 least one cased character, false otherwise.
1067
1068 For 8-bit strings, this method is locale-dependent.
1069
1070
1071 .. method:: str.join(iterable)
1072
1073 Return a string which is the concatenation of the strings in *iterable*.
1074 If there is any Unicode object in *iterable*, return a Unicode instead.
1075 A :exc:`TypeError` will be raised if there are any non-string or non Unicode
1076 object values in *iterable*. The separator between elements is the string
1077 providing this method.
1078
1079
1080 .. method:: str.ljust(width[, fillchar])
1081
1082 Return the string left justified in a string of length *width*. Padding is done
1083 using the specified *fillchar* (default is a space). The original string is
1084 returned if *width* is less than or equal to ``len(s)``.
1085
1086 .. versionchanged:: 2.4
1087 Support for the *fillchar* argument.
1088
1089
1090 .. method:: str.lower()
1091
1092 Return a copy of the string with all the cased characters [4]_ converted to
1093 lowercase.
1094
1095 For 8-bit strings, this method is locale-dependent.
1096
1097
1098 .. method:: str.lstrip([chars])
1099
1100 Return a copy of the string with leading characters removed. The *chars*
1101 argument is a string specifying the set of characters to be removed. If omitted
1102 or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
1103 argument is not a prefix; rather, all combinations of its values are stripped:
1104
1105 >>> ' spacious '.lstrip()
1106 'spacious '
1107 >>> 'www.example.com'.lstrip('cmowz.')
1108 'example.com'
1109
1110 .. versionchanged:: 2.2.2
1111 Support for the *chars* argument.
1112
1113
1114 .. method:: str.partition(sep)
1115
1116 Split the string at the first occurrence of *sep*, and return a 3-tuple
1117 containing the part before the separator, the separator itself, and the part
1118 after the separator. If the separator is not found, return a 3-tuple containing
1119 the string itself, followed by two empty strings.
1120
1121 .. versionadded:: 2.5
1122
1123
1124 .. method:: str.replace(old, new[, count])
1125
1126 Return a copy of the string with all occurrences of substring *old* replaced by
1127 *new*. If the optional argument *count* is given, only the first *count*
1128 occurrences are replaced.
1129
1130
1131 .. method:: str.rfind(sub [,start [,end]])
1132
1133 Return the highest index in the string where substring *sub* is found, such
1134 that *sub* is contained within ``s[start:end]``. Optional arguments *start*
1135 and *end* are interpreted as in slice notation. Return ``-1`` on failure.
1136
1137
1138 .. method:: str.rindex(sub[, start[, end]])
1139
1140 Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not
1141 found.
1142
1143
1144 .. method:: str.rjust(width[, fillchar])
1145
1146 Return the string right justified in a string of length *width*. Padding is done
1147 using the specified *fillchar* (default is a space). The original string is
1148 returned if *width* is less than or equal to ``len(s)``.
1149
1150 .. versionchanged:: 2.4
1151 Support for the *fillchar* argument.
1152
1153
1154 .. method:: str.rpartition(sep)
1155
1156 Split the string at the last occurrence of *sep*, and return a 3-tuple
1157 containing the part before the separator, the separator itself, and the part
1158 after the separator. If the separator is not found, return a 3-tuple containing
1159 two empty strings, followed by the string itself.
1160
1161 .. versionadded:: 2.5
1162
1163
1164 .. method:: str.rsplit([sep [,maxsplit]])
1165
1166 Return a list of the words in the string, using *sep* as the delimiter string.
1167 If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost*
1168 ones. If *sep* is not specified or ``None``, any whitespace string is a
1169 separator. Except for splitting from the right, :meth:`rsplit` behaves like
1170 :meth:`split` which is described in detail below.
1171
1172 .. versionadded:: 2.4
1173
1174
1175 .. method:: str.rstrip([chars])
1176
1177 Return a copy of the string with trailing characters removed. The *chars*
1178 argument is a string specifying the set of characters to be removed. If omitted
1179 or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
1180 argument is not a suffix; rather, all combinations of its values are stripped:
1181
1182 >>> ' spacious '.rstrip()
1183 ' spacious'
1184 >>> 'mississippi'.rstrip('ipz')
1185 'mississ'
1186
1187 .. versionchanged:: 2.2.2
1188 Support for the *chars* argument.
1189
1190
1191 .. method:: str.split([sep[, maxsplit]])
1192
1193 Return a list of the words in the string, using *sep* as the delimiter
1194 string. If *maxsplit* is given, at most *maxsplit* splits are done (thus,
1195 the list will have at most ``maxsplit+1`` elements). If *maxsplit* is not
1196 specified or ``-1``, then there is no limit on the number of splits
1197 (all possible splits are made).
1198
1199 If *sep* is given, consecutive delimiters are not grouped together and are
1200 deemed to delimit empty strings (for example, ``'1,,2'.split(',')`` returns
1201 ``['1', '', '2']``). The *sep* argument may consist of multiple characters
1202 (for example, ``'1<>2<>3'.split('<>')`` returns ``['1', '2', '3']``).
1203 Splitting an empty string with a specified separator returns ``['']``.
1204
1205 If *sep* is not specified or is ``None``, a different splitting algorithm is
1206 applied: runs of consecutive whitespace are regarded as a single separator,
1207 and the result will contain no empty strings at the start or end if the
1208 string has leading or trailing whitespace. Consequently, splitting an empty
1209 string or a string consisting of just whitespace with a ``None`` separator
1210 returns ``[]``.
1211
1212 For example, ``' 1 2 3 '.split()`` returns ``['1', '2', '3']``, and
1213 ``' 1 2 3 '.split(None, 1)`` returns ``['1', '2 3 ']``.
1214
1215
1216 .. index::
1217 single: universal newlines; str.splitlines method
1218
1219 .. method:: str.splitlines([keepends])
1220
1221 Return a list of the lines in the string, breaking at line boundaries.
1222 This method uses the :term:`universal newlines` approach to splitting lines.
1223 Line breaks are not included in the resulting list unless *keepends* is
1224 given and true.
1225
1226 Python recognizes ``"\r"``, ``"\n"``, and ``"\r\n"`` as line boundaries for
1227 8-bit strings.
1228
1229 For example::
1230
1231 >>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
1232 ['ab c', '', 'de fg', 'kl']
1233 >>> 'ab c\n\nde fg\rkl\r\n'.splitlines(True)
1234 ['ab c\n', '\n', 'de fg\r', 'kl\r\n']
1235
1236 Unlike :meth:`~str.split` when a delimiter string *sep* is given, this
1237 method returns an empty list for the empty string, and a terminal line
1238 break does not result in an extra line::
1239
1240 >>> "".splitlines()
1241 []
1242 >>> "One line\n".splitlines()
1243 ['One line']
1244
1245 For comparison, ``split('\n')`` gives::
1246
1247 >>> ''.split('\n')
1248 ['']
1249 >>> 'Two lines\n'.split('\n')
1250 ['Two lines', '']
1251
1252 .. method:: unicode.splitlines([keepends])
1253
1254 Return a list of the lines in the string, like :meth:`str.splitlines`.
1255 However, the Unicode method splits on the following line boundaries,
1256 which are a superset of the :term:`universal newlines` recognized for
1257 8-bit strings.
1258
1259 +-----------------------+-----------------------------+
1260 | Representation | Description |
1261 +=======================+=============================+
1262 | ``\n`` | Line Feed |
1263 +-----------------------+-----------------------------+
1264 | ``\r`` | Carriage Return |
1265 +-----------------------+-----------------------------+
1266 | ``\r\n`` | Carriage Return + Line Feed |
1267 +-----------------------+-----------------------------+
1268 | ``\v`` or ``\x0b`` | Line Tabulation |
1269 +-----------------------+-----------------------------+
1270 | ``\f`` or ``\x0c`` | Form Feed |
1271 +-----------------------+-----------------------------+
1272 | ``\x1c`` | File Separator |
1273 +-----------------------+-----------------------------+
1274 | ``\x1d`` | Group Separator |
1275 +-----------------------+-----------------------------+
1276 | ``\x1e`` | Record Separator |
1277 +-----------------------+-----------------------------+
1278 | ``\x85`` | Next Line (C1 Control Code) |
1279 +-----------------------+-----------------------------+
1280 | ``\u2028`` | Line Separator |
1281 +-----------------------+-----------------------------+
1282 | ``\u2029`` | Paragraph Separator |
1283 +-----------------------+-----------------------------+
1284
1285 .. versionchanged:: 2.7
1286
1287 ``\v`` and ``\f`` added to list of line boundaries.
1288
1289
1290 .. method:: str.startswith(prefix[, start[, end]])
1291
1292 Return ``True`` if string starts with the *prefix*, otherwise return ``False``.
1293 *prefix* can also be a tuple of prefixes to look for. With optional *start*,
1294 test string beginning at that position. With optional *end*, stop comparing
1295 string at that position.
1296
1297 .. versionchanged:: 2.5
1298 Accept tuples as *prefix*.
1299
1300
1301 .. method:: str.strip([chars])
1302
1303 Return a copy of the string with the leading and trailing characters removed.
1304 The *chars* argument is a string specifying the set of characters to be removed.
1305 If omitted or ``None``, the *chars* argument defaults to removing whitespace.
1306 The *chars* argument is not a prefix or suffix; rather, all combinations of its
1307 values are stripped:
1308
1309 >>> ' spacious '.strip()
1310 'spacious'
1311 >>> 'www.example.com'.strip('cmowz.')
1312 'example'
1313
1314 .. versionchanged:: 2.2.2
1315 Support for the *chars* argument.
1316
1317
1318 .. method:: str.swapcase()
1319
1320 Return a copy of the string with uppercase characters converted to lowercase and
1321 vice versa.
1322
1323 For 8-bit strings, this method is locale-dependent.
1324
1325
1326 .. method:: str.title()
1327
1328 Return a titlecased version of the string where words start with an uppercase
1329 character and the remaining characters are lowercase.
1330
1331 The algorithm uses a simple language-independent definition of a word as
1332 groups of consecutive letters. The definition works in many contexts but
1333 it means that apostrophes in contractions and possessives form word
1334 boundaries, which may not be the desired result::
1335
1336 >>> "they're bill's friends from the UK".title()
1337 "They'Re Bill'S Friends From The Uk"
1338
1339 A workaround for apostrophes can be constructed using regular expressions::
1340
1341 >>> import re
1342 >>> def titlecase(s):
1343 ... return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
1344 ... lambda mo: mo.group(0)[0].upper() +
1345 ... mo.group(0)[1:].lower(),
1346 ... s)
1347 ...
1348 >>> titlecase("they're bill's friends.")
1349 "They're Bill's Friends."
1350
1351 For 8-bit strings, this method is locale-dependent.
1352
1353
1354 .. method:: str.translate(table[, deletechars])
1355
1356 Return a copy of the string where all characters occurring in the optional
1357 argument *deletechars* are removed, and the remaining characters have been
1358 mapped through the given translation table, which must be a string of length
1359 256.
1360
1361 You can use the :func:`~string.maketrans` helper function in the :mod:`string`
1362 module to create a translation table. For string objects, set the *table*
1363 argument to ``None`` for translations that only delete characters:
1364
1365 >>> 'read this short text'.translate(None, 'aeiou')
1366 'rd ths shrt txt'
1367
1368 .. versionadded:: 2.6
1369 Support for a ``None`` *table* argument.
1370
1371 For Unicode objects, the :meth:`translate` method does not accept the optional
1372 *deletechars* argument. Instead, it returns a copy of the *s* where all
1373 characters have been mapped through the given translation table which must be a
1374 mapping of Unicode ordinals to Unicode ordinals, Unicode strings or ``None``.
1375 Unmapped characters are left untouched. Characters mapped to ``None`` are
1376 deleted. Note, a more flexible approach is to create a custom character mapping
1377 codec using the :mod:`codecs` module (see :mod:`encodings.cp1251` for an
1378 example).
1379
1380
1381 .. method:: str.upper()
1382
1383 Return a copy of the string with all the cased characters [4]_ converted to
1384 uppercase. Note that ``s.upper().isupper()`` might be ``False`` if ``s``
1385 contains uncased characters or if the Unicode category of the resulting
1386 character(s) is not "Lu" (Letter, uppercase), but e.g. "Lt" (Letter, titlecase).
1387
1388 For 8-bit strings, this method is locale-dependent.
1389
1390
1391 .. method:: str.zfill(width)
1392
1393 Return the numeric string left filled with zeros in a string of length
1394 *width*. A sign prefix is handled correctly. The original string is
1395 returned if *width* is less than or equal to ``len(s)``.
1396
1397
1398 .. versionadded:: 2.2.2
1399
1400 The following methods are present only on unicode objects:
1401
1402 .. method:: unicode.isnumeric()
1403
1404 Return ``True`` if there are only numeric characters in S, ``False``
1405 otherwise. Numeric characters include digit characters, and all characters
1406 that have the Unicode numeric value property, e.g. U+2155,
1407 VULGAR FRACTION ONE FIFTH.
1408
1409 .. method:: unicode.isdecimal()
1410
1411 Return ``True`` if there are only decimal characters in S, ``False``
1412 otherwise. Decimal characters include digit characters, and all characters
1413 that can be used to form decimal-radix numbers, e.g. U+0660,
1414 ARABIC-INDIC DIGIT ZERO.
1415
1416
1417 .. _string-formatting:
1418
1419 String Formatting Operations
1420 ----------------------------
1421
1422 .. index::
1423 single: formatting, string (%)
1424 single: interpolation, string (%)
1425 single: string; formatting
1426 single: string; interpolation
1427 single: printf-style formatting
1428 single: sprintf-style formatting
1429 single: % formatting
1430 single: % interpolation
1431
1432 String and Unicode objects have one unique built-in operation: the ``%``
1433 operator (modulo). This is also known as the string *formatting* or
1434 *interpolation* operator. Given ``format % values`` (where *format* is a string
1435 or Unicode object), ``%`` conversion specifications in *format* are replaced
1436 with zero or more elements of *values*. The effect is similar to the using
1437 :c:func:`sprintf` in the C language. If *format* is a Unicode object, or if any
1438 of the objects being converted using the ``%s`` conversion are Unicode objects,
1439 the result will also be a Unicode object.
1440
1441 If *format* requires a single argument, *values* may be a single non-tuple
1442 object. [5]_ Otherwise, *values* must be a tuple with exactly the number of
1443 items specified by the format string, or a single mapping object (for example, a
1444 dictionary).
1445
1446 A conversion specifier contains two or more characters and has the following
1447 components, which must occur in this order:
1448
1449 #. The ``'%'`` character, which marks the start of the specifier.
1450
1451 #. Mapping key (optional), consisting of a parenthesised sequence of characters
1452 (for example, ``(somename)``).
1453
1454 #. Conversion flags (optional), which affect the result of some conversion
1455 types.
1456
1457 #. Minimum field width (optional). If specified as an ``'*'`` (asterisk), the
1458 actual width is read from the next element of the tuple in *values*, and the
1459 object to convert comes after the minimum field width and optional precision.
1460
1461 #. Precision (optional), given as a ``'.'`` (dot) followed by the precision. If
1462 specified as ``'*'`` (an asterisk), the actual width is read from the next
1463 element of the tuple in *values*, and the value to convert comes after the
1464 precision.
1465
1466 #. Length modifier (optional).
1467
1468 #. Conversion type.
1469
1470 When the right argument is a dictionary (or other mapping type), then the
1471 formats in the string *must* include a parenthesised mapping key into that
1472 dictionary inserted immediately after the ``'%'`` character. The mapping key
1473 selects the value to be formatted from the mapping. For example:
1474
1475 >>> print '%(language)s has %(number)03d quote types.' % \
1476 ... {"language": "Python", "number": 2}
1477 Python has 002 quote types.
1478
1479 In this case no ``*`` specifiers may occur in a format (since they require a
1480 sequential parameter list).
1481
1482 The conversion flag characters are:
1483
1484 +---------+---------------------------------------------------------------------+
1485 | Flag | Meaning |
1486 +=========+=====================================================================+
1487 | ``'#'`` | The value conversion will use the "alternate form" (where defined |
1488 | | below). |
1489 +---------+---------------------------------------------------------------------+
1490 | ``'0'`` | The conversion will be zero padded for numeric values. |
1491 +---------+---------------------------------------------------------------------+
1492 | ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` |
1493 | | conversion if both are given). |
1494 +---------+---------------------------------------------------------------------+
1495 | ``' '`` | (a space) A blank should be left before a positive number (or empty |
1496 | | string) produced by a signed conversion. |
1497 +---------+---------------------------------------------------------------------+
1498 | ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion |
1499 | | (overrides a "space" flag). |
1500 +---------+---------------------------------------------------------------------+
1501
1502 A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it
1503 is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``.
1504
1505 The conversion types are:
1506
1507 +------------+-----------------------------------------------------+-------+
1508 | Conversion | Meaning | Notes |
1509 +============+=====================================================+=======+
1510 | ``'d'`` | Signed integer decimal. | |
1511 +------------+-----------------------------------------------------+-------+
1512 | ``'i'`` | Signed integer decimal. | |
1513 +------------+-----------------------------------------------------+-------+
1514 | ``'o'`` | Signed octal value. | \(1) |
1515 +------------+-----------------------------------------------------+-------+
1516 | ``'u'`` | Obsolete type -- it is identical to ``'d'``. | \(7) |
1517 +------------+-----------------------------------------------------+-------+
1518 | ``'x'`` | Signed hexadecimal (lowercase). | \(2) |
1519 +------------+-----------------------------------------------------+-------+
1520 | ``'X'`` | Signed hexadecimal (uppercase). | \(2) |
1521 +------------+-----------------------------------------------------+-------+
1522 | ``'e'`` | Floating point exponential format (lowercase). | \(3) |
1523 +------------+-----------------------------------------------------+-------+
1524 | ``'E'`` | Floating point exponential format (uppercase). | \(3) |
1525 +------------+-----------------------------------------------------+-------+
1526 | ``'f'`` | Floating point decimal format. | \(3) |
1527 +------------+-----------------------------------------------------+-------+
1528 | ``'F'`` | Floating point decimal format. | \(3) |
1529 +------------+-----------------------------------------------------+-------+
1530 | ``'g'`` | Floating point format. Uses lowercase exponential | \(4) |
1531 | | format if exponent is less than -4 or not less than | |
1532 | | precision, decimal format otherwise. | |
1533 +------------+-----------------------------------------------------+-------+
1534 | ``'G'`` | Floating point format. Uses uppercase exponential | \(4) |
1535 | | format if exponent is less than -4 or not less than | |
1536 | | precision, decimal format otherwise. | |
1537 +------------+-----------------------------------------------------+-------+
1538 | ``'c'`` | Single character (accepts integer or single | |
1539 | | character string). | |
1540 +------------+-----------------------------------------------------+-------+
1541 | ``'r'`` | String (converts any Python object using | \(5) |
1542 | | :ref:`repr() <func-repr>`). | |
1543 +------------+-----------------------------------------------------+-------+
1544 | ``'s'`` | String (converts any Python object using | \(6) |
1545 | | :func:`str`). | |
1546 +------------+-----------------------------------------------------+-------+
1547 | ``'%'`` | No argument is converted, results in a ``'%'`` | |
1548 | | character in the result. | |
1549 +------------+-----------------------------------------------------+-------+
1550
1551 Notes:
1552
1553 (1)
1554 The alternate form causes a leading zero (``'0'``) to be inserted between
1555 left-hand padding and the formatting of the number if the leading character
1556 of the result is not already a zero.
1557
1558 (2)
1559 The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether
1560 the ``'x'`` or ``'X'`` format was used) to be inserted before the first digit.
1561
1562 (3)
1563 The alternate form causes the result to always contain a decimal point, even if
1564 no digits follow it.
1565
1566 The precision determines the number of digits after the decimal point and
1567 defaults to 6.
1568
1569 (4)
1570 The alternate form causes the result to always contain a decimal point, and
1571 trailing zeroes are not removed as they would otherwise be.
1572
1573 The precision determines the number of significant digits before and after the
1574 decimal point and defaults to 6.
1575
1576 (5)
1577 The ``%r`` conversion was added in Python 2.0.
1578
1579 The precision determines the maximal number of characters used.
1580
1581 (6)
1582 If the object or format provided is a :class:`unicode` string, the resulting
1583 string will also be :class:`unicode`.
1584
1585 The precision determines the maximal number of characters used.
1586
1587 (7)
1588 See :pep:`237`.
1589
1590 Since Python strings have an explicit length, ``%s`` conversions do not assume
1591 that ``'\0'`` is the end of the string.
1592
1593 .. XXX Examples?
1594
1595 .. versionchanged:: 2.7
1596 ``%f`` conversions for numbers whose absolute value is over 1e50 are no
1597 longer replaced by ``%g`` conversions.
1598
1599 .. index::
1600 module: string
1601 module: re
1602
1603 Additional string operations are defined in standard modules :mod:`string` and
1604 :mod:`re`.
1605
1606
1607 .. _typesseq-xrange:
1608
1609 XRange Type
1610 -----------
1611
1612 .. index:: object: xrange
1613
1614 The :class:`xrange` type is an immutable sequence which is commonly used for
1615 looping. The advantage of the :class:`xrange` type is that an :class:`xrange`
1616 object will always take the same amount of memory, no matter the size of the
1617 range it represents. There are no consistent performance advantages.
1618
1619 XRange objects have very little behavior: they only support indexing, iteration,
1620 and the :func:`len` function.
1621
1622
1623 .. _typesseq-mutable:
1624
1625 Mutable Sequence Types
1626 ----------------------
1627
1628 .. index::
1629 triple: mutable; sequence; types
1630 object: list
1631
1632 List and :class:`bytearray` objects support additional operations that allow
1633 in-place modification of the object. Other mutable sequence types (when added
1634 to the language) should also support these operations. Strings and tuples
1635 are immutable sequence types: such objects cannot be modified once created.
1636 The following operations are defined on mutable sequence types (where *x* is
1637 an arbitrary object):
1638
1639 .. index::
1640 triple: operations on; sequence; types
1641 triple: operations on; list; type
1642 pair: subscript; assignment
1643 pair: slice; assignment
1644 pair: extended slice; assignment
1645 statement: del
1646 single: append() (list method)
1647 single: extend() (list method)
1648 single: count() (list method)
1649 single: index() (list method)
1650 single: insert() (list method)
1651 single: pop() (list method)
1652 single: remove() (list method)
1653 single: reverse() (list method)
1654 single: sort() (list method)
1655
1656 +------------------------------+--------------------------------+---------------------+
1657 | Operation | Result | Notes |
1658 +==============================+================================+=====================+
1659 | ``s[i] = x`` | item *i* of *s* is replaced by | |
1660 | | *x* | |
1661 +------------------------------+--------------------------------+---------------------+
1662 | ``s[i:j] = t`` | slice of *s* from *i* to *j* | |
1663 | | is replaced by the contents of | |
1664 | | the iterable *t* | |
1665 +------------------------------+--------------------------------+---------------------+
1666 | ``del s[i:j]`` | same as ``s[i:j] = []`` | |
1667 +------------------------------+--------------------------------+---------------------+
1668 | ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` | \(1) |
1669 | | are replaced by those of *t* | |
1670 +------------------------------+--------------------------------+---------------------+
1671 | ``del s[i:j:k]`` | removes the elements of | |
1672 | | ``s[i:j:k]`` from the list | |
1673 +------------------------------+--------------------------------+---------------------+
1674 | ``s.append(x)`` | same as ``s[len(s):len(s)] = | \(2) |
1675 | | [x]`` | |
1676 +------------------------------+--------------------------------+---------------------+
1677 | ``s.extend(t)`` or | for the most part the same as | \(3) |
1678 | ``s += t`` | ``s[len(s):len(s)] = t`` | |
1679 +------------------------------+--------------------------------+---------------------+
1680 | ``s *= n`` | updates *s* with its contents | \(11) |
1681 | | repeated *n* times | |
1682 +------------------------------+--------------------------------+---------------------+
1683 | ``s.count(x)`` | return number of *i*'s for | |
1684 | | which ``s[i] == x`` | |
1685 +------------------------------+--------------------------------+---------------------+
1686 | ``s.index(x[, i[, j]])`` | return smallest *k* such that | \(4) |
1687 | | ``s[k] == x`` and ``i <= k < | |
1688 | | j`` | |
1689 +------------------------------+--------------------------------+---------------------+
1690 | ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | \(5) |
1691 +------------------------------+--------------------------------+---------------------+
1692 | ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | \(6) |
1693 | | return x`` | |
1694 +------------------------------+--------------------------------+---------------------+
1695 | ``s.remove(x)`` | same as ``del s[s.index(x)]`` | \(4) |
1696 +------------------------------+--------------------------------+---------------------+
1697 | ``s.reverse()`` | reverses the items of *s* in | \(7) |
1698 | | place | |
1699 +------------------------------+--------------------------------+---------------------+
1700 | ``s.sort([cmp[, key[, | sort the items of *s* in place | (7)(8)(9)(10) |
1701 | reverse]]])`` | | |
1702 +------------------------------+--------------------------------+---------------------+
1703
1704 Notes:
1705
1706 (1)
1707 *t* must have the same length as the slice it is replacing.
1708
1709 (2)
1710 The C implementation of Python has historically accepted multiple parameters and
1711 implicitly joined them into a tuple; this no longer works in Python 2.0. Use of
1712 this misfeature has been deprecated since Python 1.4.
1713
1714 (3)
1715 *t* can be any iterable object.
1716
1717 (4)
1718 Raises :exc:`ValueError` when *x* is not found in *s*. When a negative index is
1719 passed as the second or third parameter to the :meth:`index` method, the list
1720 length is added, as for slice indices. If it is still negative, it is truncated
1721 to zero, as for slice indices.
1722
1723 .. versionchanged:: 2.3
1724 Previously, :meth:`index` didn't have arguments for specifying start and stop
1725 positions.
1726
1727 (5)
1728 When a negative index is passed as the first parameter to the :meth:`insert`
1729 method, the list length is added, as for slice indices. If it is still
1730 negative, it is truncated to zero, as for slice indices.
1731
1732 .. versionchanged:: 2.3
1733 Previously, all negative indices were truncated to zero.
1734
1735 (6)
1736 The :meth:`pop` method's optional argument *i* defaults to ``-1``, so that
1737 by default the last item is removed and returned.
1738
1739 (7)
1740 The :meth:`sort` and :meth:`reverse` methods modify the list in place for
1741 economy of space when sorting or reversing a large list. To remind you that
1742 they operate by side effect, they don't return the sorted or reversed list.
1743
1744 (8)
1745 The :meth:`sort` method takes optional arguments for controlling the
1746 comparisons.
1747
1748 *cmp* specifies a custom comparison function of two arguments (list items) which
1749 should return a negative, zero or positive number depending on whether the first
1750 argument is considered smaller than, equal to, or larger than the second
1751 argument: ``cmp=lambda x,y: cmp(x.lower(), y.lower())``. The default value
1752 is ``None``.
1753
1754 *key* specifies a function of one argument that is used to extract a comparison
1755 key from each list element: ``key=str.lower``. The default value is ``None``.
1756
1757 *reverse* is a boolean value. If set to ``True``, then the list elements are
1758 sorted as if each comparison were reversed.
1759
1760 In general, the *key* and *reverse* conversion processes are much faster than
1761 specifying an equivalent *cmp* function. This is because *cmp* is called
1762 multiple times for each list element while *key* and *reverse* touch each
1763 element only once. Use :func:`functools.cmp_to_key` to convert an
1764 old-style *cmp* function to a *key* function.
1765
1766 .. versionchanged:: 2.3
1767 Support for ``None`` as an equivalent to omitting *cmp* was added.
1768
1769 .. versionchanged:: 2.4
1770 Support for *key* and *reverse* was added.
1771
1772 (9)
1773 Starting with Python 2.3, the :meth:`sort` method is guaranteed to be stable. A
1774 sort is stable if it guarantees not to change the relative order of elements
1775 that compare equal --- this is helpful for sorting in multiple passes (for
1776 example, sort by department, then by salary grade).
1777
1778 (10)
1779 .. impl-detail::
1780
1781 While a list is being sorted, the effect of attempting to mutate, or even
1782 inspect, the list is undefined. The C implementation of Python 2.3 and
1783 newer makes the list appear empty for the duration, and raises
1784 :exc:`ValueError` if it can detect that the list has been mutated during a
1785 sort.
1786
1787 (11)
1788 The value *n* is an integer, or an object implementing
1789 :meth:`~object.__index__`. Zero and negative values of *n* clear
1790 the sequence. Items in the sequence are not copied; they are referenced
1791 multiple times, as explained for ``s * n`` under :ref:`typesseq`.
1792
1793
1794 .. _types-set:
1795
1796 Set Types --- :class:`set`, :class:`frozenset`
1797 ==============================================
1798
1799 .. index:: object: set
1800
1801 A :dfn:`set` object is an unordered collection of distinct :term:`hashable` objects.
1802 Common uses include membership testing, removing duplicates from a sequence, and
1803 computing mathematical operations such as intersection, union, difference, and
1804 symmetric difference.
1805 (For other containers see the built in :class:`dict`, :class:`list`,
1806 and :class:`tuple` classes, and the :mod:`collections` module.)
1807
1808
1809 .. versionadded:: 2.4
1810
1811 Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in
1812 set``. Being an unordered collection, sets do not record element position or
1813 order of insertion. Accordingly, sets do not support indexing, slicing, or
1814 other sequence-like behavior.
1815
1816 There are currently two built-in set types, :class:`set` and :class:`frozenset`.
1817 The :class:`set` type is mutable --- the contents can be changed using methods
1818 like :meth:`~set.add` and :meth:`~set.remove`. Since it is mutable, it has no
1819 hash value and cannot be used as either a dictionary key or as an element of
1820 another set. The :class:`frozenset` type is immutable and :term:`hashable` ---
1821 its contents cannot be altered after it is created; it can therefore be used as
1822 a dictionary key or as an element of another set.
1823
1824 As of Python 2.7, non-empty sets (not frozensets) can be created by placing a
1825 comma-separated list of elements within braces, for example: ``{'jack',
1826 'sjoerd'}``, in addition to the :class:`set` constructor.
1827
1828 The constructors for both classes work the same:
1829
1830 .. class:: set([iterable])
1831 frozenset([iterable])
1832
1833 Return a new set or frozenset object whose elements are taken from
1834 *iterable*. The elements of a set must be :term:`hashable`. To
1835 represent sets of sets, the inner sets must be :class:`frozenset`
1836 objects. If *iterable* is not specified, a new empty set is
1837 returned.
1838
1839 Instances of :class:`set` and :class:`frozenset` provide the following
1840 operations:
1841
1842 .. describe:: len(s)
1843
1844 Return the number of elements in set *s* (cardinality of *s*).
1845
1846 .. describe:: x in s
1847
1848 Test *x* for membership in *s*.
1849
1850 .. describe:: x not in s
1851
1852 Test *x* for non-membership in *s*.
1853
1854 .. method:: isdisjoint(other)
1855
1856 Return ``True`` if the set has no elements in common with *other*. Sets are
1857 disjoint if and only if their intersection is the empty set.
1858
1859 .. versionadded:: 2.6
1860
1861 .. method:: issubset(other)
1862 set <= other
1863
1864 Test whether every element in the set is in *other*.
1865
1866 .. method:: set < other
1867
1868 Test whether the set is a proper subset of *other*, that is,
1869 ``set <= other and set != other``.
1870
1871 .. method:: issuperset(other)
1872 set >= other
1873
1874 Test whether every element in *other* is in the set.
1875
1876 .. method:: set > other
1877
1878 Test whether the set is a proper superset of *other*, that is, ``set >=
1879 other and set != other``.
1880
1881 .. method:: union(*others)
1882 set | other | ...
1883
1884 Return a new set with elements from the set and all others.
1885
1886 .. versionchanged:: 2.6
1887 Accepts multiple input iterables.
1888
1889 .. method:: intersection(*others)
1890 set & other & ...
1891
1892 Return a new set with elements common to the set and all others.
1893
1894 .. versionchanged:: 2.6
1895 Accepts multiple input iterables.
1896
1897 .. method:: difference(*others)
1898 set - other - ...
1899
1900 Return a new set with elements in the set that are not in the others.
1901
1902 .. versionchanged:: 2.6
1903 Accepts multiple input iterables.
1904
1905 .. method:: symmetric_difference(other)
1906 set ^ other
1907
1908 Return a new set with elements in either the set or *other* but not both.
1909
1910 .. method:: copy()
1911
1912 Return a shallow copy of the set.
1913
1914
1915 Note, the non-operator versions of :meth:`union`, :meth:`intersection`,
1916 :meth:`difference`, and :meth:`symmetric_difference`, :meth:`issubset`, and
1917 :meth:`issuperset` methods will accept any iterable as an argument. In
1918 contrast, their operator based counterparts require their arguments to be
1919 sets. This precludes error-prone constructions like ``set('abc') & 'cbs'``
1920 in favor of the more readable ``set('abc').intersection('cbs')``.
1921
1922 Both :class:`set` and :class:`frozenset` support set to set comparisons. Two
1923 sets are equal if and only if every element of each set is contained in the
1924 other (each is a subset of the other). A set is less than another set if and
1925 only if the first set is a proper subset of the second set (is a subset, but
1926 is not equal). A set is greater than another set if and only if the first set
1927 is a proper superset of the second set (is a superset, but is not equal).
1928
1929 Instances of :class:`set` are compared to instances of :class:`frozenset`
1930 based on their members. For example, ``set('abc') == frozenset('abc')``
1931 returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``.
1932
1933 The subset and equality comparisons do not generalize to a total ordering
1934 function. For example, any two non-empty disjoint sets are not equal and are not
1935 subsets of each other, so *all* of the following return ``False``: ``a<b``,
1936 ``a==b``, or ``a>b``. Accordingly, sets do not implement the :meth:`__cmp__`
1937 method.
1938
1939 Since sets only define partial ordering (subset relationships), the output of
1940 the :meth:`list.sort` method is undefined for lists of sets.
1941
1942 Set elements, like dictionary keys, must be :term:`hashable`.
1943
1944 Binary operations that mix :class:`set` instances with :class:`frozenset`
1945 return the type of the first operand. For example: ``frozenset('ab') |
1946 set('bc')`` returns an instance of :class:`frozenset`.
1947
1948 The following table lists operations available for :class:`set` that do not
1949 apply to immutable instances of :class:`frozenset`:
1950
1951 .. method:: update(*others)
1952 set |= other | ...
1953
1954 Update the set, adding elements from all others.
1955
1956 .. versionchanged:: 2.6
1957 Accepts multiple input iterables.
1958
1959 .. method:: intersection_update(*others)
1960 set &= other & ...
1961
1962 Update the set, keeping only elements found in it and all others.
1963
1964 .. versionchanged:: 2.6
1965 Accepts multiple input iterables.
1966
1967 .. method:: difference_update(*others)
1968 set -= other | ...
1969
1970 Update the set, removing elements found in others.
1971
1972 .. versionchanged:: 2.6
1973 Accepts multiple input iterables.
1974
1975 .. method:: symmetric_difference_update(other)
1976 set ^= other
1977
1978 Update the set, keeping only elements found in either set, but not in both.
1979
1980 .. method:: add(elem)
1981
1982 Add element *elem* to the set.
1983
1984 .. method:: remove(elem)
1985
1986 Remove element *elem* from the set. Raises :exc:`KeyError` if *elem* is
1987 not contained in the set.
1988
1989 .. method:: discard(elem)
1990
1991 Remove element *elem* from the set if it is present.
1992
1993 .. method:: pop()
1994
1995 Remove and return an arbitrary element from the set. Raises
1996 :exc:`KeyError` if the set is empty.
1997
1998 .. method:: clear()
1999
2000 Remove all elements from the set.
2001
2002
2003 Note, the non-operator versions of the :meth:`update`,
2004 :meth:`intersection_update`, :meth:`difference_update`, and
2005 :meth:`symmetric_difference_update` methods will accept any iterable as an
2006 argument.
2007
2008 Note, the *elem* argument to the :meth:`__contains__`, :meth:`remove`, and
2009 :meth:`discard` methods may be a set. To support searching for an equivalent
2010 frozenset, a temporary one is created from *elem*.
2011
2012
2013 .. seealso::
2014
2015 :ref:`comparison-to-builtin-set`
2016 Differences between the :mod:`sets` module and the built-in set types.
2017
2018
2019 .. _typesmapping:
2020
2021 Mapping Types --- :class:`dict`
2022 ===============================
2023
2024 .. index::
2025 object: mapping
2026 object: dictionary
2027 triple: operations on; mapping; types
2028 triple: operations on; dictionary; type
2029 statement: del
2030 builtin: len
2031
2032 A :term:`mapping` object maps :term:`hashable` values to arbitrary objects.
2033 Mappings are mutable objects. There is currently only one standard mapping
2034 type, the :dfn:`dictionary`. (For other containers see the built in
2035 :class:`list`, :class:`set`, and :class:`tuple` classes, and the
2036 :mod:`collections` module.)
2037
2038 A dictionary's keys are *almost* arbitrary values. Values that are not
2039 :term:`hashable`, that is, values containing lists, dictionaries or other
2040 mutable types (that are compared by value rather than by object identity) may
2041 not be used as keys. Numeric types used for keys obey the normal rules for
2042 numeric comparison: if two numbers compare equal (such as ``1`` and ``1.0``)
2043 then they can be used interchangeably to index the same dictionary entry. (Note
2044 however, that since computers store floating-point numbers as approximations it
2045 is usually unwise to use them as dictionary keys.)
2046
2047 Dictionaries can be created by placing a comma-separated list of ``key: value``
2048 pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098:
2049 'jack', 4127: 'sjoerd'}``, or by the :class:`dict` constructor.
2050
2051 .. class:: dict(**kwarg)
2052 dict(mapping, **kwarg)
2053 dict(iterable, **kwarg)
2054
2055 Return a new dictionary initialized from an optional positional argument
2056 and a possibly empty set of keyword arguments.
2057
2058 If no positional argument is given, an empty dictionary is created.
2059 If a positional argument is given and it is a mapping object, a dictionary
2060 is created with the same key-value pairs as the mapping object. Otherwise,
2061 the positional argument must be an :term:`iterable` object. Each item in
2062 the iterable must itself be an iterable with exactly two objects. The
2063 first object of each item becomes a key in the new dictionary, and the
2064 second object the corresponding value. If a key occurs more than once, the
2065 last value for that key becomes the corresponding value in the new
2066 dictionary.
2067
2068 If keyword arguments are given, the keyword arguments and their values are
2069 added to the dictionary created from the positional argument. If a key
2070 being added is already present, the value from the keyword argument
2071 replaces the value from the positional argument.
2072
2073 To illustrate, the following examples all return a dictionary equal to
2074 ``{"one": 1, "two": 2, "three": 3}``::
2075
2076 >>> a = dict(one=1, two=2, three=3)
2077 >>> b = {'one': 1, 'two': 2, 'three': 3}
2078 >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
2079 >>> d = dict([('two', 2), ('one', 1), ('three', 3)])
2080 >>> e = dict({'three': 3, 'one': 1, 'two': 2})
2081 >>> a == b == c == d == e
2082 True
2083
2084 Providing keyword arguments as in the first example only works for keys that
2085 are valid Python identifiers. Otherwise, any valid keys can be used.
2086
2087 .. versionadded:: 2.2
2088
2089 .. versionchanged:: 2.3
2090 Support for building a dictionary from keyword arguments added.
2091
2092
2093 These are the operations that dictionaries support (and therefore, custom
2094 mapping types should support too):
2095
2096 .. describe:: len(d)
2097
2098 Return the number of items in the dictionary *d*.
2099
2100 .. describe:: d[key]
2101
2102 Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key*
2103 is not in the map.
2104
2105 .. index:: __missing__()
2106
2107 If a subclass of dict defines a method :meth:`__missing__` and *key*
2108 is not present, the ``d[key]`` operation calls that method with the key *key*
2109 as argument. The ``d[key]`` operation then returns or raises whatever is
2110 returned or raised by the ``__missing__(key)`` call.
2111 No other operations or methods invoke :meth:`__missing__`. If
2112 :meth:`__missing__` is not defined, :exc:`KeyError` is raised.
2113 :meth:`__missing__` must be a method; it cannot be an instance variable::
2114
2115 >>> class Counter(dict):
2116 ... def __missing__(self, key):
2117 ... return 0
2118 >>> c = Counter()
2119 >>> c['red']
2120 0
2121 >>> c['red'] += 1
2122 >>> c['red']
2123 1
2124
2125 The example above shows part of the implementation of
2126 :class:`collections.Counter`. A different ``__missing__`` method is used
2127 by :class:`collections.defaultdict`.
2128
2129 .. versionadded:: 2.5
2130 Recognition of __missing__ methods of dict subclasses.
2131
2132 .. describe:: d[key] = value
2133
2134 Set ``d[key]`` to *value*.
2135
2136 .. describe:: del d[key]
2137
2138 Remove ``d[key]`` from *d*. Raises a :exc:`KeyError` if *key* is not in the
2139 map.
2140
2141 .. describe:: key in d
2142
2143 Return ``True`` if *d* has a key *key*, else ``False``.
2144
2145 .. versionadded:: 2.2
2146
2147 .. describe:: key not in d
2148
2149 Equivalent to ``not key in d``.
2150
2151 .. versionadded:: 2.2
2152
2153 .. describe:: iter(d)
2154
2155 Return an iterator over the keys of the dictionary. This is a shortcut
2156 for :meth:`iterkeys`.
2157
2158 .. method:: clear()
2159
2160 Remove all items from the dictionary.
2161
2162 .. method:: copy()
2163
2164 Return a shallow copy of the dictionary.
2165
2166 .. method:: fromkeys(seq[, value])
2167
2168 Create a new dictionary with keys from *seq* and values set to *value*.
2169
2170 :func:`fromkeys` is a class method that returns a new dictionary. *value*
2171 defaults to ``None``.
2172
2173 .. versionadded:: 2.3
2174
2175 .. method:: get(key[, default])
2176
2177 Return the value for *key* if *key* is in the dictionary, else *default*.
2178 If *default* is not given, it defaults to ``None``, so that this method
2179 never raises a :exc:`KeyError`.
2180
2181 .. method:: has_key(key)
2182
2183 Test for the presence of *key* in the dictionary. :meth:`has_key` is
2184 deprecated in favor of ``key in d``.
2185
2186 .. method:: items()
2187
2188 Return a copy of the dictionary's list of ``(key, value)`` pairs.
2189
2190 .. impl-detail::
2191
2192 Keys and values are listed in an arbitrary order which is non-random,
2193 varies across Python implementations, and depends on the dictionary's
2194 history of insertions and deletions.
2195
2196 If :meth:`items`, :meth:`keys`, :meth:`values`, :meth:`iteritems`,
2197 :meth:`iterkeys`, and :meth:`itervalues` are called with no intervening
2198 modifications to the dictionary, the lists will directly correspond. This
2199 allows the creation of ``(value, key)`` pairs using :func:`zip`: ``pairs =
2200 zip(d.values(), d.keys())``. The same relationship holds for the
2201 :meth:`iterkeys` and :meth:`itervalues` methods: ``pairs =
2202 zip(d.itervalues(), d.iterkeys())`` provides the same value for
2203 ``pairs``. Another way to create the same list is ``pairs = [(v, k) for
2204 (k, v) in d.iteritems()]``.
2205
2206 .. method:: iteritems()
2207
2208 Return an iterator over the dictionary's ``(key, value)`` pairs. See the
2209 note for :meth:`dict.items`.
2210
2211 Using :meth:`iteritems` while adding or deleting entries in the dictionary
2212 may raise a :exc:`RuntimeError` or fail to iterate over all entries.
2213
2214 .. versionadded:: 2.2
2215
2216 .. method:: iterkeys()
2217
2218 Return an iterator over the dictionary's keys. See the note for
2219 :meth:`dict.items`.
2220
2221 Using :meth:`iterkeys` while adding or deleting entries in the dictionary
2222 may raise a :exc:`RuntimeError` or fail to iterate over all entries.
2223
2224 .. versionadded:: 2.2
2225
2226 .. method:: itervalues()
2227
2228 Return an iterator over the dictionary's values. See the note for
2229 :meth:`dict.items`.
2230
2231 Using :meth:`itervalues` while adding or deleting entries in the
2232 dictionary may raise a :exc:`RuntimeError` or fail to iterate over all
2233 entries.
2234
2235 .. versionadded:: 2.2
2236
2237 .. method:: keys()
2238
2239 Return a copy of the dictionary's list of keys. See the note for
2240 :meth:`dict.items`.
2241
2242 .. method:: pop(key[, default])
2243
2244 If *key* is in the dictionary, remove it and return its value, else return
2245 *default*. If *default* is not given and *key* is not in the dictionary,
2246 a :exc:`KeyError` is raised.
2247
2248 .. versionadded:: 2.3
2249
2250 .. method:: popitem()
2251
2252 Remove and return an arbitrary ``(key, value)`` pair from the dictionary.
2253
2254 :func:`popitem` is useful to destructively iterate over a dictionary, as
2255 often used in set algorithms. If the dictionary is empty, calling
2256 :func:`popitem` raises a :exc:`KeyError`.
2257
2258 .. method:: setdefault(key[, default])
2259
2260 If *key* is in the dictionary, return its value. If not, insert *key*
2261 with a value of *default* and return *default*. *default* defaults to
2262 ``None``.
2263
2264 .. method:: update([other])
2265
2266 Update the dictionary with the key/value pairs from *other*, overwriting
2267 existing keys. Return ``None``.
2268
2269 :func:`update` accepts either another dictionary object or an iterable of
2270 key/value pairs (as tuples or other iterables of length two). If keyword
2271 arguments are specified, the dictionary is then updated with those
2272 key/value pairs: ``d.update(red=1, blue=2)``.
2273
2274 .. versionchanged:: 2.4
2275 Allowed the argument to be an iterable of key/value pairs and allowed
2276 keyword arguments.
2277
2278 .. method:: values()
2279
2280 Return a copy of the dictionary's list of values. See the note for
2281 :meth:`dict.items`.
2282
2283 .. method:: viewitems()
2284
2285 Return a new view of the dictionary's items (``(key, value)`` pairs). See
2286 below for documentation of view objects.
2287
2288 .. versionadded:: 2.7
2289
2290 .. method:: viewkeys()
2291
2292 Return a new view of the dictionary's keys. See below for documentation of
2293 view objects.
2294
2295 .. versionadded:: 2.7
2296
2297 .. method:: viewvalues()
2298
2299 Return a new view of the dictionary's values. See below for documentation of
2300 view objects.
2301
2302 .. versionadded:: 2.7
2303
2304 Dictionaries compare equal if and only if they have the same ``(key,
2305 value)`` pairs.
2306
2307
2308 .. _dict-views:
2309
2310 Dictionary view objects
2311 -----------------------
2312
2313 The objects returned by :meth:`dict.viewkeys`, :meth:`dict.viewvalues` and
2314 :meth:`dict.viewitems` are *view objects*. They provide a dynamic view on the
2315 dictionary's entries, which means that when the dictionary changes, the view
2316 reflects these changes.
2317
2318 Dictionary views can be iterated over to yield their respective data, and
2319 support membership tests:
2320
2321 .. describe:: len(dictview)
2322
2323 Return the number of entries in the dictionary.
2324
2325 .. describe:: iter(dictview)
2326
2327 Return an iterator over the keys, values or items (represented as tuples of
2328 ``(key, value)``) in the dictionary.
2329
2330 Keys and values are iterated over in an arbitrary order which is non-random,
2331 varies across Python implementations, and depends on the dictionary's history
2332 of insertions and deletions. If keys, values and items views are iterated
2333 over with no intervening modifications to the dictionary, the order of items
2334 will directly correspond. This allows the creation of ``(value, key)`` pairs
2335 using :func:`zip`: ``pairs = zip(d.values(), d.keys())``. Another way to
2336 create the same list is ``pairs = [(v, k) for (k, v) in d.items()]``.
2337
2338 Iterating views while adding or deleting entries in the dictionary may raise
2339 a :exc:`RuntimeError` or fail to iterate over all entries.
2340
2341 .. describe:: x in dictview
2342
2343 Return ``True`` if *x* is in the underlying dictionary's keys, values or
2344 items (in the latter case, *x* should be a ``(key, value)`` tuple).
2345
2346
2347 Keys views are set-like since their entries are unique and hashable. If all
2348 values are hashable, so that (key, value) pairs are unique and hashable, then
2349 the items view is also set-like. (Values views are not treated as set-like
2350 since the entries are generally not unique.) Then these set operations are
2351 available ("other" refers either to another view or a set):
2352
2353 .. describe:: dictview & other
2354
2355 Return the intersection of the dictview and the other object as a new set.
2356
2357 .. describe:: dictview | other
2358
2359 Return the union of the dictview and the other object as a new set.
2360
2361 .. describe:: dictview - other
2362
2363 Return the difference between the dictview and the other object (all elements
2364 in *dictview* that aren't in *other*) as a new set.
2365
2366 .. describe:: dictview ^ other
2367
2368 Return the symmetric difference (all elements either in *dictview* or
2369 *other*, but not in both) of the dictview and the other object as a new set.
2370
2371
2372 An example of dictionary view usage::
2373
2374 >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
2375 >>> keys = dishes.viewkeys()
2376 >>> values = dishes.viewvalues()
2377
2378 >>> # iteration
2379 >>> n = 0
2380 >>> for val in values:
2381 ... n += val
2382 >>> print(n)
2383 504
2384
2385 >>> # keys and values are iterated over in the same order
2386 >>> list(keys)
2387 ['eggs', 'bacon', 'sausage', 'spam']
2388 >>> list(values)
2389 [2, 1, 1, 500]
2390
2391 >>> # view objects are dynamic and reflect dict changes
2392 >>> del dishes['eggs']
2393 >>> del dishes['sausage']
2394 >>> list(keys)
2395 ['spam', 'bacon']
2396
2397 >>> # set operations
2398 >>> keys & {'eggs', 'bacon', 'salad'}
2399 {'bacon'}
2400
2401
2402 .. _bltin-file-objects:
2403
2404 File Objects
2405 ============
2406
2407 .. index::
2408 object: file
2409 builtin: file
2410 module: os
2411 module: socket
2412
2413 File objects are implemented using C's ``stdio`` package and can be
2414 created with the built-in :func:`open` function. File
2415 objects are also returned by some other built-in functions and methods,
2416 such as :func:`os.popen` and :func:`os.fdopen` and the :meth:`makefile`
2417 method of socket objects. Temporary files can be created using the
2418 :mod:`tempfile` module, and high-level file operations such as copying,
2419 moving, and deleting files and directories can be achieved with the
2420 :mod:`shutil` module.
2421
2422 When a file operation fails for an I/O-related reason, the exception
2423 :exc:`IOError` is raised. This includes situations where the operation is not
2424 defined for some reason, like :meth:`seek` on a tty device or writing a file
2425 opened for reading.
2426
2427 Files have the following methods:
2428
2429
2430 .. method:: file.close()
2431
2432 Close the file. A closed file cannot be read or written any more. Any operation
2433 which requires that the file be open will raise a :exc:`ValueError` after the
2434 file has been closed. Calling :meth:`close` more than once is allowed.
2435
2436 As of Python 2.5, you can avoid having to call this method explicitly if you use
2437 the :keyword:`with` statement. For example, the following code will
2438 automatically close *f* when the :keyword:`with` block is exited::
2439
2440 from __future__ import with_statement # This isn't required in Python 2.6
2441
2442 with open("hello.txt") as f:
2443 for line in f:
2444 print line,
2445
2446 In older versions of Python, you would have needed to do this to get the same
2447 effect::
2448
2449 f = open("hello.txt")
2450 try:
2451 for line in f:
2452 print line,
2453 finally:
2454 f.close()
2455
2456 .. note::
2457
2458 Not all "file-like" types in Python support use as a context manager for the
2459 :keyword:`with` statement. If your code is intended to work with any file-like
2460 object, you can use the function :func:`contextlib.closing` instead of using
2461 the object directly.
2462
2463
2464 .. method:: file.flush()
2465
2466 Flush the internal buffer, like ``stdio``'s :c:func:`fflush`. This may be a
2467 no-op on some file-like objects.
2468
2469 .. note::
2470
2471 :meth:`flush` does not necessarily write the file's data to disk. Use
2472 :meth:`flush` followed by :func:`os.fsync` to ensure this behavior.
2473
2474
2475 .. method:: file.fileno()
2476
2477 .. index::
2478 pair: file; descriptor
2479 module: fcntl
2480
2481 Return the integer "file descriptor" that is used by the underlying
2482 implementation to request I/O operations from the operating system. This can be
2483 useful for other, lower level interfaces that use file descriptors, such as the
2484 :mod:`fcntl` module or :func:`os.read` and friends.
2485
2486 .. note::
2487
2488 File-like objects which do not have a real file descriptor should *not* provide
2489 this method!
2490
2491
2492 .. method:: file.isatty()
2493
2494 Return ``True`` if the file is connected to a tty(-like) device, else ``False``.
2495
2496 .. note::
2497
2498 If a file-like object is not associated with a real file, this method should
2499 *not* be implemented.
2500
2501
2502 .. method:: file.next()
2503
2504 A file object is its own iterator, for example ``iter(f)`` returns *f* (unless
2505 *f* is closed). When a file is used as an iterator, typically in a
2506 :keyword:`for` loop (for example, ``for line in f: print line.strip()``), the
2507 :meth:`~file.next` method is called repeatedly. This method returns the next input
2508 line, or raises :exc:`StopIteration` when EOF is hit when the file is open for
2509 reading (behavior is undefined when the file is open for writing). In order to
2510 make a :keyword:`for` loop the most efficient way of looping over the lines of a
2511 file (a very common operation), the :meth:`~file.next` method uses a hidden read-ahead
2512 buffer. As a consequence of using a read-ahead buffer, combining :meth:`~file.next`
2513 with other file methods (like :meth:`~file.readline`) does not work right. However,
2514 using :meth:`seek` to reposition the file to an absolute position will flush the
2515 read-ahead buffer.
2516
2517 .. versionadded:: 2.3
2518
2519
2520 .. method:: file.read([size])
2521
2522 Read at most *size* bytes from the file (less if the read hits EOF before
2523 obtaining *size* bytes). If the *size* argument is negative or omitted, read
2524 all data until EOF is reached. The bytes are returned as a string object. An
2525 empty string is returned when EOF is encountered immediately. (For certain
2526 files, like ttys, it makes sense to continue reading after an EOF is hit.) Note
2527 that this method may call the underlying C function :c:func:`fread` more than
2528 once in an effort to acquire as close to *size* bytes as possible. Also note
2529 that when in non-blocking mode, less data than was requested may be
2530 returned, even if no *size* parameter was given.
2531
2532 .. note::
2533 This function is simply a wrapper for the underlying
2534 :c:func:`fread` C function, and will behave the same in corner cases,
2535 such as whether the EOF value is cached.
2536
2537
2538 .. method:: file.readline([size])
2539
2540 Read one entire line from the file. A trailing newline character is kept in
2541 the string (but may be absent when a file ends with an incomplete line). [6]_
2542 If the *size* argument is present and non-negative, it is a maximum byte
2543 count (including the trailing newline) and an incomplete line may be
2544 returned. When *size* is not 0, an empty string is returned *only* when EOF
2545 is encountered immediately.
2546
2547 .. note::
2548
2549 Unlike ``stdio``'s :c:func:`fgets`, the returned string contains null characters
2550 (``'\0'``) if they occurred in the input.
2551
2552
2553 .. method:: file.readlines([sizehint])
2554
2555 Read until EOF using :meth:`~file.readline` and return a list containing the lines
2556 thus read. If the optional *sizehint* argument is present, instead of
2557 reading up to EOF, whole lines totalling approximately *sizehint* bytes
2558 (possibly after rounding up to an internal buffer size) are read. Objects
2559 implementing a file-like interface may choose to ignore *sizehint* if it
2560 cannot be implemented, or cannot be implemented efficiently.
2561
2562
2563 .. method:: file.xreadlines()
2564
2565 This method returns the same thing as ``iter(f)``.
2566
2567 .. versionadded:: 2.1
2568
2569 .. deprecated:: 2.3
2570 Use ``for line in file`` instead.
2571
2572
2573 .. method:: file.seek(offset[, whence])
2574
2575 Set the file's current position, like ``stdio``'s :c:func:`fseek`. The *whence*
2576 argument is optional and defaults to ``os.SEEK_SET`` or ``0`` (absolute file
2577 positioning); other values are ``os.SEEK_CUR`` or ``1`` (seek relative to the
2578 current position) and ``os.SEEK_END`` or ``2`` (seek relative to the file's
2579 end). There is no return value.
2580
2581 For example, ``f.seek(2, os.SEEK_CUR)`` advances the position by two and
2582 ``f.seek(-3, os.SEEK_END)`` sets the position to the third to last.
2583
2584 Note that if the file is opened for appending
2585 (mode ``'a'`` or ``'a+'``), any :meth:`seek` operations will be undone at the
2586 next write. If the file is only opened for writing in append mode (mode
2587 ``'a'``), this method is essentially a no-op, but it remains useful for files
2588 opened in append mode with reading enabled (mode ``'a+'``). If the file is
2589 opened in text mode (without ``'b'``), only offsets returned by :meth:`tell` are
2590 legal. Use of other offsets causes undefined behavior.
2591
2592 Note that not all file objects are seekable.
2593
2594 .. versionchanged:: 2.6
2595 Passing float values as offset has been deprecated.
2596
2597
2598 .. method:: file.tell()
2599
2600 Return the file's current position, like ``stdio``'s :c:func:`ftell`.
2601
2602 .. note::
2603
2604 On Windows, :meth:`tell` can return illegal values (after an :c:func:`fgets`)
2605 when reading files with Unix-style line-endings. Use binary mode (``'rb'``) to
2606 circumvent this problem.
2607
2608
2609 .. method:: file.truncate([size])
2610
2611 Truncate the file's size. If the optional *size* argument is present, the file
2612 is truncated to (at most) that size. The size defaults to the current position.
2613 The current file position is not changed. Note that if a specified size exceeds
2614 the file's current size, the result is platform-dependent: possibilities
2615 include that the file may remain unchanged, increase to the specified size as if
2616 zero-filled, or increase to the specified size with undefined new content.
2617 Availability: Windows, many Unix variants.
2618
2619
2620 .. method:: file.write(str)
2621
2622 Write a string to the file. There is no return value. Due to buffering, the
2623 string may not actually show up in the file until the :meth:`flush` or
2624 :meth:`close` method is called.
2625
2626
2627 .. method:: file.writelines(sequence)
2628
2629 Write a sequence of strings to the file. The sequence can be any iterable
2630 object producing strings, typically a list of strings. There is no return value.
2631 (The name is intended to match :meth:`readlines`; :meth:`writelines` does not
2632 add line separators.)
2633
2634 Files support the iterator protocol. Each iteration returns the same result as
2635 :meth:`~file.readline`, and iteration ends when the :meth:`~file.readline` method returns
2636 an empty string.
2637
2638 File objects also offer a number of other interesting attributes. These are not
2639 required for file-like objects, but should be implemented if they make sense for
2640 the particular object.
2641
2642
2643 .. attribute:: file.closed
2644
2645 bool indicating the current state of the file object. This is a read-only
2646 attribute; the :meth:`close` method changes the value. It may not be available
2647 on all file-like objects.
2648
2649
2650 .. attribute:: file.encoding
2651
2652 The encoding that this file uses. When Unicode strings are written to a file,
2653 they will be converted to byte strings using this encoding. In addition, when
2654 the file is connected to a terminal, the attribute gives the encoding that the
2655 terminal is likely to use (that information might be incorrect if the user has
2656 misconfigured the terminal). The attribute is read-only and may not be present
2657 on all file-like objects. It may also be ``None``, in which case the file uses
2658 the system default encoding for converting Unicode strings.
2659
2660 .. versionadded:: 2.3
2661
2662
2663 .. attribute:: file.errors
2664
2665 The Unicode error handler used along with the encoding.
2666
2667 .. versionadded:: 2.6
2668
2669
2670 .. attribute:: file.mode
2671
2672 The I/O mode for the file. If the file was created using the :func:`open`
2673 built-in function, this will be the value of the *mode* parameter. This is a
2674 read-only attribute and may not be present on all file-like objects.
2675
2676
2677 .. attribute:: file.name
2678
2679 If the file object was created using :func:`open`, the name of the file.
2680 Otherwise, some string that indicates the source of the file object, of the
2681 form ``<...>``. This is a read-only attribute and may not be present on all
2682 file-like objects.
2683
2684 .. index::
2685 single: universal newlines; file.newlines attribute
2686
2687
2688 .. attribute:: file.newlines
2689
2690 If Python was built with :term:`universal newlines` enabled (the default) this
2691 read-only attribute exists, and for files opened in universal newline read
2692 mode it keeps track of the types of newlines encountered while reading the
2693 file. The values it can take are ``'\r'``, ``'\n'``, ``'\r\n'``, ``None``
2694 (unknown, no newlines read yet) or a tuple containing all the newline types
2695 seen, to indicate that multiple newline conventions were encountered. For
2696 files not opened in universal newlines read mode the value of this attribute
2697 will be ``None``.
2698
2699
2700 .. attribute:: file.softspace
2701
2702 Boolean that indicates whether a space character needs to be printed before
2703 another value when using the :keyword:`print` statement. Classes that are trying
2704 to simulate a file object should also have a writable :attr:`softspace`
2705 attribute, which should be initialized to zero. This will be automatic for most
2706 classes implemented in Python (care may be needed for objects that override
2707 attribute access); types implemented in C will have to provide a writable
2708 :attr:`softspace` attribute.
2709
2710 .. note::
2711
2712 This attribute is not used to control the :keyword:`print` statement, but to
2713 allow the implementation of :keyword:`print` to keep track of its internal
2714 state.
2715
2716
2717 .. _typememoryview:
2718
2719 memoryview type
2720 ===============
2721
2722 .. versionadded:: 2.7
2723
2724 :class:`memoryview` objects allow Python code to access the internal data
2725 of an object that supports the buffer protocol without copying. Memory
2726 is generally interpreted as simple bytes.
2727
2728 .. class:: memoryview(obj)
2729
2730 Create a :class:`memoryview` that references *obj*. *obj* must support the
2731 buffer protocol. Built-in objects that support the buffer protocol include
2732 :class:`str` and :class:`bytearray` (but not :class:`unicode`).
2733
2734 A :class:`memoryview` has the notion of an *element*, which is the
2735 atomic memory unit handled by the originating object *obj*. For many
2736 simple types such as :class:`str` and :class:`bytearray`, an element
2737 is a single byte, but other third-party types may expose larger elements.
2738
2739 ``len(view)`` returns the total number of elements in the memoryview,
2740 *view*. The :class:`~memoryview.itemsize` attribute will give you the
2741 number of bytes in a single element.
2742
2743 A :class:`memoryview` supports slicing to expose its data. Taking a single
2744 index will return a single element as a :class:`str` object. Full
2745 slicing will result in a subview::
2746
2747 >>> v = memoryview('abcefg')
2748 >>> v[1]
2749 'b'
2750 >>> v[-1]
2751 'g'
2752 >>> v[1:4]
2753 <memory at 0x77ab28>
2754 >>> v[1:4].tobytes()
2755 'bce'
2756
2757 If the object the memoryview is over supports changing its data, the
2758 memoryview supports slice assignment::
2759
2760 >>> data = bytearray('abcefg')
2761 >>> v = memoryview(data)
2762 >>> v.readonly
2763 False
2764 >>> v[0] = 'z'
2765 >>> data
2766 bytearray(b'zbcefg')
2767 >>> v[1:4] = '123'
2768 >>> data
2769 bytearray(b'z123fg')
2770 >>> v[2] = 'spam'
2771 Traceback (most recent call last):
2772 File "<stdin>", line 1, in <module>
2773 ValueError: cannot modify size of memoryview object
2774
2775 Notice how the size of the memoryview object cannot be changed.
2776
2777 :class:`memoryview` has two methods:
2778
2779 .. method:: tobytes()
2780
2781 Return the data in the buffer as a bytestring (an object of class
2782 :class:`str`). ::
2783
2784 >>> m = memoryview("abc")
2785 >>> m.tobytes()
2786 'abc'
2787
2788 .. method:: tolist()
2789
2790 Return the data in the buffer as a list of integers. ::
2791
2792 >>> memoryview("abc").tolist()
2793 [97, 98, 99]
2794
2795 There are also several readonly attributes available:
2796
2797 .. attribute:: format
2798
2799 A string containing the format (in :mod:`struct` module style) for each
2800 element in the view. This defaults to ``'B'``, a simple bytestring.
2801
2802 .. attribute:: itemsize
2803
2804 The size in bytes of each element of the memoryview.
2805
2806 .. attribute:: shape
2807
2808 A tuple of integers the length of :attr:`ndim` giving the shape of the
2809 memory as an N-dimensional array.
2810
2811 .. attribute:: ndim
2812
2813 An integer indicating how many dimensions of a multi-dimensional array the
2814 memory represents.
2815
2816 .. attribute:: strides
2817
2818 A tuple of integers the length of :attr:`ndim` giving the size in bytes to
2819 access each element for each dimension of the array.
2820
2821 .. attribute:: readonly
2822
2823 A bool indicating whether the memory is read only.
2824
2825 .. memoryview.suboffsets isn't documented because it only seems useful for C
2826
2827
2828 .. _typecontextmanager:
2829
2830 Context Manager Types
2831 =====================
2832
2833 .. versionadded:: 2.5
2834
2835 .. index::
2836 single: context manager
2837 single: context management protocol
2838 single: protocol; context management
2839
2840 Python's :keyword:`with` statement supports the concept of a runtime context
2841 defined by a context manager. This is implemented using two separate methods
2842 that allow user-defined classes to define a runtime context that is entered
2843 before the statement body is executed and exited when the statement ends.
2844
2845 The :dfn:`context management protocol` consists of a pair of methods that need
2846 to be provided for a context manager object to define a runtime context:
2847
2848
2849 .. method:: contextmanager.__enter__()
2850
2851 Enter the runtime context and return either this object or another object
2852 related to the runtime context. The value returned by this method is bound to
2853 the identifier in the :keyword:`as` clause of :keyword:`with` statements using
2854 this context manager.
2855
2856 An example of a context manager that returns itself is a file object. File
2857 objects return themselves from __enter__() to allow :func:`open` to be used as
2858 the context expression in a :keyword:`with` statement.
2859
2860 An example of a context manager that returns a related object is the one
2861 returned by :func:`decimal.localcontext`. These managers set the active
2862 decimal context to a copy of the original decimal context and then return the
2863 copy. This allows changes to be made to the current decimal context in the body
2864 of the :keyword:`with` statement without affecting code outside the
2865 :keyword:`with` statement.
2866
2867
2868 .. method:: contextmanager.__exit__(exc_type, exc_val, exc_tb)
2869
2870 Exit the runtime context and return a Boolean flag indicating if any exception
2871 that occurred should be suppressed. If an exception occurred while executing the
2872 body of the :keyword:`with` statement, the arguments contain the exception type,
2873 value and traceback information. Otherwise, all three arguments are ``None``.
2874
2875 Returning a true value from this method will cause the :keyword:`with` statement
2876 to suppress the exception and continue execution with the statement immediately
2877 following the :keyword:`with` statement. Otherwise the exception continues
2878 propagating after this method has finished executing. Exceptions that occur
2879 during execution of this method will replace any exception that occurred in the
2880 body of the :keyword:`with` statement.
2881
2882 The exception passed in should never be reraised explicitly - instead, this
2883 method should return a false value to indicate that the method completed
2884 successfully and does not want to suppress the raised exception. This allows
2885 context management code (such as ``contextlib.nested``) to easily detect whether
2886 or not an :meth:`__exit__` method has actually failed.
2887
2888 Python defines several context managers to support easy thread synchronisation,
2889 prompt closure of files or other objects, and simpler manipulation of the active
2890 decimal arithmetic context. The specific types are not treated specially beyond
2891 their implementation of the context management protocol. See the
2892 :mod:`contextlib` module for some examples.
2893
2894 Python's :term:`generator`\s and the ``contextlib.contextmanager`` :term:`decorator`
2895 provide a convenient way to implement these protocols. If a generator function is
2896 decorated with the ``contextlib.contextmanager`` decorator, it will return a
2897 context manager implementing the necessary :meth:`__enter__` and
2898 :meth:`__exit__` methods, rather than the iterator produced by an undecorated
2899 generator function.
2900
2901 Note that there is no specific slot for any of these methods in the type
2902 structure for Python objects in the Python/C API. Extension types wanting to
2903 define these methods must provide them as a normal Python accessible method.
2904 Compared to the overhead of setting up the runtime context, the overhead of a
2905 single class dictionary lookup is negligible.
2906
2907
2908 .. _typesother:
2909
2910 Other Built-in Types
2911 ====================
2912
2913 The interpreter supports several other kinds of objects. Most of these support
2914 only one or two operations.
2915
2916
2917 .. _typesmodules:
2918
2919 Modules
2920 -------
2921
2922 The only special operation on a module is attribute access: ``m.name``, where
2923 *m* is a module and *name* accesses a name defined in *m*'s symbol table.
2924 Module attributes can be assigned to. (Note that the :keyword:`import`
2925 statement is not, strictly speaking, an operation on a module object; ``import
2926 foo`` does not require a module object named *foo* to exist, rather it requires
2927 an (external) *definition* for a module named *foo* somewhere.)
2928
2929 A special attribute of every module is :attr:`~object.__dict__`. This is the
2930 dictionary containing the module's symbol table. Modifying this dictionary will
2931 actually change the module's symbol table, but direct assignment to the
2932 :attr:`~object.__dict__` attribute is not possible (you can write
2933 ``m.__dict__['a'] = 1``, which defines ``m.a`` to be ``1``, but you can't write
2934 ``m.__dict__ = {}``). Modifying :attr:`~object.__dict__` directly is
2935 not recommended.
2936
2937 Modules built into the interpreter are written like this: ``<module 'sys'
2938 (built-in)>``. If loaded from a file, they are written as ``<module 'os' from
2939 '/usr/local/lib/pythonX.Y/os.pyc'>``.
2940
2941
2942 .. _typesobjects:
2943
2944 Classes and Class Instances
2945 ---------------------------
2946
2947 See :ref:`objects` and :ref:`class` for these.
2948
2949
2950 .. _typesfunctions:
2951
2952 Functions
2953 ---------
2954
2955 Function objects are created by function definitions. The only operation on a
2956 function object is to call it: ``func(argument-list)``.
2957
2958 There are really two flavors of function objects: built-in functions and
2959 user-defined functions. Both support the same operation (to call the function),
2960 but the implementation is different, hence the different object types.
2961
2962 See :ref:`function` for more information.
2963
2964
2965 .. _typesmethods:
2966
2967 Methods
2968 -------
2969
2970 .. index:: object: method
2971
2972 Methods are functions that are called using the attribute notation. There are
2973 two flavors: built-in methods (such as :meth:`append` on lists) and class
2974 instance methods. Built-in methods are described with the types that support
2975 them.
2976
2977 The implementation adds two special read-only attributes to class instance
2978 methods: ``m.im_self`` is the object on which the method operates, and
2979 ``m.im_func`` is the function implementing the method. Calling ``m(arg-1,
2980 arg-2, ..., arg-n)`` is completely equivalent to calling ``m.im_func(m.im_self,
2981 arg-1, arg-2, ..., arg-n)``.
2982
2983 Class instance methods are either *bound* or *unbound*, referring to whether the
2984 method was accessed through an instance or a class, respectively. When a method
2985 is unbound, its ``im_self`` attribute will be ``None`` and if called, an
2986 explicit ``self`` object must be passed as the first argument. In this case,
2987 ``self`` must be an instance of the unbound method's class (or a subclass of
2988 that class), otherwise a :exc:`TypeError` is raised.
2989
2990 Like function objects, methods objects support getting arbitrary attributes.
2991 However, since method attributes are actually stored on the underlying function
2992 object (``meth.im_func``), setting method attributes on either bound or unbound
2993 methods is disallowed. Attempting to set an attribute on a method results in
2994 an :exc:`AttributeError` being raised. In order to set a method attribute, you
2995 need to explicitly set it on the underlying function object::
2996
2997 >>> class C:
2998 ... def method(self):
2999 ... pass
3000 ...
3001 >>> c = C()
3002 >>> c.method.whoami = 'my name is method' # can't set on the method
3003 Traceback (most recent call last):
3004 File "<stdin>", line 1, in <module>
3005 AttributeError: 'instancemethod' object has no attribute 'whoami'
3006 >>> c.method.im_func.whoami = 'my name is method'
3007 >>> c.method.whoami
3008 'my name is method'
3009
3010
3011 See :ref:`types` for more information.
3012
3013
3014 .. index:: object; code, code object
3015
3016 .. _bltin-code-objects:
3017
3018 Code Objects
3019 ------------
3020
3021 .. index::
3022 builtin: compile
3023 single: func_code (function object attribute)
3024
3025 Code objects are used by the implementation to represent "pseudo-compiled"
3026 executable Python code such as a function body. They differ from function
3027 objects because they don't contain a reference to their global execution
3028 environment. Code objects are returned by the built-in :func:`compile` function
3029 and can be extracted from function objects through their :attr:`func_code`
3030 attribute. See also the :mod:`code` module.
3031
3032 .. index::
3033 statement: exec
3034 builtin: eval
3035
3036 A code object can be executed or evaluated by passing it (instead of a source
3037 string) to the :keyword:`exec` statement or the built-in :func:`eval` function.
3038
3039 See :ref:`types` for more information.
3040
3041
3042 .. _bltin-type-objects:
3043
3044 Type Objects
3045 ------------
3046
3047 .. index::
3048 builtin: type
3049 module: types
3050
3051 Type objects represent the various object types. An object's type is accessed
3052 by the built-in function :func:`type`. There are no special operations on
3053 types. The standard module :mod:`types` defines names for all standard built-in
3054 types.
3055
3056 Types are written like this: ``<type 'int'>``.
3057
3058
3059 .. _bltin-null-object:
3060
3061 The Null Object
3062 ---------------
3063
3064 This object is returned by functions that don't explicitly return a value. It
3065 supports no special operations. There is exactly one null object, named
3066 ``None`` (a built-in name).
3067
3068 It is written as ``None``.
3069
3070
3071 .. _bltin-ellipsis-object:
3072
3073 The Ellipsis Object
3074 -------------------
3075
3076 This object is used by extended slice notation (see :ref:`slicings`). It
3077 supports no special operations. There is exactly one ellipsis object, named
3078 :const:`Ellipsis` (a built-in name).
3079
3080 It is written as ``Ellipsis``. When in a subscript, it can also be written as
3081 ``...``, for example ``seq[...]``.
3082
3083
3084 The NotImplemented Object
3085 -------------------------
3086
3087 This object is returned from comparisons and binary operations when they are
3088 asked to operate on types they don't support. See :ref:`comparisons` for more
3089 information.
3090
3091 It is written as ``NotImplemented``.
3092
3093
3094 Boolean Values
3095 --------------
3096
3097 Boolean values are the two constant objects ``False`` and ``True``. They are
3098 used to represent truth values (although other values can also be considered
3099 false or true). In numeric contexts (for example when used as the argument to
3100 an arithmetic operator), they behave like the integers 0 and 1, respectively.
3101 The built-in function :func:`bool` can be used to convert any value to a
3102 Boolean, if the value can be interpreted as a truth value (see section
3103 :ref:`truth` above).
3104
3105 .. index::
3106 single: False
3107 single: True
3108 pair: Boolean; values
3109
3110 They are written as ``False`` and ``True``, respectively.
3111
3112
3113 .. _typesinternal:
3114
3115 Internal Objects
3116 ----------------
3117
3118 See :ref:`types` for this information. It describes stack frame objects,
3119 traceback objects, and slice objects.
3120
3121
3122 .. _specialattrs:
3123
3124 Special Attributes
3125 ==================
3126
3127 The implementation adds a few special read-only attributes to several object
3128 types, where they are relevant. Some of these are not reported by the
3129 :func:`dir` built-in function.
3130
3131
3132 .. attribute:: object.__dict__
3133
3134 A dictionary or other mapping object used to store an object's (writable)
3135 attributes.
3136
3137
3138 .. attribute:: object.__methods__
3139
3140 .. deprecated:: 2.2
3141 Use the built-in function :func:`dir` to get a list of an object's attributes.
3142 This attribute is no longer available.
3143
3144
3145 .. attribute:: object.__members__
3146
3147 .. deprecated:: 2.2
3148 Use the built-in function :func:`dir` to get a list of an object's attributes.
3149 This attribute is no longer available.
3150
3151
3152 .. attribute:: instance.__class__
3153
3154 The class to which a class instance belongs.
3155
3156
3157 .. attribute:: class.__bases__
3158
3159 The tuple of base classes of a class object.
3160
3161
3162 .. attribute:: definition.__name__
3163
3164 The name of the class, type, function, method, descriptor, or
3165 generator instance.
3166
3167
3168 The following attributes are only supported by :term:`new-style class`\ es.
3169
3170 .. attribute:: class.__mro__
3171
3172 This attribute is a tuple of classes that are considered when looking for
3173 base classes during method resolution.
3174
3175
3176 .. method:: class.mro()
3177
3178 This method can be overridden by a metaclass to customize the method
3179 resolution order for its instances. It is called at class instantiation, and
3180 its result is stored in :attr:`~class.__mro__`.
3181
3182
3183 .. method:: class.__subclasses__
3184
3185 Each new-style class keeps a list of weak references to its immediate
3186 subclasses. This method returns a list of all those references still alive.
3187 Example::
3188
3189 >>> int.__subclasses__()
3190 [<type 'bool'>]
3191
3192
3193 .. rubric:: Footnotes
3194
3195 .. [1] Additional information on these special methods may be found in the Python
3196 Reference Manual (:ref:`customization`).
3197
3198 .. [2] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and
3199 similarly for tuples.
3200
3201 .. [3] They must have since the parser can't tell the type of the operands.
3202
3203 .. [4] Cased characters are those with general category property being one of
3204 "Lu" (Letter, uppercase), "Ll" (Letter, lowercase), or "Lt" (Letter, titlecase).
3205
3206 .. [5] To format only a tuple you should therefore provide a singleton tuple whose only
3207 element is the tuple to be formatted.
3208
3209 .. [6] The advantage of leaving the newline on is that returning an empty string is
3210 then an unambiguous EOF indication. It is also possible (in cases where it
3211 might matter, for example, if you want to make an exact copy of a file while
3212 scanning its lines) to tell whether the last line of a file ended in a newline
3213 or not (yes this happens!).