Debian Codegraph @

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 .. index:: pair: built-in; types
14
15 The principal built-in types are numerics, sequences, mappings, classes,
16 instances and exceptions.
17
18 Some collection classes are mutable. The methods that add, subtract, or
19 rearrange their members in place, and don't return a specific item, never return
20 the collection instance itself but ``None``.
21
22 Some operations are supported by several object types; in particular,
23 practically all objects can be compared for equality, tested for truth
24 value, and converted to a string (with the :func:`repr` function or the
25 slightly different :func:`str` function). The latter function is implicitly
26 used when an object is written by the :func:`print` function.
27
28
29 .. _truth:
30
31 Truth Value Testing
32 ===================
33
34 .. index::
35 pair: statement; if
36 pair: statement; while
37 pair: truth; value
38 pair: Boolean; operations
39 single: false
40
41 Any object can be tested for truth value, for use in an :keyword:`if` or
42 :keyword:`while` condition or as operand of the Boolean operations below.
43
44 .. index:: single: true
45
46 By default, an object is considered true unless its class defines either a
47 :meth:`~object.__bool__` method that returns ``False`` or a
48 :meth:`~object.__len__` method that
49 returns zero, when called with the object. [1]_ Here are most of the built-in
50 objects considered false:
51
52 .. index::
53 single: None (Built-in object)
54 single: False (Built-in object)
55
56 * constants defined to be false: ``None`` and ``False``
57
58 * zero of any numeric type: ``0``, ``0.0``, ``0j``, ``Decimal(0)``,
59 ``Fraction(0, 1)``
60
61 * empty sequences and collections: ``''``, ``()``, ``[]``, ``{}``, ``set()``,
62 ``range(0)``
63
64 .. index::
65 pair: operator; or
66 pair: operator; and
67 single: False
68 single: True
69
70 Operations and built-in functions that have a Boolean result always return ``0``
71 or ``False`` for false and ``1`` or ``True`` for true, unless otherwise stated.
72 (Important exception: the Boolean operations ``or`` and ``and`` always return
73 one of their operands.)
74
75
76 .. _boolean:
77
78 Boolean Operations --- :keyword:`!and`, :keyword:`!or`, :keyword:`!not`
79 =======================================================================
80
81 .. index:: pair: Boolean; operations
82
83 These are the Boolean operations, ordered by ascending priority:
84
85 +-------------+---------------------------------+-------+
86 | Operation | Result | Notes |
87 +=============+=================================+=======+
88 | ``x or y`` | if *x* is true, then *x*, else | \(1) |
89 | | *y* | |
90 +-------------+---------------------------------+-------+
91 | ``x and y`` | if *x* is false, then *x*, else | \(2) |
92 | | *y* | |
93 +-------------+---------------------------------+-------+
94 | ``not x`` | if *x* is false, then ``True``, | \(3) |
95 | | else ``False`` | |
96 +-------------+---------------------------------+-------+
97
98 .. index::
99 pair: operator; and
100 pair: operator; or
101 pair: operator; not
102
103 Notes:
104
105 (1)
106 This is a short-circuit operator, so it only evaluates the second
107 argument if the first one is false.
108
109 (2)
110 This is a short-circuit operator, so it only evaluates the second
111 argument if the first one is true.
112
113 (3)
114 ``not`` has a lower priority than non-Boolean operators, so ``not a == b`` is
115 interpreted as ``not (a == b)``, and ``a == not b`` is a syntax error.
116
117
118 .. _stdcomparisons:
119
120 Comparisons
121 ===========
122
123 .. index::
124 pair: chaining; comparisons
125 pair: operator; comparison
126 pair: operator; ==
127 pair: operator; < (less)
128 pair: operator; <=
129 pair: operator; > (greater)
130 pair: operator; >=
131 pair: operator; !=
132 pair: operator; is
133 pair: operator; is not
134
135 There are eight comparison operations in Python. They all have the same
136 priority (which is higher than that of the Boolean operations). Comparisons can
137 be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and
138 y <= z``, except that *y* is evaluated only once (but in both cases *z* is not
139 evaluated at all when ``x < y`` is found to be false).
140
141 This table summarizes the comparison operations:
142
143 +------------+-------------------------+
144 | Operation | Meaning |
145 +============+=========================+
146 | ``<`` | strictly less than |
147 +------------+-------------------------+
148 | ``<=`` | less than or equal |
149 +------------+-------------------------+
150 | ``>`` | strictly greater than |
151 +------------+-------------------------+
152 | ``>=`` | greater than or equal |
153 +------------+-------------------------+
154 | ``==`` | equal |
155 +------------+-------------------------+
156 | ``!=`` | not equal |
157 +------------+-------------------------+
158 | ``is`` | object identity |
159 +------------+-------------------------+
160 | ``is not`` | negated object identity |
161 +------------+-------------------------+
162
163 .. index::
164 pair: object; numeric
165 pair: objects; comparing
166
167 Unless stated otherwise, objects of different types never compare equal.
168 The ``==`` operator is always defined but for some object types (for example,
169 class objects) is equivalent to :keyword:`is`. The ``<``, ``<=``, ``>`` and ``>=``
170 operators are only defined where they make sense; for example, they raise a
171 :exc:`TypeError` exception when one of the arguments is a complex number.
172
173 .. index::
174 single: __eq__() (instance method)
175 single: __ne__() (instance method)
176 single: __lt__() (instance method)
177 single: __le__() (instance method)
178 single: __gt__() (instance method)
179 single: __ge__() (instance method)
180
181 Non-identical instances of a class normally compare as non-equal unless the
182 class defines the :meth:`~object.__eq__` method.
183
184 Instances of a class cannot be ordered with respect to other instances of the
185 same class, or other types of object, unless the class defines enough of the
186 methods :meth:`~object.__lt__`, :meth:`~object.__le__`, :meth:`~object.__gt__`, and
187 :meth:`~object.__ge__` (in general, :meth:`~object.__lt__` and
188 :meth:`~object.__eq__` are sufficient, if you want the conventional meanings of the
189 comparison operators).
190
191 The behavior of the :keyword:`is` and :keyword:`is not` operators cannot be
192 customized; also they can be applied to any two objects and never raise an
193 exception.
194
195 .. index::
196 pair: operator; in
197 pair: operator; not in
198
199 Two more operations with the same syntactic priority, :keyword:`in` and
200 :keyword:`not in`, are supported by types that are :term:`iterable` or
201 implement the :meth:`~object.__contains__` method.
202
203 .. _typesnumeric:
204
205 Numeric Types --- :class:`int`, :class:`float`, :class:`complex`
206 ================================================================
207
208 .. index::
209 pair: object; numeric
210 pair: object; Boolean
211 pair: object; integer
212 pair: object; floating-point
213 pair: object; complex number
214 pair: C; language
215
216 There are three distinct numeric types: :dfn:`integers`, :dfn:`floating-point
217 numbers`, and :dfn:`complex numbers`. In addition, Booleans are a
218 subtype of integers. Integers have unlimited precision. Floating-point
219 numbers are usually implemented using :c:expr:`double` in C; information
220 about the precision and internal representation of floating-point
221 numbers for the machine on which your program is running is available
222 in :data:`sys.float_info`. Complex numbers have a real and imaginary
223 part, which are each a floating-point number. To extract these parts
224 from a complex number *z*, use ``z.real`` and ``z.imag``. (The standard
225 library includes the additional numeric types :mod:`fractions.Fraction`, for
226 rationals, and :mod:`decimal.Decimal`, for floating-point numbers with
227 user-definable precision.)
228
229 .. index::
230 pair: numeric; literals
231 pair: integer; literals
232 pair: floating-point; literals
233 pair: complex number; literals
234 pair: hexadecimal; literals
235 pair: octal; literals
236 pair: binary; literals
237
238 Numbers are created by numeric literals or as the result of built-in functions
239 and operators. Unadorned integer literals (including hex, octal and binary
240 numbers) yield integers. Numeric literals containing a decimal point or an
241 exponent sign yield floating-point numbers. Appending ``'j'`` or ``'J'`` to a
242 numeric literal yields an imaginary number (a complex number with a zero real
243 part) which you can add to an integer or float to get a complex number with real
244 and imaginary parts.
245
246 .. index::
247 single: arithmetic
248 pair: built-in function; int
249 pair: built-in function; float
250 pair: built-in function; complex
251 single: operator; + (plus)
252 single: + (plus); unary operator
253 single: + (plus); binary operator
254 single: operator; - (minus)
255 single: - (minus); unary operator
256 single: - (minus); binary operator
257 pair: operator; * (asterisk)
258 pair: operator; / (slash)
259 pair: operator; //
260 pair: operator; % (percent)
261 pair: operator; **
262
263 Python fully supports mixed arithmetic: when a binary arithmetic operator has
264 operands of different numeric types, the operand with the "narrower" type is
265 widened to that of the other, where integer is narrower than floating point,
266 which is narrower than complex. A comparison between numbers of different types
267 behaves as though the exact values of those numbers were being compared. [2]_
268
269 The constructors :func:`int`, :func:`float`, and
270 :func:`complex` can be used to produce numbers of a specific type.
271
272 All numeric types (except complex) support the following operations (for priorities of
273 the operations, see :ref:`operator-summary`):
274
275 +---------------------+---------------------------------+---------+--------------------+
276 | Operation | Result | Notes | Full documentation |
277 +=====================+=================================+=========+====================+
278 | ``x + y`` | sum of *x* and *y* | | |
279 +---------------------+---------------------------------+---------+--------------------+
280 | ``x - y`` | difference of *x* and *y* | | |
281 +---------------------+---------------------------------+---------+--------------------+
282 | ``x * y`` | product of *x* and *y* | | |
283 +---------------------+---------------------------------+---------+--------------------+
284 | ``x / y`` | quotient of *x* and *y* | | |
285 +---------------------+---------------------------------+---------+--------------------+
286 | ``x // y`` | floored quotient of *x* and | \(1)\(2)| |
287 | | *y* | | |
288 +---------------------+---------------------------------+---------+--------------------+
289 | ``x % y`` | remainder of ``x / y`` | \(2) | |
290 +---------------------+---------------------------------+---------+--------------------+
291 | ``-x`` | *x* negated | | |
292 +---------------------+---------------------------------+---------+--------------------+
293 | ``+x`` | *x* unchanged | | |
294 +---------------------+---------------------------------+---------+--------------------+
295 | ``abs(x)`` | absolute value or magnitude of | | :func:`abs` |
296 | | *x* | | |
297 +---------------------+---------------------------------+---------+--------------------+
298 | ``int(x)`` | *x* converted to integer | \(3)\(6)| :func:`int` |
299 +---------------------+---------------------------------+---------+--------------------+
300 | ``float(x)`` | *x* converted to floating point | \(4)\(6)| :func:`float` |
301 +---------------------+---------------------------------+---------+--------------------+
302 | ``complex(re, im)`` | a complex number with real part | \(6) | :func:`complex` |
303 | | *re*, imaginary part *im*. | | |
304 | | *im* defaults to zero. | | |
305 +---------------------+---------------------------------+---------+--------------------+
306 | ``c.conjugate()`` | conjugate of the complex number | | |
307 | | *c* | | |
308 +---------------------+---------------------------------+---------+--------------------+
309 | ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | \(2) | :func:`divmod` |
310 +---------------------+---------------------------------+---------+--------------------+
311 | ``pow(x, y)`` | *x* to the power *y* | \(5) | :func:`pow` |
312 +---------------------+---------------------------------+---------+--------------------+
313 | ``x ** y`` | *x* to the power *y* | \(5) | |
314 +---------------------+---------------------------------+---------+--------------------+
315
316 .. index::
317 triple: operations on; numeric; types
318 single: conjugate() (complex number method)
319
320 Notes:
321
322 (1)
323 Also referred to as integer division. For operands of type :class:`int`,
324 the result has type :class:`int`. For operands of type :class:`float`,
325 the result has type :class:`float`. In general, the result is a whole
326 integer, though the result's type is not necessarily :class:`int`. The result is
327 always rounded towards minus infinity: ``1//2`` is ``0``, ``(-1)//2`` is
328 ``-1``, ``1//(-2)`` is ``-1``, and ``(-1)//(-2)`` is ``0``.
329
330 (2)
331 Not for complex numbers. Instead convert to floats using :func:`abs` if
332 appropriate.
333
334 (3)
335 .. index::
336 pair: module; math
337 single: floor() (in module math)
338 single: ceil() (in module math)
339 single: trunc() (in module math)
340 pair: numeric; conversions
341
342 Conversion from :class:`float` to :class:`int` truncates, discarding the
343 fractional part. See functions :func:`math.floor` and :func:`math.ceil` for
344 alternative conversions.
345
346 (4)
347 float also accepts the strings "nan" and "inf" with an optional prefix "+"
348 or "-" for Not a Number (NaN) and positive or negative infinity.
349
350 (5)
351 Python defines ``pow(0, 0)`` and ``0 ** 0`` to be ``1``, as is common for
352 programming languages.
353
354 (6)
355 The numeric literals accepted include the digits ``0`` to ``9`` or any
356 Unicode equivalent (code points with the ``Nd`` property).
357
358 See `the Unicode Standard <https://unicode.org/Public/UNIDATA/extracted/DerivedNumericType.txt>`_
359 for a complete list of code points with the ``Nd`` property.
360
361
362 All :class:`numbers.Real` types (:class:`int` and :class:`float`) also include
363 the following operations:
364
365 +--------------------+---------------------------------------------+
366 | Operation | Result |
367 +====================+=============================================+
368 | :func:`math.trunc(\| *x* truncated to :class:`~numbers.Integral` |
369 | x) <math.trunc>` | |
370 +--------------------+---------------------------------------------+
371 | :func:`round(x[, | *x* rounded to *n* digits, |
372 | n]) <round>` | rounding half to even. If *n* is |
373 | | omitted, it defaults to 0. |
374 +--------------------+---------------------------------------------+
375 | :func:`math.floor(\| the greatest :class:`~numbers.Integral` |
376 | x) <math.floor>` | <= *x* |
377 +--------------------+---------------------------------------------+
378 | :func:`math.ceil(x)| the least :class:`~numbers.Integral` >= *x* |
379 | <math.ceil>` | |
380 +--------------------+---------------------------------------------+
381
382 For additional numeric operations see the :mod:`math` and :mod:`cmath`
383 modules.
384
385 .. XXXJH exceptions: overflow (when? what operations?) zerodivision
386
387
388 .. _bitstring-ops:
389
390 Bitwise Operations on Integer Types
391 -----------------------------------
392
393 .. index::
394 triple: operations on; integer; types
395 pair: bitwise; operations
396 pair: shifting; operations
397 pair: masking; operations
398 pair: operator; | (vertical bar)
399 pair: operator; ^ (caret)
400 pair: operator; & (ampersand)
401 pair: operator; <<
402 pair: operator; >>
403 pair: operator; ~ (tilde)
404
405 Bitwise operations only make sense for integers. The result of bitwise
406 operations is calculated as though carried out in two's complement with an
407 infinite number of sign bits.
408
409 The priorities of the binary bitwise operations are all lower than the numeric
410 operations and higher than the comparisons; the unary operation ``~`` has the
411 same priority as the other unary numeric operations (``+`` and ``-``).
412
413 This table lists the bitwise operations sorted in ascending priority:
414
415 +------------+--------------------------------+----------+
416 | Operation | Result | Notes |
417 +============+================================+==========+
418 | ``x | y`` | bitwise :dfn:`or` of *x* and | \(4) |
419 | | *y* | |
420 +------------+--------------------------------+----------+
421 | ``x ^ y`` | bitwise :dfn:`exclusive or` of | \(4) |
422 | | *x* and *y* | |
423 +------------+--------------------------------+----------+
424 | ``x & y`` | bitwise :dfn:`and` of *x* and | \(4) |
425 | | *y* | |
426 +------------+--------------------------------+----------+
427 | ``x << n`` | *x* shifted left by *n* bits | (1)(2) |
428 +------------+--------------------------------+----------+
429 | ``x >> n`` | *x* shifted right by *n* bits | (1)(3) |
430 +------------+--------------------------------+----------+
431 | ``~x`` | the bits of *x* inverted | |
432 +------------+--------------------------------+----------+
433
434 Notes:
435
436 (1)
437 Negative shift counts are illegal and cause a :exc:`ValueError` to be raised.
438
439 (2)
440 A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)``.
441
442 (3)
443 A right shift by *n* bits is equivalent to floor division by ``pow(2, n)``.
444
445 (4)
446 Performing these calculations with at least one extra sign extension bit in
447 a finite two's complement representation (a working bit-width of
448 ``1 + max(x.bit_length(), y.bit_length())`` or more) is sufficient to get the
449 same result as if there were an infinite number of sign bits.
450
451
452 Additional Methods on Integer Types
453 -----------------------------------
454
455 The int type implements the :class:`numbers.Integral` :term:`abstract base
456 class`. In addition, it provides a few more methods:
457
458 .. method:: int.bit_length()
459
460 Return the number of bits necessary to represent an integer in binary,
461 excluding the sign and leading zeros::
462
463 >>> n = -37
464 >>> bin(n)
465 '-0b100101'
466 >>> n.bit_length()
467 6
468
469 More precisely, if ``x`` is nonzero, then ``x.bit_length()`` is the
470 unique positive integer ``k`` such that ``2**(k-1) <= abs(x) < 2**k``.
471 Equivalently, when ``abs(x)`` is small enough to have a correctly
472 rounded logarithm, then ``k = 1 + int(log(abs(x), 2))``.
473 If ``x`` is zero, then ``x.bit_length()`` returns ``0``.
474
475 Equivalent to::
476
477 def bit_length(self):
478 s = bin(self) # binary representation: bin(-37) --> '-0b100101'
479 s = s.lstrip('-0b') # remove leading zeros and minus sign
480 return len(s) # len('100101') --> 6
481
482 .. versionadded:: 3.1
483
484 .. method:: int.bit_count()
485
486 Return the number of ones in the binary representation of the absolute
487 value of the integer. This is also known as the population count.
488 Example::
489
490 >>> n = 19
491 >>> bin(n)
492 '0b10011'
493 >>> n.bit_count()
494 3
495 >>> (-n).bit_count()
496 3
497
498 Equivalent to::
499
500 def bit_count(self):
501 return bin(self).count("1")
502
503 .. versionadded:: 3.10
504
505 .. method:: int.to_bytes(length=1, byteorder='big', *, signed=False)
506
507 Return an array of bytes representing an integer.
508
509 >>> (1024).to_bytes(2, byteorder='big')
510 b'\x04\x00'
511 >>> (1024).to_bytes(10, byteorder='big')
512 b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'
513 >>> (-1024).to_bytes(10, byteorder='big', signed=True)
514 b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
515 >>> x = 1000
516 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little')
517 b'\xe8\x03'
518
519 The integer is represented using *length* bytes, and defaults to 1. An
520 :exc:`OverflowError` is raised if the integer is not representable with
521 the given number of bytes.
522
523 The *byteorder* argument determines the byte order used to represent the
524 integer, and defaults to ``"big"``. If *byteorder* is
525 ``"big"``, the most significant byte is at the beginning of the byte
526 array. If *byteorder* is ``"little"``, the most significant byte is at
527 the end of the byte array.
528
529 The *signed* argument determines whether two's complement is used to
530 represent the integer. If *signed* is ``False`` and a negative integer is
531 given, an :exc:`OverflowError` is raised. The default value for *signed*
532 is ``False``.
533
534 The default values can be used to conveniently turn an integer into a
535 single byte object::
536
537 >>> (65).to_bytes()
538 b'A'
539
540 However, when using the default arguments, don't try
541 to convert a value greater than 255 or you'll get an :exc:`OverflowError`.
542
543 Equivalent to::
544
545 def to_bytes(n, length=1, byteorder='big', signed=False):
546 if byteorder == 'little':
547 order = range(length)
548 elif byteorder == 'big':
549 order = reversed(range(length))
550 else:
551 raise ValueError("byteorder must be either 'little' or 'big'")
552
553 return bytes((n >> i*8) & 0xff for i in order)
554
555 .. versionadded:: 3.2
556 .. versionchanged:: 3.11
557 Added default argument values for ``length`` and ``byteorder``.
558
559 .. classmethod:: int.from_bytes(bytes, byteorder='big', *, signed=False)
560
561 Return the integer represented by the given array of bytes.
562
563 >>> int.from_bytes(b'\x00\x10', byteorder='big')
564 16
565 >>> int.from_bytes(b'\x00\x10', byteorder='little')
566 4096
567 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)
568 -1024
569 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False)
570 64512
571 >>> int.from_bytes([255, 0, 0], byteorder='big')
572 16711680
573
574 The argument *bytes* must either be a :term:`bytes-like object` or an
575 iterable producing bytes.
576
577 The *byteorder* argument determines the byte order used to represent the
578 integer, and defaults to ``"big"``. If *byteorder* is
579 ``"big"``, the most significant byte is at the beginning of the byte
580 array. If *byteorder* is ``"little"``, the most significant byte is at
581 the end of the byte array. To request the native byte order of the host
582 system, use :data:`sys.byteorder` as the byte order value.
583
584 The *signed* argument indicates whether two's complement is used to
585 represent the integer.
586
587 Equivalent to::
588
589 def from_bytes(bytes, byteorder='big', signed=False):
590 if byteorder == 'little':
591 little_ordered = list(bytes)
592 elif byteorder == 'big':
593 little_ordered = list(reversed(bytes))
594 else:
595 raise ValueError("byteorder must be either 'little' or 'big'")
596
597 n = sum(b << i*8 for i, b in enumerate(little_ordered))
598 if signed and little_ordered and (little_ordered[-1] & 0x80):
599 n -= 1 << 8*len(little_ordered)
600
601 return n
602
603 .. versionadded:: 3.2
604 .. versionchanged:: 3.11
605 Added default argument value for ``byteorder``.
606
607 .. method:: int.as_integer_ratio()
608
609 Return a pair of integers whose ratio is equal to the original
610 integer and has a positive denominator. The integer ratio of integers
611 (whole numbers) is always the integer as the numerator and ``1`` as the
612 denominator.
613
614 .. versionadded:: 3.8
615
616 .. method:: int.is_integer()
617
618 Returns ``True``. Exists for duck type compatibility with :meth:`float.is_integer`.
619
620 .. versionadded:: 3.12
621
622 Additional Methods on Float
623 ---------------------------
624
625 The float type implements the :class:`numbers.Real` :term:`abstract base
626 class`. float also has the following additional methods.
627
628 .. method:: float.as_integer_ratio()
629
630 Return a pair of integers whose ratio is exactly equal to the
631 original float. The ratio is in lowest terms and has a positive denominator. Raises
632 :exc:`OverflowError` on infinities and a :exc:`ValueError` on
633 NaNs.
634
635 .. method:: float.is_integer()
636
637 Return ``True`` if the float instance is finite with integral
638 value, and ``False`` otherwise::
639
640 >>> (-2.0).is_integer()
641 True
642 >>> (3.2).is_integer()
643 False
644
645 Two methods support conversion to
646 and from hexadecimal strings. Since Python's floats are stored
647 internally as binary numbers, converting a float to or from a
648 *decimal* string usually involves a small rounding error. In
649 contrast, hexadecimal strings allow exact representation and
650 specification of floating-point numbers. This can be useful when
651 debugging, and in numerical work.
652
653
654 .. method:: float.hex()
655
656 Return a representation of a floating-point number as a hexadecimal
657 string. For finite floating-point numbers, this representation
658 will always include a leading ``0x`` and a trailing ``p`` and
659 exponent.
660
661
662 .. classmethod:: float.fromhex(s)
663
664 Class method to return the float represented by a hexadecimal
665 string *s*. The string *s* may have leading and trailing
666 whitespace.
667
668
669 Note that :meth:`float.hex` is an instance method, while
670 :meth:`float.fromhex` is a class method.
671
672 A hexadecimal string takes the form::
673
674 [sign] ['0x'] integer ['.' fraction] ['p' exponent]
675
676 where the optional ``sign`` may by either ``+`` or ``-``, ``integer``
677 and ``fraction`` are strings of hexadecimal digits, and ``exponent``
678 is a decimal integer with an optional leading sign. Case is not
679 significant, and there must be at least one hexadecimal digit in
680 either the integer or the fraction. This syntax is similar to the
681 syntax specified in section 6.4.4.2 of the C99 standard, and also to
682 the syntax used in Java 1.5 onwards. In particular, the output of
683 :meth:`float.hex` is usable as a hexadecimal floating-point literal in
684 C or Java code, and hexadecimal strings produced by C's ``%a`` format
685 character or Java's ``Double.toHexString`` are accepted by
686 :meth:`float.fromhex`.
687
688
689 Note that the exponent is written in decimal rather than hexadecimal,
690 and that it gives the power of 2 by which to multiply the coefficient.
691 For example, the hexadecimal string ``0x3.a7p10`` represents the
692 floating-point number ``(3 + 10./16 + 7./16**2) * 2.0**10``, or
693 ``3740.0``::
694
695 >>> float.fromhex('0x3.a7p10')
696 3740.0
697
698
699 Applying the reverse conversion to ``3740.0`` gives a different
700 hexadecimal string representing the same number::
701
702 >>> float.hex(3740.0)
703 '0x1.d380000000000p+11'
704
705
706 .. _numeric-hash:
707
708 Hashing of numeric types
709 ------------------------
710
711 For numbers ``x`` and ``y``, possibly of different types, it's a requirement
712 that ``hash(x) == hash(y)`` whenever ``x == y`` (see the :meth:`~object.__hash__`
713 method documentation for more details). For ease of implementation and
714 efficiency across a variety of numeric types (including :class:`int`,
715 :class:`float`, :class:`decimal.Decimal` and :class:`fractions.Fraction`)
716 Python's hash for numeric types is based on a single mathematical function
717 that's defined for any rational number, and hence applies to all instances of
718 :class:`int` and :class:`fractions.Fraction`, and all finite instances of
719 :class:`float` and :class:`decimal.Decimal`. Essentially, this function is
720 given by reduction modulo ``P`` for a fixed prime ``P``. The value of ``P`` is
721 made available to Python as the :attr:`~sys.hash_info.modulus` attribute of
722 :data:`sys.hash_info`.
723
724 .. impl-detail::
725
726 Currently, the prime used is ``P = 2**31 - 1`` on machines with 32-bit C
727 longs and ``P = 2**61 - 1`` on machines with 64-bit C longs.
728
729 Here are the rules in detail:
730
731 - If ``x = m / n`` is a nonnegative rational number and ``n`` is not divisible
732 by ``P``, define ``hash(x)`` as ``m * invmod(n, P) % P``, where ``invmod(n,
733 P)`` gives the inverse of ``n`` modulo ``P``.
734
735 - If ``x = m / n`` is a nonnegative rational number and ``n`` is
736 divisible by ``P`` (but ``m`` is not) then ``n`` has no inverse
737 modulo ``P`` and the rule above doesn't apply; in this case define
738 ``hash(x)`` to be the constant value ``sys.hash_info.inf``.
739
740 - If ``x = m / n`` is a negative rational number define ``hash(x)``
741 as ``-hash(-x)``. If the resulting hash is ``-1``, replace it with
742 ``-2``.
743
744 - The particular values ``sys.hash_info.inf`` and ``-sys.hash_info.inf``
745 are used as hash values for positive
746 infinity or negative infinity (respectively).
747
748 - For a :class:`complex` number ``z``, the hash values of the real
749 and imaginary parts are combined by computing ``hash(z.real) +
750 sys.hash_info.imag * hash(z.imag)``, reduced modulo
751 ``2**sys.hash_info.width`` so that it lies in
752 ``range(-2**(sys.hash_info.width - 1), 2**(sys.hash_info.width -
753 1))``. Again, if the result is ``-1``, it's replaced with ``-2``.
754
755
756 To clarify the above rules, here's some example Python code,
757 equivalent to the built-in hash, for computing the hash of a rational
758 number, :class:`float`, or :class:`complex`::
759
760
761 import sys, math
762
763 def hash_fraction(m, n):
764 """Compute the hash of a rational number m / n.
765
766 Assumes m and n are integers, with n positive.
767 Equivalent to hash(fractions.Fraction(m, n)).
768
769 """
770 P = sys.hash_info.modulus
771 # Remove common factors of P. (Unnecessary if m and n already coprime.)
772 while m % P == n % P == 0:
773 m, n = m // P, n // P
774
775 if n % P == 0:
776 hash_value = sys.hash_info.inf
777 else:
778 # Fermat's Little Theorem: pow(n, P-1, P) is 1, so
779 # pow(n, P-2, P) gives the inverse of n modulo P.
780 hash_value = (abs(m) % P) * pow(n, P - 2, P) % P
781 if m < 0:
782 hash_value = -hash_value
783 if hash_value == -1:
784 hash_value = -2
785 return hash_value
786
787 def hash_float(x):
788 """Compute the hash of a float x."""
789
790 if math.isnan(x):
791 return object.__hash__(x)
792 elif math.isinf(x):
793 return sys.hash_info.inf if x > 0 else -sys.hash_info.inf
794 else:
795 return hash_fraction(*x.as_integer_ratio())
796
797 def hash_complex(z):
798 """Compute the hash of a complex number z."""
799
800 hash_value = hash_float(z.real) + sys.hash_info.imag * hash_float(z.imag)
801 # do a signed reduction modulo 2**sys.hash_info.width
802 M = 2**(sys.hash_info.width - 1)
803 hash_value = (hash_value & (M - 1)) - (hash_value & M)
804 if hash_value == -1:
805 hash_value = -2
806 return hash_value
807
808 .. _bltin-boolean-values:
809 .. _typebool:
810
811 Boolean Type - :class:`bool`
812 ============================
813
814 Booleans represent truth values. The :class:`bool` type has exactly two
815 constant instances: ``True`` and ``False``.
816
817 .. index::
818 single: False
819 single: True
820 pair: Boolean; values
821
822 The built-in function :func:`bool` converts any value to a boolean, if the
823 value can be interpreted as a truth value (see section :ref:`truth` above).
824
825 For logical operations, use the :ref:`boolean operators <boolean>` ``and``,
826 ``or`` and ``not``.
827 When applying the bitwise operators ``&``, ``|``, ``^`` to two booleans, they
828 return a bool equivalent to the logical operations "and", "or", "xor". However,
829 the logical operators ``and``, ``or`` and ``!=`` should be preferred
830 over ``&``, ``|`` and ``^``.
831
832 .. deprecated:: 3.12
833
834 The use of the bitwise inversion operator ``~`` is deprecated and will
835 raise an error in Python 3.16.
836
837 :class:`bool` is a subclass of :class:`int` (see :ref:`typesnumeric`). In
838 many numeric contexts, ``False`` and ``True`` behave like the integers 0 and 1, respectively.
839 However, relying on this is discouraged; explicitly convert using :func:`int`
840 instead.
841
842 .. _typeiter:
843
844 Iterator Types
845 ==============
846
847 .. index::
848 single: iterator protocol
849 single: protocol; iterator
850 single: sequence; iteration
851 single: container; iteration over
852
853 Python supports a concept of iteration over containers. This is implemented
854 using two distinct methods; these are used to allow user-defined classes to
855 support iteration. Sequences, described below in more detail, always support
856 the iteration methods.
857
858 One method needs to be defined for container objects to provide :term:`iterable`
859 support:
860
861 .. XXX duplicated in reference/datamodel!
862
863 .. method:: container.__iter__()
864
865 Return an :term:`iterator` object. The object is required to support the
866 iterator protocol described below. If a container supports different types
867 of iteration, additional methods can be provided to specifically request
868 iterators for those iteration types. (An example of an object supporting
869 multiple forms of iteration would be a tree structure which supports both
870 breadth-first and depth-first traversal.) This method corresponds to the
871 :c:member:`~PyTypeObject.tp_iter` slot of the type structure for Python
872 objects in the Python/C API.
873
874 The iterator objects themselves are required to support the following two
875 methods, which together form the :dfn:`iterator protocol`:
876
877
878 .. method:: iterator.__iter__()
879
880 Return the :term:`iterator` object itself. This is required to allow both
881 containers and iterators to be used with the :keyword:`for` and
882 :keyword:`in` statements. This method corresponds to the
883 :c:member:`~PyTypeObject.tp_iter` slot of the type structure for Python
884 objects in the Python/C API.
885
886
887 .. method:: iterator.__next__()
888
889 Return the next item from the :term:`iterator`. If there are no further
890 items, raise the :exc:`StopIteration` exception. This method corresponds to
891 the :c:member:`~PyTypeObject.tp_iternext` slot of the type structure for
892 Python objects in the Python/C API.
893
894 Python defines several iterator objects to support iteration over general and
895 specific sequence types, dictionaries, and other more specialized forms. The
896 specific types are not important beyond their implementation of the iterator
897 protocol.
898
899 Once an iterator's :meth:`~iterator.__next__` method raises
900 :exc:`StopIteration`, it must continue to do so on subsequent calls.
901 Implementations that do not obey this property are deemed broken.
902
903
904 .. _generator-types:
905
906 Generator Types
907 ---------------
908
909 Python's :term:`generator`\s provide a convenient way to implement the iterator
910 protocol. If a container object's :meth:`~object.__iter__` method is implemented as a
911 generator, it will automatically return an iterator object (technically, a
912 generator object) supplying the :meth:`~iterator.__iter__` and :meth:`~generator.__next__`
913 methods.
914 More information about generators can be found in :ref:`the documentation for
915 the yield expression <yieldexpr>`.
916
917
918 .. _typesseq:
919
920 Sequence Types --- :class:`list`, :class:`tuple`, :class:`range`
921 ================================================================
922
923 There are three basic sequence types: lists, tuples, and range objects.
924 Additional sequence types tailored for processing of
925 :ref:`binary data <binaryseq>` and :ref:`text strings <textseq>` are
926 described in dedicated sections.
927
928
929 .. _typesseq-common:
930
931 Common Sequence Operations
932 --------------------------
933
934 .. index:: pair: object; sequence
935
936 The operations in the following table are supported by most sequence types,
937 both mutable and immutable. The :class:`collections.abc.Sequence` ABC is
938 provided to make it easier to correctly implement these operations on
939 custom sequence types.
940
941 This table lists the sequence operations sorted in ascending priority. In the
942 table, *s* and *t* are sequences of the same type, *n*, *i*, *j* and *k* are
943 integers and *x* is an arbitrary object that meets any type and value
944 restrictions imposed by *s*.
945
946 The ``in`` and ``not in`` operations have the same priorities as the
947 comparison operations. The ``+`` (concatenation) and ``*`` (repetition)
948 operations have the same priority as the corresponding numeric operations. [3]_
949
950 .. index::
951 triple: operations on; sequence; types
952 pair: built-in function; len
953 pair: built-in function; min
954 pair: built-in function; max
955 pair: concatenation; operation
956 pair: repetition; operation
957 pair: subscript; operation
958 pair: slice; operation
959 pair: operator; in
960 pair: operator; not in
961
962 +--------------------------+--------------------------------+----------+
963 | Operation | Result | Notes |
964 +==========================+================================+==========+
965 | ``x in s`` | ``True`` if an item of *s* is | \(1) |
966 | | equal to *x*, else ``False`` | |
967 +--------------------------+--------------------------------+----------+
968 | ``x not in s`` | ``False`` if an item of *s* is | \(1) |
969 | | equal to *x*, else ``True`` | |
970 +--------------------------+--------------------------------+----------+
971 | ``s + t`` | the concatenation of *s* and | (6)(7) |
972 | | *t* | |
973 +--------------------------+--------------------------------+----------+
974 | ``s * n`` or | equivalent to adding *s* to | (2)(7) |
975 | ``n * s`` | itself *n* times | |
976 +--------------------------+--------------------------------+----------+
977 | ``s[i]`` | *i*\ th item of *s*, origin 0 | (3)(8) |
978 +--------------------------+--------------------------------+----------+
979 | ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) |
980 +--------------------------+--------------------------------+----------+
981 | ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) |
982 | | with step *k* | |
983 +--------------------------+--------------------------------+----------+
984 | ``len(s)`` | length of *s* | |
985 +--------------------------+--------------------------------+----------+
986 | ``min(s)`` | smallest item of *s* | |
987 +--------------------------+--------------------------------+----------+
988 | ``max(s)`` | largest item of *s* | |
989 +--------------------------+--------------------------------+----------+
990
991 Sequences of the same type also support comparisons. In particular, tuples
992 and lists are compared lexicographically by comparing corresponding elements.
993 This means that to compare equal, every element must compare equal and the
994 two sequences must be of the same type and have the same length. (For full
995 details see :ref:`comparisons` in the language reference.)
996
997 .. index::
998 single: loop; over mutable sequence
999 single: mutable sequence; loop over
1000
1001 Forward and reversed iterators over mutable sequences access values using an
1002 index. That index will continue to march forward (or backward) even if the
1003 underlying sequence is mutated. The iterator terminates only when an
1004 :exc:`IndexError` or a :exc:`StopIteration` is encountered (or when the index
1005 drops below zero).
1006
1007 Notes:
1008
1009 (1)
1010 While the ``in`` and ``not in`` operations are used only for simple
1011 containment testing in the general case, some specialised sequences
1012 (such as :class:`str`, :class:`bytes` and :class:`bytearray`) also use
1013 them for subsequence testing::
1014
1015 >>> "gg" in "eggs"
1016 True
1017
1018 (2)
1019 Values of *n* less than ``0`` are treated as ``0`` (which yields an empty
1020 sequence of the same type as *s*). Note that items in the sequence *s*
1021 are not copied; they are referenced multiple times. This often haunts
1022 new Python programmers; consider::
1023
1024 >>> lists = [[]] * 3
1025 >>> lists
1026 [[], [], []]
1027 >>> lists[0].append(3)
1028 >>> lists
1029 [[3], [3], [3]]
1030
1031 What has happened is that ``[[]]`` is a one-element list containing an empty
1032 list, so all three elements of ``[[]] * 3`` are references to this single empty
1033 list. Modifying any of the elements of ``lists`` modifies this single list.
1034 You can create a list of different lists this way::
1035
1036 >>> lists = [[] for i in range(3)]
1037 >>> lists[0].append(3)
1038 >>> lists[1].append(5)
1039 >>> lists[2].append(7)
1040 >>> lists
1041 [[3], [5], [7]]
1042
1043 Further explanation is available in the FAQ entry
1044 :ref:`faq-multidimensional-list`.
1045
1046 (3)
1047 If *i* or *j* is negative, the index is relative to the end of sequence *s*:
1048 ``len(s) + i`` or ``len(s) + j`` is substituted. But note that ``-0`` is
1049 still ``0``.
1050
1051 (4)
1052 The slice of *s* from *i* to *j* is defined as the sequence of items with
1053 index *k* such that ``i <= k < j``.
1054
1055 * If *i* is omitted or ``None``, use ``0``.
1056 * If *j* is omitted or ``None``, use ``len(s)``.
1057 * If *i* or *j* is less than ``-len(s)``, use ``0``.
1058 * If *i* or *j* is greater than ``len(s)``, use ``len(s)``.
1059 * If *i* is greater than or equal to *j*, the slice is empty.
1060
1061 (5)
1062 The slice of *s* from *i* to *j* with step *k* is defined as the sequence of
1063 items with index ``x = i + n*k`` such that ``0 <= n < (j-i)/k``. In other words,
1064 the indices are ``i``, ``i+k``, ``i+2*k``, ``i+3*k`` and so on, stopping when
1065 *j* is reached (but never including *j*). When *k* is positive,
1066 *i* and *j* are reduced to ``len(s)`` if they are greater.
1067 When *k* is negative, *i* and *j* are reduced to ``len(s) - 1`` if
1068 they are greater. If *i* or *j* are omitted or ``None``, they become
1069 "end" values (which end depends on the sign of *k*). Note, *k* cannot be zero.
1070 If *k* is ``None``, it is treated like ``1``.
1071
1072 (6)
1073 Concatenating immutable sequences always results in a new object. This
1074 means that building up a sequence by repeated concatenation will have a
1075 quadratic runtime cost in the total sequence length. To get a linear
1076 runtime cost, you must switch to one of the alternatives below:
1077
1078 * if concatenating :class:`str` objects, you can build a list and use
1079 :meth:`str.join` at the end or else write to an :class:`io.StringIO`
1080 instance and retrieve its value when complete
1081
1082 * if concatenating :class:`bytes` objects, you can similarly use
1083 :meth:`bytes.join` or :class:`io.BytesIO`, or you can do in-place
1084 concatenation with a :class:`bytearray` object. :class:`bytearray`
1085 objects are mutable and have an efficient overallocation mechanism
1086
1087 * if concatenating :class:`tuple` objects, extend a :class:`list` instead
1088
1089 * for other types, investigate the relevant class documentation
1090
1091
1092 (7)
1093 Some sequence types (such as :class:`range`) only support item sequences
1094 that follow specific patterns, and hence don't support sequence
1095 concatenation or repetition.
1096
1097 (8)
1098 An :exc:`IndexError` is raised if *i* is outside the sequence range.
1099
1100 .. rubric:: Sequence Methods
1101
1102 Sequence types also support the following methods:
1103
1104 .. method:: list.count(value, /)
1105 range.count(value, /)
1106 tuple.count(value, /)
1107 :no-contents-entry:
1108 :no-index-entry:
1109 :no-typesetting:
1110 .. method:: sequence.count(value, /)
1111
1112 Return the total number of occurrences of *value* in *sequence*.
1113
1114 .. method:: list.index(value[, start[, stop])
1115 range.index(value[, start[, stop])
1116 tuple.index(value[, start[, stop])
1117 :no-contents-entry:
1118 :no-index-entry:
1119 :no-typesetting:
1120 .. method:: sequence.index(value[, start[, stop])
1121
1122 Return the index of the first occurrence of *value* in *sequence*.
1123
1124 Raises :exc:`ValueError` if *value* is not found in *sequence*.
1125
1126 The *start* or *stop* arguments allow for efficient searching
1127 of subsections of the sequence, beginning at *start* and ending at *stop*.
1128 This is roughly equivalent to ``start + sequence[start:stop].index(value)``,
1129 only without copying any data.
1130
1131 .. caution::
1132 Not all sequence types support passing the *start* and *stop* arguments.
1133
1134
1135 .. _typesseq-immutable:
1136
1137 Immutable Sequence Types
1138 ------------------------
1139
1140 .. index::
1141 triple: immutable; sequence; types
1142 pair: object; tuple
1143 pair: built-in function; hash
1144
1145 The only operation that immutable sequence types generally implement that is
1146 not also implemented by mutable sequence types is support for the :func:`hash`
1147 built-in.
1148
1149 This support allows immutable sequences, such as :class:`tuple` instances, to
1150 be used as :class:`dict` keys and stored in :class:`set` and :class:`frozenset`
1151 instances.
1152
1153 Attempting to hash an immutable sequence that contains unhashable values will
1154 result in :exc:`TypeError`.
1155
1156
1157 .. _typesseq-mutable:
1158
1159 Mutable Sequence Types
1160 ----------------------
1161
1162 .. index::
1163 triple: mutable; sequence; types
1164 pair: object; list
1165 pair: object; bytearray
1166
1167 The operations in the following table are defined on mutable sequence types.
1168 The :class:`collections.abc.MutableSequence` ABC is provided to make it
1169 easier to correctly implement these operations on custom sequence types.
1170
1171 In the table *s* is an instance of a mutable sequence type, *t* is any
1172 iterable object and *x* is an arbitrary object that meets any type
1173 and value restrictions imposed by *s* (for example, :class:`bytearray` only
1174 accepts integers that meet the value restriction ``0 <= x <= 255``).
1175
1176
1177 .. index::
1178 triple: operations on; sequence; types
1179 triple: operations on; list; type
1180 pair: subscript; assignment
1181 pair: slice; assignment
1182 pair: statement; del
1183
1184 +------------------------------+--------------------------------+---------------------+
1185 | Operation | Result | Notes |
1186 +==============================+================================+=====================+
1187 | ``s[i] = x`` | item *i* of *s* is replaced by | |
1188 | | *x* | |
1189 +------------------------------+--------------------------------+---------------------+
1190 | ``del s[i]`` | removes item *i* of *s* | |
1191 +------------------------------+--------------------------------+---------------------+
1192 | ``s[i:j] = t`` | slice of *s* from *i* to *j* | |
1193 | | is replaced by the contents of | |
1194 | | the iterable *t* | |
1195 +------------------------------+--------------------------------+---------------------+
1196 | ``del s[i:j]`` | removes the elements of | |
1197 | | ``s[i:j]`` from the list | |
1198 | | (same as ``s[i:j] = []``) | |
1199 +------------------------------+--------------------------------+---------------------+
1200 | ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` | \(1) |
1201 | | are replaced by those of *t* | |
1202 +------------------------------+--------------------------------+---------------------+
1203 | ``del s[i:j:k]`` | removes the elements of | |
1204 | | ``s[i:j:k]`` from the list | |
1205 +------------------------------+--------------------------------+---------------------+
1206 | ``s += t`` | extends *s* with the | |
1207 | | contents of *t* (for the | |
1208 | | most part the same as | |
1209 | | ``s[len(s):len(s)] = t``) | |
1210 +------------------------------+--------------------------------+---------------------+
1211 | ``s *= n`` | updates *s* with its contents | \(2) |
1212 | | repeated *n* times | |
1213 +------------------------------+--------------------------------+---------------------+
1214
1215 Notes:
1216
1217 (1)
1218 If *k* is not equal to ``1``, *t* must have the same length as the slice it is replacing.
1219
1220 (2)
1221 The value *n* is an integer, or an object implementing
1222 :meth:`~object.__index__`. Zero and negative values of *n* clear
1223 the sequence. Items in the sequence are not copied; they are referenced
1224 multiple times, as explained for ``s * n`` under :ref:`typesseq-common`.
1225
1226 .. rubric:: Mutable Sequence Methods
1227
1228 Mutable sequence types also support the following methods:
1229
1230 .. method:: bytearray.append(value, /)
1231 list.append(value, /)
1232 :no-contents-entry:
1233 :no-index-entry:
1234 :no-typesetting:
1235 .. method:: sequence.append(value, /)
1236
1237 Append *value* to the end of the sequence
1238 This is equivalent to writing ``seq[len(seq):len(seq)] = [value]``.
1239
1240 .. method:: bytearray.clear()
1241 list.clear()
1242 :no-contents-entry:
1243 :no-index-entry:
1244 :no-typesetting:
1245 .. method:: sequence.clear()
1246
1247 .. versionadded:: 3.3
1248
1249 Remove all items from *sequence*.
1250 This is equivalent to writing ``del sequence[:]``.
1251
1252 .. method:: bytearray.copy()
1253 list.copy()
1254 :no-contents-entry:
1255 :no-index-entry:
1256 :no-typesetting:
1257 .. method:: sequence.copy()
1258
1259 .. versionadded:: 3.3
1260
1261 Create a shallow copy of *sequence*.
1262 This is equivalent to writing ``sequence[:]``.
1263
1264 .. hint:: The :meth:`!copy` method is not part of the
1265 :class:`~collections.abc.MutableSequence` :class:`~abc.ABC`,
1266 but most concrete mutable sequence types provide it.
1267
1268 .. method:: bytearray.extend(iterable, /)
1269 list.extend(iterable, /)
1270 :no-contents-entry:
1271 :no-index-entry:
1272 :no-typesetting:
1273 .. method:: sequence.extend(iterable, /)
1274
1275 Extend *sequence* with the contents of *iterable*.
1276 For the most part, this is the same as writing
1277 ``seq[len(seq):len(seq)] = iterable``.
1278
1279 .. method:: bytearray.insert(index, value, /)
1280 list.insert(index, value, /)
1281 :no-contents-entry:
1282 :no-index-entry:
1283 :no-typesetting:
1284 .. method:: sequence.insert(index, value, /)
1285
1286 Insert *value* into *sequence* at the given *index*.
1287 This is equivalent to writing ``sequence[index:index] = [value]``.
1288
1289 .. method:: bytearray.pop(index=-1, /)
1290 list.pop(index=-1, /)
1291 :no-contents-entry:
1292 :no-index-entry:
1293 :no-typesetting:
1294 .. method:: sequence.pop(index=-1, /)
1295
1296 Retrieve the item at *index* and also removes it from *sequence*.
1297 By default, the last item in *sequence* is removed and returned.
1298
1299 .. method:: bytearray.remove(value, /)
1300 list.remove(value, /)
1301 :no-contents-entry:
1302 :no-index-entry:
1303 :no-typesetting:
1304 .. method:: sequence.remove(value, /)
1305
1306 Remove the first item from *sequence* where ``sequence[i] == value``.
1307
1308 Raises :exc:`ValueError` if *value* is not found in *sequence*.
1309
1310 .. method:: bytearray.reverse()
1311 list.reverse()
1312 :no-contents-entry:
1313 :no-index-entry:
1314 :no-typesetting:
1315 .. method:: sequence.reverse()
1316
1317 Reverse the items of *sequence* in place.
1318 This method maintains economy of space when reversing a large sequence.
1319 To remind users that it operates by side-effect, it returns ``None``.
1320
1321
1322 .. _typesseq-list:
1323
1324 Lists
1325 -----
1326
1327 .. index:: pair: object; list
1328
1329 Lists are mutable sequences, typically used to store collections of
1330 homogeneous items (where the precise degree of similarity will vary by
1331 application).
1332
1333 .. class:: list(iterable=(), /)
1334
1335 Lists may be constructed in several ways:
1336
1337 * Using a pair of square brackets to denote the empty list: ``[]``
1338 * Using square brackets, separating items with commas: ``[a]``, ``[a, b, c]``
1339 * Using a list comprehension: ``[x for x in iterable]``
1340 * Using the type constructor: ``list()`` or ``list(iterable)``
1341
1342 The constructor builds a list whose items are the same and in the same
1343 order as *iterable*'s items. *iterable* may be either a sequence, a
1344 container that supports iteration, or an iterator object. If *iterable*
1345 is already a list, a copy is made and returned, similar to ``iterable[:]``.
1346 For example, ``list('abc')`` returns ``['a', 'b', 'c']`` and
1347 ``list( (1, 2, 3) )`` returns ``[1, 2, 3]``.
1348 If no argument is given, the constructor creates a new empty list, ``[]``.
1349
1350
1351 Many other operations also produce lists, including the :func:`sorted`
1352 built-in.
1353
1354 Lists implement all of the :ref:`common <typesseq-common>` and
1355 :ref:`mutable <typesseq-mutable>` sequence operations. Lists also provide the
1356 following additional method:
1357
1358 .. method:: list.sort(*, key=None, reverse=False)
1359
1360 This method sorts the list in place, using only ``<`` comparisons
1361 between items. Exceptions are not suppressed - if any comparison operations
1362 fail, the entire sort operation will fail (and the list will likely be left
1363 in a partially modified state).
1364
1365 :meth:`sort` accepts two arguments that can only be passed by keyword
1366 (:ref:`keyword-only arguments <keyword-only_parameter>`):
1367
1368 *key* specifies a function of one argument that is used to extract a
1369 comparison key from each list element (for example, ``key=str.lower``).
1370 The key corresponding to each item in the list is calculated once and
1371 then used for the entire sorting process. The default value of ``None``
1372 means that list items are sorted directly without calculating a separate
1373 key value.
1374
1375 The :func:`functools.cmp_to_key` utility is available to convert a 2.x
1376 style *cmp* function to a *key* function.
1377
1378 *reverse* is a boolean value. If set to ``True``, then the list elements
1379 are sorted as if each comparison were reversed.
1380
1381 This method modifies the sequence in place for economy of space when
1382 sorting a large sequence. To remind users that it operates by side
1383 effect, it does not return the sorted sequence (use :func:`sorted` to
1384 explicitly request a new sorted list instance).
1385
1386 The :meth:`sort` method is guaranteed to be stable. A sort is stable if it
1387 guarantees not to change the relative order of elements that compare equal
1388 --- this is helpful for sorting in multiple passes (for example, sort by
1389 department, then by salary grade).
1390
1391 For sorting examples and a brief sorting tutorial, see :ref:`sortinghowto`.
1392
1393 .. impl-detail::
1394
1395 While a list is being sorted, the effect of attempting to mutate, or even
1396 inspect, the list is undefined. The C implementation of Python makes the
1397 list appear empty for the duration, and raises :exc:`ValueError` if it can
1398 detect that the list has been mutated during a sort.
1399
1400
1401 .. _typesseq-tuple:
1402
1403 Tuples
1404 ------
1405
1406 .. index:: pair: object; tuple
1407
1408 Tuples are immutable sequences, typically used to store collections of
1409 heterogeneous data (such as the 2-tuples produced by the :func:`enumerate`
1410 built-in). Tuples are also used for cases where an immutable sequence of
1411 homogeneous data is needed (such as allowing storage in a :class:`set` or
1412 :class:`dict` instance).
1413
1414 .. class:: tuple(iterable=(), /)
1415
1416 Tuples may be constructed in a number of ways:
1417
1418 * Using a pair of parentheses to denote the empty tuple: ``()``
1419 * Using a trailing comma for a singleton tuple: ``a,`` or ``(a,)``
1420 * Separating items with commas: ``a, b, c`` or ``(a, b, c)``
1421 * Using the :func:`tuple` built-in: ``tuple()`` or ``tuple(iterable)``
1422
1423 The constructor builds a tuple whose items are the same and in the same
1424 order as *iterable*'s items. *iterable* may be either a sequence, a
1425 container that supports iteration, or an iterator object. If *iterable*
1426 is already a tuple, it is returned unchanged. For example,
1427 ``tuple('abc')`` returns ``('a', 'b', 'c')`` and
1428 ``tuple( [1, 2, 3] )`` returns ``(1, 2, 3)``.
1429 If no argument is given, the constructor creates a new empty tuple, ``()``.
1430
1431 Note that it is actually the comma which makes a tuple, not the parentheses.
1432 The parentheses are optional, except in the empty tuple case, or
1433 when they are needed to avoid syntactic ambiguity. For example,
1434 ``f(a, b, c)`` is a function call with three arguments, while
1435 ``f((a, b, c))`` is a function call with a 3-tuple as the sole argument.
1436
1437 Tuples implement all of the :ref:`common <typesseq-common>` sequence
1438 operations.
1439
1440 For heterogeneous collections of data where access by name is clearer than
1441 access by index, :func:`collections.namedtuple` may be a more appropriate
1442 choice than a simple tuple object.
1443
1444
1445 .. _typesseq-range:
1446
1447 Ranges
1448 ------
1449
1450 .. index:: pair: object; range
1451
1452 The :class:`range` type represents an immutable sequence of numbers and is
1453 commonly used for looping a specific number of times in :keyword:`for`
1454 loops.
1455
1456 .. class:: range(stop, /)
1457 range(start, stop, step=1, /)
1458
1459 The arguments to the range constructor must be integers (either built-in
1460 :class:`int` or any object that implements the :meth:`~object.__index__` special
1461 method). If the *step* argument is omitted, it defaults to ``1``.
1462 If the *start* argument is omitted, it defaults to ``0``.
1463 If *step* is zero, :exc:`ValueError` is raised.
1464
1465 For a positive *step*, the contents of a range ``r`` are determined by the
1466 formula ``r[i] = start + step*i`` where ``i >= 0`` and
1467 ``r[i] < stop``.
1468
1469 For a negative *step*, the contents of the range are still determined by
1470 the formula ``r[i] = start + step*i``, but the constraints are ``i >= 0``
1471 and ``r[i] > stop``.
1472
1473 A range object will be empty if ``r[0]`` does not meet the value
1474 constraint. Ranges do support negative indices, but these are interpreted
1475 as indexing from the end of the sequence determined by the positive
1476 indices.
1477
1478 Ranges containing absolute values larger than :data:`sys.maxsize` are
1479 permitted but some features (such as :func:`len`) may raise
1480 :exc:`OverflowError`.
1481
1482 Range examples::
1483
1484 >>> list(range(10))
1485 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1486 >>> list(range(1, 11))
1487 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
1488 >>> list(range(0, 30, 5))
1489 [0, 5, 10, 15, 20, 25]
1490 >>> list(range(0, 10, 3))
1491 [0, 3, 6, 9]
1492 >>> list(range(0, -10, -1))
1493 [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
1494 >>> list(range(0))
1495 []
1496 >>> list(range(1, 0))
1497 []
1498
1499 Ranges implement all of the :ref:`common <typesseq-common>` sequence operations
1500 except concatenation and repetition (due to the fact that range objects can
1501 only represent sequences that follow a strict pattern and repetition and
1502 concatenation will usually violate that pattern).
1503
1504 .. attribute:: start
1505
1506 The value of the *start* parameter (or ``0`` if the parameter was
1507 not supplied)
1508
1509 .. attribute:: stop
1510
1511 The value of the *stop* parameter
1512
1513 .. attribute:: step
1514
1515 The value of the *step* parameter (or ``1`` if the parameter was
1516 not supplied)
1517
1518 The advantage of the :class:`range` type over a regular :class:`list` or
1519 :class:`tuple` is that a :class:`range` object will always take the same
1520 (small) amount of memory, no matter the size of the range it represents (as it
1521 only stores the ``start``, ``stop`` and ``step`` values, calculating individual
1522 items and subranges as needed).
1523
1524 Range objects implement the :class:`collections.abc.Sequence` ABC, and provide
1525 features such as containment tests, element index lookup, slicing and
1526 support for negative indices (see :ref:`typesseq`):
1527
1528 >>> r = range(0, 20, 2)
1529 >>> r
1530 range(0, 20, 2)
1531 >>> 11 in r
1532 False
1533 >>> 10 in r
1534 True
1535 >>> r.index(10)
1536 5
1537 >>> r[5]
1538 10
1539 >>> r[:5]
1540 range(0, 10, 2)
1541 >>> r[-1]
1542 18
1543
1544 Testing range objects for equality with ``==`` and ``!=`` compares
1545 them as sequences. That is, two range objects are considered equal if
1546 they represent the same sequence of values. (Note that two range
1547 objects that compare equal might have different :attr:`~range.start`,
1548 :attr:`~range.stop` and :attr:`~range.step` attributes, for example
1549 ``range(0) == range(2, 1, 3)`` or ``range(0, 3, 2) == range(0, 4, 2)``.)
1550
1551 .. versionchanged:: 3.2
1552 Implement the Sequence ABC.
1553 Support slicing and negative indices.
1554 Test :class:`int` objects for membership in constant time instead of
1555 iterating through all items.
1556
1557 .. versionchanged:: 3.3
1558 Define '==' and '!=' to compare range objects based on the
1559 sequence of values they define (instead of comparing based on
1560 object identity).
1561
1562 Added the :attr:`~range.start`, :attr:`~range.stop` and :attr:`~range.step`
1563 attributes.
1564
1565 .. seealso::
1566
1567 * The `linspace recipe <https://code.activestate.com/recipes/579000-equally-spaced-numbers-linspace/>`_
1568 shows how to implement a lazy version of range suitable for floating-point
1569 applications.
1570
1571 .. index::
1572 single: string; text sequence type
1573 single: str (built-in class); (see also string)
1574 pair: object; string
1575
1576 .. _textseq:
1577
1578 Text Sequence Type --- :class:`str`
1579 ===================================
1580
1581 Textual data in Python is handled with :class:`str` objects, or :dfn:`strings`.
1582 Strings are immutable
1583 :ref:`sequences <typesseq>` of Unicode code points. String literals are
1584 written in a variety of ways:
1585
1586 * Single quotes: ``'allows embedded "double" quotes'``
1587 * Double quotes: ``"allows embedded 'single' quotes"``
1588 * Triple quoted: ``'''Three single quotes'''``, ``"""Three double quotes"""``
1589
1590 Triple quoted strings may span multiple lines - all associated whitespace will
1591 be included in the string literal.
1592
1593 String literals that are part of a single expression and have only whitespace
1594 between them will be implicitly converted to a single string literal. That
1595 is, ``("spam " "eggs") == "spam eggs"``.
1596
1597 See :ref:`strings` for more about the various forms of string literal,
1598 including supported :ref:`escape sequences <escape-sequences>`, and the ``r`` ("raw") prefix that
1599 disables most escape sequence processing.
1600
1601 Strings may also be created from other objects using the :class:`str`
1602 constructor.
1603
1604 Since there is no separate "character" type, indexing a string produces
1605 strings of length 1. That is, for a non-empty string *s*, ``s[0] == s[0:1]``.
1606
1607 .. index::
1608 pair: object; io.StringIO
1609
1610 There is also no mutable string type, but :meth:`str.join` or
1611 :class:`io.StringIO` can be used to efficiently construct strings from
1612 multiple fragments.
1613
1614 .. versionchanged:: 3.3
1615 For backwards compatibility with the Python 2 series, the ``u`` prefix is
1616 once again permitted on string literals. It has no effect on the meaning
1617 of string literals and cannot be combined with the ``r`` prefix.
1618
1619
1620 .. index::
1621 single: string; str (built-in class)
1622
1623 .. class:: str(*, encoding='utf-8', errors='strict')
1624 str(object)
1625 str(object, encoding, errors='strict')
1626 str(object, *, errors)
1627
1628 Return a :ref:`string <textseq>` version of *object*. If *object* is not
1629 provided, returns the empty string. Otherwise, the behavior of ``str()``
1630 depends on whether *encoding* or *errors* is given, as follows.
1631
1632 If neither *encoding* nor *errors* is given, ``str(object)`` returns
1633 :meth:`type(object).__str__(object) <object.__str__>`,
1634 which is the "informal" or nicely
1635 printable string representation of *object*. For string objects, this is
1636 the string itself. If *object* does not have a :meth:`~object.__str__`
1637 method, then :func:`str` falls back to returning
1638 :func:`repr(object) <repr>`.
1639
1640 .. index::
1641 single: buffer protocol; str (built-in class)
1642 single: bytes; str (built-in class)
1643
1644 If at least one of *encoding* or *errors* is given, *object* should be a
1645 :term:`bytes-like object` (e.g. :class:`bytes` or :class:`bytearray`). In
1646 this case, if *object* is a :class:`bytes` (or :class:`bytearray`) object,
1647 then ``str(bytes, encoding, errors)`` is equivalent to
1648 :meth:`bytes.decode(encoding, errors) <bytes.decode>`. Otherwise, the bytes
1649 object underlying the buffer object is obtained before calling
1650 :meth:`bytes.decode`. See :ref:`binaryseq` and
1651 :ref:`bufferobjects` for information on buffer objects.
1652
1653 Passing a :class:`bytes` object to :func:`str` without the *encoding*
1654 or *errors* arguments falls under the first case of returning the informal
1655 string representation (see also the :option:`-b` command-line option to
1656 Python). For example::
1657
1658 >>> str(b'Zoot!')
1659 "b'Zoot!'"
1660
1661 For more information on the ``str`` class and its methods, see
1662 :ref:`textseq` and the :ref:`string-methods` section below. To output
1663 formatted strings, see the :ref:`f-strings` and :ref:`formatstrings`
1664 sections. In addition, see the :ref:`stringservices` section.
1665
1666
1667 .. index::
1668 pair: string; methods
1669
1670 .. _string-methods:
1671
1672 String Methods
1673 --------------
1674
1675 .. index::
1676 pair: module; re
1677
1678 Strings implement all of the :ref:`common <typesseq-common>` sequence
1679 operations, along with the additional methods described below.
1680
1681 Strings also support two styles of string formatting, one providing a large
1682 degree of flexibility and customization (see :meth:`str.format`,
1683 :ref:`formatstrings` and :ref:`string-formatting`) and the other based on C
1684 ``printf`` style formatting that handles a narrower range of types and is
1685 slightly harder to use correctly, but is often faster for the cases it can
1686 handle (:ref:`old-string-formatting`).
1687
1688 The :ref:`textservices` section of the standard library covers a number of
1689 other modules that provide various text related utilities (including regular
1690 expression support in the :mod:`re` module).
1691
1692 .. method:: str.capitalize()
1693
1694 Return a copy of the string with its first character capitalized and the
1695 rest lowercased.
1696
1697 .. versionchanged:: 3.8
1698 The first character is now put into titlecase rather than uppercase.
1699 This means that characters like digraphs will only have their first
1700 letter capitalized, instead of the full character.
1701
1702 .. method:: str.casefold()
1703
1704 Return a casefolded copy of the string. Casefolded strings may be used for
1705 caseless matching.
1706
1707 Casefolding is similar to lowercasing but more aggressive because it is
1708 intended to remove all case distinctions in a string. For example, the German
1709 lowercase letter ``'ß'`` is equivalent to ``"ss"``. Since it is already
1710 lowercase, :meth:`lower` would do nothing to ``'ß'``; :meth:`casefold`
1711 converts it to ``"ss"``.
1712 For example:
1713
1714 .. doctest::
1715
1716 >>> 'straße'.lower()
1717 'straße'
1718 >>> 'straße'.casefold()
1719 'strasse'
1720
1721 The casefolding algorithm is
1722 `described in section 3.13 'Default Case Folding' of the Unicode Standard
1723 <https://www.unicode.org/versions/Unicode15.1.0/ch03.pdf>`__.
1724
1725 .. versionadded:: 3.3
1726
1727
1728 .. method:: str.center(width, fillchar=' ', /)
1729
1730 Return centered in a string of length *width*. Padding is done using the
1731 specified *fillchar* (default is an ASCII space). The original string is
1732 returned if *width* is less than or equal to ``len(s)``. For example::
1733
1734 >>> 'Python'.center(10)
1735 ' Python '
1736 >>> 'Python'.center(10, '-')
1737 '--Python--'
1738 >>> 'Python'.center(4)
1739 'Python'
1740
1741
1742 .. method:: str.count(sub[, start[, end]])
1743
1744 Return the number of non-overlapping occurrences of substring *sub* in the
1745 range [*start*, *end*]. Optional arguments *start* and *end* are
1746 interpreted as in slice notation.
1747
1748 If *sub* is empty, returns the number of empty strings between characters
1749 which is the length of the string plus one. For example::
1750
1751 >>> 'spam, spam, spam'.count('spam')
1752 3
1753 >>> 'spam, spam, spam'.count('spam', 5)
1754 2
1755 >>> 'spam, spam, spam'.count('spam', 5, 10)
1756 1
1757 >>> 'spam, spam, spam'.count('eggs')
1758 0
1759 >>> 'spam, spam, spam'.count('')
1760 17
1761
1762 .. method:: str.encode(encoding="utf-8", errors="strict")
1763
1764 Return the string encoded to :class:`bytes`.
1765
1766 *encoding* defaults to ``'utf-8'``;
1767 see :ref:`standard-encodings` for possible values.
1768
1769 *errors* controls how encoding errors are handled.
1770 If ``'strict'`` (the default), a :exc:`UnicodeError` exception is raised.
1771 Other possible values are ``'ignore'``,
1772 ``'replace'``, ``'xmlcharrefreplace'``, ``'backslashreplace'`` and any
1773 other name registered via :func:`codecs.register_error`.
1774 See :ref:`error-handlers` for details.
1775
1776 For performance reasons, the value of *errors* is not checked for validity
1777 unless an encoding error actually occurs,
1778 :ref:`devmode` is enabled
1779 or a :ref:`debug build <debug-build>` is used.
1780 For example::
1781
1782 >>> encoded_str_to_bytes = 'Python'.encode()
1783 >>> type(encoded_str_to_bytes)
1784 <class 'bytes'>
1785 >>> encoded_str_to_bytes
1786 b'Python'
1787
1788
1789 .. versionchanged:: 3.1
1790 Added support for keyword arguments.
1791
1792 .. versionchanged:: 3.9
1793 The value of the *errors* argument is now checked in :ref:`devmode` and
1794 in :ref:`debug mode <debug-build>`.
1795
1796
1797 .. method:: str.endswith(suffix[, start[, end]])
1798
1799 Return ``True`` if the string ends with the specified *suffix*, otherwise return
1800 ``False``. *suffix* can also be a tuple of suffixes to look for. With optional
1801 *start*, test beginning at that position. With optional *end*, stop comparing
1802 at that position. Using *start* and *end* is equivalent to
1803 ``str[start:end].endswith(suffix)``. For example::
1804
1805 >>> 'Python'.endswith('on')
1806 True
1807 >>> 'a tuple of suffixes'.endswith(('at', 'in'))
1808 False
1809 >>> 'a tuple of suffixes'.endswith(('at', 'es'))
1810 True
1811 >>> 'Python is amazing'.endswith('is', 0, 9)
1812 True
1813
1814 See also :meth:`startswith` and :meth:`removesuffix`.
1815
1816
1817 .. method:: str.expandtabs(tabsize=8)
1818
1819 Return a copy of the string where all tab characters are replaced by one or
1820 more spaces, depending on the current column and the given tab size. Tab
1821 positions occur every *tabsize* characters (default is 8, giving tab
1822 positions at columns 0, 8, 16 and so on). To expand the string, the current
1823 column is set to zero and the string is examined character by character. If
1824 the character is a tab (``\t``), one or more space characters are inserted
1825 in the result until the current column is equal to the next tab position.
1826 (The tab character itself is not copied.) If the character is a newline
1827 (``\n``) or return (``\r``), it is copied and the current column is reset to
1828 zero. Any other character is copied unchanged and the current column is
1829 incremented by one regardless of how the character is represented when
1830 printed. For example::
1831
1832 >>> '01\t012\t0123\t01234'.expandtabs()
1833 '01 012 0123 01234'
1834 >>> '01\t012\t0123\t01234'.expandtabs(4)
1835 '01 012 0123 01234'
1836 >>> print('01\t012\n0123\t01234'.expandtabs(4))
1837 01 012
1838 0123 01234
1839
1840
1841 .. method:: str.find(sub[, start[, end]])
1842
1843 Return the lowest index in the string where substring *sub* is found within
1844 the slice ``s[start:end]``. Optional arguments *start* and *end* are
1845 interpreted as in slice notation. Return ``-1`` if *sub* is not found.
1846 For example::
1847
1848 >>> 'spam, spam, spam'.find('sp')
1849 0
1850 >>> 'spam, spam, spam'.find('sp', 5)
1851 6
1852
1853 See also :meth:`rfind` and :meth:`index`.
1854
1855 .. note::
1856
1857 The :meth:`~str.find` method should be used only if you need to know the
1858 position of *sub*. To check if *sub* is a substring or not, use the
1859 :keyword:`in` operator::
1860
1861 >>> 'Py' in 'Python'
1862 True
1863
1864
1865 .. method:: str.format(*args, **kwargs)
1866
1867 Perform a string formatting operation. The string on which this method is
1868 called can contain literal text or replacement fields delimited by braces
1869 ``{}``. Each replacement field contains either the numeric index of a
1870 positional argument, or the name of a keyword argument. Returns a copy of
1871 the string where each replacement field is replaced with the string value of
1872 the corresponding argument. For example:
1873
1874 .. doctest::
1875
1876 >>> "The sum of 1 + 2 is {0}".format(1+2)
1877 'The sum of 1 + 2 is 3'
1878 >>> "The sum of {a} + {b} is {answer}".format(answer=1+2, a=1, b=2)
1879 'The sum of 1 + 2 is 3'
1880 >>> "{1} expects the {0} Inquisition!".format("Spanish", "Nobody")
1881 'Nobody expects the Spanish Inquisition!'
1882
1883 See :ref:`formatstrings` for a description of the various formatting options
1884 that can be specified in format strings.
1885
1886 .. note::
1887 When formatting a number (:class:`int`, :class:`float`, :class:`complex`,
1888 :class:`decimal.Decimal` and subclasses) with the ``n`` type
1889 (ex: ``'{:n}'.format(1234)``), the function temporarily sets the
1890 ``LC_CTYPE`` locale to the ``LC_NUMERIC`` locale to decode
1891 ``decimal_point`` and ``thousands_sep`` fields of :c:func:`localeconv` if
1892 they are non-ASCII or longer than 1 byte, and the ``LC_NUMERIC`` locale is
1893 different than the ``LC_CTYPE`` locale. This temporary change affects
1894 other threads.
1895
1896 .. versionchanged:: 3.7
1897 When formatting a number with the ``n`` type, the function sets
1898 temporarily the ``LC_CTYPE`` locale to the ``LC_NUMERIC`` locale in some
1899 cases.
1900
1901
1902 .. method:: str.format_map(mapping, /)
1903
1904 Similar to ``str.format(**mapping)``, except that ``mapping`` is
1905 used directly and not copied to a :class:`dict`. This is useful
1906 if for example ``mapping`` is a dict subclass:
1907
1908 >>> class Default(dict):
1909 ... def __missing__(self, key):
1910 ... return key
1911 ...
1912 >>> '{name} was born in {country}'.format_map(Default(name='Guido'))
1913 'Guido was born in country'
1914
1915 .. versionadded:: 3.2
1916
1917
1918 .. method:: str.index(sub[, start[, end]])
1919
1920 Like :meth:`~str.find`, but raise :exc:`ValueError` when the substring is
1921 not found. For example:
1922
1923 .. doctest::
1924
1925 >>> 'spam, spam, spam'.index('spam')
1926 0
1927 >>> 'spam, spam, spam'.index('eggs')
1928 Traceback (most recent call last):
1929 File "<python-input-0>", line 1, in <module>
1930 'spam, spam, spam'.index('eggs')
1931 ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
1932 ValueError: substring not found
1933
1934 See also :meth:`rindex`.
1935
1936
1937 .. method:: str.isalnum()
1938
1939 Return ``True`` if all characters in the string are alphanumeric and there is at
1940 least one character, ``False`` otherwise. A character ``c`` is alphanumeric if one
1941 of the following returns ``True``: ``c.isalpha()``, ``c.isdecimal()``,
1942 ``c.isdigit()``, or ``c.isnumeric()``.
1943
1944
1945 .. method:: str.isalpha()
1946
1947 Return ``True`` if all characters in the string are alphabetic and there is at least
1948 one character, ``False`` otherwise. Alphabetic characters are those characters defined
1949 in the Unicode character database as "Letter", i.e., those with general category
1950 property being one of "Lm", "Lt", "Lu", "Ll", or "Lo". Note that this is different
1951 from the `Alphabetic property defined in the section 4.10 'Letters, Alphabetic, and
1952 Ideographic' of the Unicode Standard
1953 <https://www.unicode.org/versions/Unicode15.1.0/ch04.pdf>`_.
1954 For example:
1955
1956 .. doctest::
1957
1958 >>> 'Letters and spaces'.isalpha()
1959 False
1960 >>> 'LettersOnly'.isalpha()
1961 True
1962 >>> 'µ'.isalpha() # non-ASCII characters can be considered alphabetical too
1963 True
1964
1965 See :ref:`unicode-properties`.
1966
1967
1968 .. method:: str.isascii()
1969
1970 Return ``True`` if the string is empty or all characters in the string are ASCII,
1971 ``False`` otherwise.
1972 ASCII characters have code points in the range U+0000-U+007F. For example:
1973
1974 .. doctest::
1975
1976 >>> 'ASCII characters'.isascii()
1977 True
1978 >>> 'µ'.isascii()
1979 False
1980
1981 .. versionadded:: 3.7
1982
1983
1984 .. method:: str.isdecimal()
1985
1986 Return ``True`` if all characters in the string are decimal
1987 characters and there is at least one character, ``False``
1988 otherwise. Decimal characters are those that can be used to form
1989 numbers in base 10, such as U+0660, ARABIC-INDIC DIGIT
1990 ZERO. Formally a decimal character is a character in the Unicode
1991 General Category "Nd". For example:
1992
1993 .. doctest::
1994
1995 >>> '0123456789'.isdecimal()
1996 True
1997 >>> '٠١٢٣٤٥٦٧٨٩'.isdecimal() # Arabic-Indic digits zero to nine
1998 True
1999 >>> 'alphabetic'.isdecimal()
2000 False
2001
2002
2003 .. method:: str.isdigit()
2004
2005 Return ``True`` if all characters in the string are digits and there is at least one
2006 character, ``False`` otherwise. Digits include decimal characters and digits that need
2007 special handling, such as the compatibility superscript digits.
2008 This covers digits which cannot be used to form numbers in base 10,
2009 like the Kharosthi numbers. Formally, a digit is a character that has the
2010 property value Numeric_Type=Digit or Numeric_Type=Decimal.
2011
2012
2013 .. method:: str.isidentifier()
2014
2015 Return ``True`` if the string is a valid identifier according to the language
2016 definition, section :ref:`identifiers`.
2017
2018 :func:`keyword.iskeyword` can be used to test whether string ``s`` is a reserved
2019 identifier, such as :keyword:`def` and :keyword:`class`.
2020
2021 Example:
2022 ::
2023
2024 >>> from keyword import iskeyword
2025
2026 >>> 'hello'.isidentifier(), iskeyword('hello')
2027 (True, False)
2028 >>> 'def'.isidentifier(), iskeyword('def')
2029 (True, True)
2030
2031
2032 .. method:: str.islower()
2033
2034 Return ``True`` if all cased characters [4]_ in the string are lowercase and
2035 there is at least one cased character, ``False`` otherwise.
2036
2037
2038 .. method:: str.isnumeric()
2039
2040 Return ``True`` if all characters in the string are numeric
2041 characters, and there is at least one character, ``False``
2042 otherwise. Numeric characters include digit characters, and all characters
2043 that have the Unicode numeric value property, e.g. U+2155,
2044 VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property
2045 value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.
2046 For example:
2047
2048 .. doctest::
2049
2050 >>> '0123456789'.isnumeric()
2051 True
2052 >>> '٠١٢٣٤٥٦٧٨٩'.isnumeric() # Arabic-indic digit zero to nine
2053 True
2054 >>> 'â…•'.isnumeric() # Vulgar fraction one fifth
2055 True
2056 >>> '²'.isdecimal(), '²'.isdigit(), '²'.isnumeric()
2057 (False, True, True)
2058
2059 See also :meth:`isdecimal` and :meth:`isdigit`. Numeric characters are
2060 a superset of decimal numbers.
2061
2062
2063 .. method:: str.isprintable()
2064
2065 Return ``True`` if all characters in the string are printable, ``False`` if it
2066 contains at least one non-printable character.
2067
2068 Here "printable" means the character is suitable for :func:`repr` to use in
2069 its output; "non-printable" means that :func:`repr` on built-in types will
2070 hex-escape the character. It has no bearing on the handling of strings
2071 written to :data:`sys.stdout` or :data:`sys.stderr`.
2072
2073 The printable characters are those which in the Unicode character database
2074 (see :mod:`unicodedata`) have a general category in group Letter, Mark,
2075 Number, Punctuation, or Symbol (L, M, N, P, or S); plus the ASCII space 0x20.
2076 Nonprintable characters are those in group Separator or Other (Z or C),
2077 except the ASCII space.
2078
2079 For example:
2080
2081 .. doctest::
2082
2083 >>> ''.isprintable(), ' '.isprintable()
2084 (True, True)
2085 >>> '\t'.isprintable(), '\n'.isprintable()
2086 (False, False)
2087
2088
2089 .. method:: str.isspace()
2090
2091 Return ``True`` if there are only whitespace characters in the string and there is
2092 at least one character, ``False`` otherwise.
2093
2094 A character is *whitespace* if in the Unicode character database
2095 (see :mod:`unicodedata`), either its general category is ``Zs``
2096 ("Separator, space"), or its bidirectional class is one of ``WS``,
2097 ``B``, or ``S``.
2098
2099
2100 .. method:: str.istitle()
2101
2102 Return ``True`` if the string is a titlecased string and there is at least one
2103 character, for example uppercase characters may only follow uncased characters
2104 and lowercase characters only cased ones. Return ``False`` otherwise.
2105
2106 For example:
2107
2108 .. doctest::
2109
2110 >>> 'Spam, Spam, Spam'.istitle()
2111 True
2112 >>> 'spam, spam, spam'.istitle()
2113 False
2114 >>> 'SPAM, SPAM, SPAM'.istitle()
2115 False
2116
2117 See also :meth:`title`.
2118
2119
2120 .. method:: str.isupper()
2121
2122 Return ``True`` if all cased characters [4]_ in the string are uppercase and
2123 there is at least one cased character, ``False`` otherwise.
2124
2125 >>> 'BANANA'.isupper()
2126 True
2127 >>> 'banana'.isupper()
2128 False
2129 >>> 'baNana'.isupper()
2130 False
2131 >>> ' '.isupper()
2132 False
2133
2134
2135
2136 .. _meth-str-join:
2137
2138 .. method:: str.join(iterable, /)
2139
2140 Return a string which is the concatenation of the strings in *iterable*.
2141 A :exc:`TypeError` will be raised if there are any non-string values in
2142 *iterable*, including :class:`bytes` objects. The separator between
2143 elements is the string providing this method. For example:
2144
2145 .. doctest::
2146
2147 >>> ', '.join(['spam', 'spam', 'spam'])
2148 'spam, spam, spam'
2149 >>> '-'.join('Python')
2150 'P-y-t-h-o-n'
2151
2152 See also :meth:`split`.
2153
2154
2155 .. method:: str.ljust(width, fillchar=' ', /)
2156
2157 Return the string left justified in a string of length *width*. Padding is
2158 done using the specified *fillchar* (default is an ASCII space). The
2159 original string is returned if *width* is less than or equal to ``len(s)``.
2160
2161 For example:
2162
2163 .. doctest::
2164
2165 >>> 'Python'.ljust(10)
2166 'Python '
2167 >>> 'Python'.ljust(10, '.')
2168 'Python....'
2169 >>> 'Monty Python'.ljust(10, '.')
2170 'Monty Python'
2171
2172 See also :meth:`rjust`.
2173
2174
2175 .. method:: str.lower()
2176
2177 Return a copy of the string with all the cased characters [4]_ converted to
2178 lowercase. For example:
2179
2180 .. doctest::
2181
2182 >>> 'Lower Method Example'.lower()
2183 'lower method example'
2184
2185 The lowercasing algorithm used is
2186 `described in section 3.13 'Default Case Folding' of the Unicode Standard
2187 <https://www.unicode.org/versions/Unicode15.1.0/ch03.pdf>`__.
2188
2189
2190 .. method:: str.lstrip(chars=None, /)
2191
2192 Return a copy of the string with leading characters removed. The *chars*
2193 argument is a string specifying the set of characters to be removed. If omitted
2194 or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
2195 argument is not a prefix; rather, all combinations of its values are stripped::
2196
2197 >>> ' spacious '.lstrip()
2198 'spacious '
2199 >>> 'www.example.com'.lstrip('cmowz.')
2200 'example.com'
2201
2202 See :meth:`str.removeprefix` for a method that will remove a single prefix
2203 string rather than all of a set of characters. For example::
2204
2205 >>> 'Arthur: three!'.lstrip('Arthur: ')
2206 'ee!'
2207 >>> 'Arthur: three!'.removeprefix('Arthur: ')
2208 'three!'
2209
2210
2211 .. staticmethod:: str.maketrans(dict, /)
2212 str.maketrans(from, to, remove='', /)
2213
2214 This static method returns a translation table usable for :meth:`str.translate`.
2215
2216 If there is only one argument, it must be a dictionary mapping Unicode
2217 ordinals (integers) or characters (strings of length 1) to Unicode ordinals,
2218 strings (of arbitrary lengths) or ``None``. Character keys will then be
2219 converted to ordinals.
2220
2221 If there are two arguments, they must be strings of equal length, and in the
2222 resulting dictionary, each character in *from* will be mapped to the character at
2223 the same position in *to*. If there is a third argument, it must be a string,
2224 whose characters will be mapped to ``None`` in the result.
2225
2226
2227 .. method:: str.partition(sep, /)
2228
2229 Split the string at the first occurrence of *sep*, and return a 3-tuple
2230 containing the part before the separator, the separator itself, and the part
2231 after the separator. If the separator is not found, return a 3-tuple containing
2232 the string itself, followed by two empty strings.
2233
2234
2235 .. method:: str.removeprefix(prefix, /)
2236
2237 If the string starts with the *prefix* string, return
2238 ``string[len(prefix):]``. Otherwise, return a copy of the original
2239 string:
2240
2241 .. doctest::
2242
2243 >>> 'TestHook'.removeprefix('Test')
2244 'Hook'
2245 >>> 'BaseTestCase'.removeprefix('Test')
2246 'BaseTestCase'
2247
2248 .. versionadded:: 3.9
2249
2250 See also :meth:`removesuffix` and :meth:`startswith`.
2251
2252
2253 .. method:: str.removesuffix(suffix, /)
2254
2255 If the string ends with the *suffix* string and that *suffix* is not empty,
2256 return ``string[:-len(suffix)]``. Otherwise, return a copy of the
2257 original string:
2258
2259 .. doctest::
2260
2261 >>> 'MiscTests'.removesuffix('Tests')
2262 'Misc'
2263 >>> 'TmpDirMixin'.removesuffix('Tests')
2264 'TmpDirMixin'
2265
2266 .. versionadded:: 3.9
2267
2268 See also :meth:`removeprefix` and :meth:`endswith`.
2269
2270
2271 .. method:: str.replace(old, new, /, count=-1)
2272
2273 Return a copy of the string with all occurrences of substring *old* replaced by
2274 *new*. If *count* is given, only the first *count* occurrences are replaced.
2275 If *count* is not specified or ``-1``, then all occurrences are replaced.
2276 For example:
2277
2278 .. doctest::
2279
2280 >>> 'spam, spam, spam'.replace('spam', 'eggs')
2281 'eggs, eggs, eggs'
2282 >>> 'spam, spam, spam'.replace('spam', 'eggs', 1)
2283 'eggs, spam, spam'
2284
2285 .. versionchanged:: 3.13
2286 *count* is now supported as a keyword argument.
2287
2288
2289 .. method:: str.rfind(sub[, start[, end]])
2290
2291 Return the highest index in the string where substring *sub* is found, such
2292 that *sub* is contained within ``s[start:end]``. Optional arguments *start*
2293 and *end* are interpreted as in slice notation. Return ``-1`` on failure.
2294 For example:
2295
2296 .. doctest::
2297
2298 >>> 'spam, spam, spam'.rfind('sp')
2299 12
2300 >>> 'spam, spam, spam'.rfind('sp', 0, 10)
2301 6
2302
2303 See also :meth:`find` and :meth:`rindex`.
2304
2305
2306 .. method:: str.rindex(sub[, start[, end]])
2307
2308 Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not
2309 found.
2310 For example:
2311
2312 .. doctest::
2313
2314 >>> 'spam, spam, spam'.rindex('spam')
2315 12
2316 >>> 'spam, spam, spam'.rindex('eggs')
2317 Traceback (most recent call last):
2318 File "<stdin-0>", line 1, in <module>
2319 'spam, spam, spam'.rindex('eggs')
2320 ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
2321 ValueError: substring not found
2322
2323 See also :meth:`index` and :meth:`find`.
2324
2325
2326 .. method:: str.rjust(width, fillchar=' ', /)
2327
2328 Return the string right justified in a string of length *width*. Padding is
2329 done using the specified *fillchar* (default is an ASCII space). The
2330 original string is returned if *width* is less than or equal to ``len(s)``.
2331
2332
2333 .. method:: str.rpartition(sep, /)
2334
2335 Split the string at the last occurrence of *sep*, and return a 3-tuple
2336 containing the part before the separator, the separator itself, and the part
2337 after the separator. If the separator is not found, return a 3-tuple containing
2338 two empty strings, followed by the string itself.
2339
2340 For example:
2341
2342 .. doctest::
2343
2344 >>> 'Monty Python'.rpartition(' ')
2345 ('Monty', ' ', 'Python')
2346 >>> "Monty Python's Flying Circus".rpartition(' ')
2347 ("Monty Python's Flying", ' ', 'Circus')
2348 >>> 'Monty Python'.rpartition('-')
2349 ('', '', 'Monty Python')
2350
2351 See also :meth:`partition`.
2352
2353
2354 .. method:: str.rsplit(sep=None, maxsplit=-1)
2355
2356 Return a list of the words in the string, using *sep* as the delimiter string.
2357 If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost*
2358 ones. If *sep* is not specified or ``None``, any whitespace string is a
2359 separator. Except for splitting from the right, :meth:`rsplit` behaves like
2360 :meth:`split` which is described in detail below.
2361
2362
2363 .. method:: str.rstrip(chars=None, /)
2364
2365 Return a copy of the string with trailing characters removed. The *chars*
2366 argument is a string specifying the set of characters to be removed. If omitted
2367 or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
2368 argument is not a suffix; rather, all combinations of its values are stripped::
2369
2370 >>> ' spacious '.rstrip()
2371 ' spacious'
2372 >>> 'mississippi'.rstrip('ipz')
2373 'mississ'
2374
2375 See :meth:`str.removesuffix` for a method that will remove a single suffix
2376 string rather than all of a set of characters. For example::
2377
2378 >>> 'Monty Python'.rstrip(' Python')
2379 'M'
2380 >>> 'Monty Python'.removesuffix(' Python')
2381 'Monty'
2382
2383 .. method:: str.split(sep=None, maxsplit=-1)
2384
2385 Return a list of the words in the string, using *sep* as the delimiter
2386 string. If *maxsplit* is given, at most *maxsplit* splits are done (thus,
2387 the list will have at most ``maxsplit+1`` elements). If *maxsplit* is not
2388 specified or ``-1``, then there is no limit on the number of splits
2389 (all possible splits are made).
2390
2391 If *sep* is given, consecutive delimiters are not grouped together and are
2392 deemed to delimit empty strings (for example, ``'1,,2'.split(',')`` returns
2393 ``['1', '', '2']``). The *sep* argument may consist of multiple characters
2394 as a single delimiter (to split with multiple delimiters, use
2395 :func:`re.split`). Splitting an empty string with a specified separator
2396 returns ``['']``.
2397
2398 For example::
2399
2400 >>> '1,2,3'.split(',')
2401 ['1', '2', '3']
2402 >>> '1,2,3'.split(',', maxsplit=1)
2403 ['1', '2,3']
2404 >>> '1,2,,3,'.split(',')
2405 ['1', '2', '', '3', '']
2406 >>> '1<>2<>3<4'.split('<>')
2407 ['1', '2', '3<4']
2408
2409 If *sep* is not specified or is ``None``, a different splitting algorithm is
2410 applied: runs of consecutive whitespace are regarded as a single separator,
2411 and the result will contain no empty strings at the start or end if the
2412 string has leading or trailing whitespace. Consequently, splitting an empty
2413 string or a string consisting of just whitespace with a ``None`` separator
2414 returns ``[]``.
2415
2416 For example::
2417
2418 >>> '1 2 3'.split()
2419 ['1', '2', '3']
2420 >>> '1 2 3'.split(maxsplit=1)
2421 ['1', '2 3']
2422 >>> ' 1 2 3 '.split()
2423 ['1', '2', '3']
2424
2425 If *sep* is not specified or is ``None`` and *maxsplit* is ``0``, only
2426 leading runs of consecutive whitespace are considered.
2427
2428 For example::
2429
2430 >>> "".split(None, 0)
2431 []
2432 >>> " ".split(None, 0)
2433 []
2434 >>> " foo ".split(maxsplit=0)
2435 ['foo ']
2436
2437 See also :meth:`join`.
2438
2439
2440 .. index::
2441 single: universal newlines; str.splitlines method
2442
2443 .. method:: str.splitlines(keepends=False)
2444
2445 Return a list of the lines in the string, breaking at line boundaries. Line
2446 breaks are not included in the resulting list unless *keepends* is given and
2447 true.
2448
2449 This method splits on the following line boundaries. In particular, the
2450 boundaries are a superset of :term:`universal newlines`.
2451
2452 +-----------------------+-----------------------------+
2453 | Representation | Description |
2454 +=======================+=============================+
2455 | ``\n`` | Line Feed |
2456 +-----------------------+-----------------------------+
2457 | ``\r`` | Carriage Return |
2458 +-----------------------+-----------------------------+
2459 | ``\r\n`` | Carriage Return + Line Feed |
2460 +-----------------------+-----------------------------+
2461 | ``\v`` or ``\x0b`` | Line Tabulation |
2462 +-----------------------+-----------------------------+
2463 | ``\f`` or ``\x0c`` | Form Feed |
2464 +-----------------------+-----------------------------+
2465 | ``\x1c`` | File Separator |
2466 +-----------------------+-----------------------------+
2467 | ``\x1d`` | Group Separator |
2468 +-----------------------+-----------------------------+
2469 | ``\x1e`` | Record Separator |
2470 +-----------------------+-----------------------------+
2471 | ``\x85`` | Next Line (C1 Control Code) |
2472 +-----------------------+-----------------------------+
2473 | ``\u2028`` | Line Separator |
2474 +-----------------------+-----------------------------+
2475 | ``\u2029`` | Paragraph Separator |
2476 +-----------------------+-----------------------------+
2477
2478 .. versionchanged:: 3.2
2479
2480 ``\v`` and ``\f`` added to list of line boundaries.
2481
2482 For example::
2483
2484 >>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
2485 ['ab c', '', 'de fg', 'kl']
2486 >>> 'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
2487 ['ab c\n', '\n', 'de fg\r', 'kl\r\n']
2488
2489 Unlike :meth:`~str.split` when a delimiter string *sep* is given, this
2490 method returns an empty list for the empty string, and a terminal line
2491 break does not result in an extra line::
2492
2493 >>> "".splitlines()
2494 []
2495 >>> "One line\n".splitlines()
2496 ['One line']
2497
2498 For comparison, ``split('\n')`` gives::
2499
2500 >>> ''.split('\n')
2501 ['']
2502 >>> 'Two lines\n'.split('\n')
2503 ['Two lines', '']
2504
2505
2506 .. method:: str.startswith(prefix[, start[, end]])
2507
2508 Return ``True`` if string starts with the *prefix*, otherwise return ``False``.
2509 *prefix* can also be a tuple of prefixes to look for. With optional *start*,
2510 test string beginning at that position. With optional *end*, stop comparing
2511 string at that position.
2512
2513
2514 .. method:: str.strip(chars=None, /)
2515
2516 Return a copy of the string with the leading and trailing characters removed.
2517 The *chars* argument is a string specifying the set of characters to be removed.
2518 If omitted or ``None``, the *chars* argument defaults to removing whitespace.
2519 The *chars* argument is not a prefix or suffix; rather, all combinations of its
2520 values are stripped::
2521
2522 >>> ' spacious '.strip()
2523 'spacious'
2524 >>> 'www.example.com'.strip('cmowz.')
2525 'example'
2526
2527 The outermost leading and trailing *chars* argument values are stripped
2528 from the string. Characters are removed from the leading end until
2529 reaching a string character that is not contained in the set of
2530 characters in *chars*. A similar action takes place on the trailing end.
2531 For example::
2532
2533 >>> comment_string = '#....... Section 3.2.1 Issue #32 .......'
2534 >>> comment_string.strip('.#! ')
2535 'Section 3.2.1 Issue #32'
2536
2537
2538 .. method:: str.swapcase()
2539
2540 Return a copy of the string with uppercase characters converted to lowercase and
2541 vice versa. Note that it is not necessarily true that
2542 ``s.swapcase().swapcase() == s``.
2543
2544
2545 .. method:: str.title()
2546
2547 Return a titlecased version of the string where words start with an uppercase
2548 character and the remaining characters are lowercase.
2549
2550 For example::
2551
2552 >>> 'Hello world'.title()
2553 'Hello World'
2554
2555 The algorithm uses a simple language-independent definition of a word as
2556 groups of consecutive letters. The definition works in many contexts but
2557 it means that apostrophes in contractions and possessives form word
2558 boundaries, which may not be the desired result::
2559
2560 >>> "they're bill's friends from the UK".title()
2561 "They'Re Bill'S Friends From The Uk"
2562
2563 The :func:`string.capwords` function does not have this problem, as it
2564 splits words on spaces only.
2565
2566 Alternatively, a workaround for apostrophes can be constructed using regular
2567 expressions::
2568
2569 >>> import re
2570 >>> def titlecase(s):
2571 ... return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
2572 ... lambda mo: mo.group(0).capitalize(),
2573 ... s)
2574 ...
2575 >>> titlecase("they're bill's friends.")
2576 "They're Bill's Friends."
2577
2578 See also :meth:`istitle`.
2579
2580
2581 .. method:: str.translate(table, /)
2582
2583 Return a copy of the string in which each character has been mapped through
2584 the given translation table. The table must be an object that implements
2585 indexing via :meth:`~object.__getitem__`, typically a :term:`mapping` or
2586 :term:`sequence`. When indexed by a Unicode ordinal (an integer), the
2587 table object can do any of the following: return a Unicode ordinal or a
2588 string, to map the character to one or more other characters; return
2589 ``None``, to delete the character from the return string; or raise a
2590 :exc:`LookupError` exception, to map the character to itself.
2591
2592 You can use :meth:`str.maketrans` to create a translation map from
2593 character-to-character mappings in different formats.
2594
2595 See also the :mod:`codecs` module for a more flexible approach to custom
2596 character mappings.
2597
2598
2599 .. method:: str.upper()
2600
2601 Return a copy of the string with all the cased characters [4]_ converted to
2602 uppercase. Note that ``s.upper().isupper()`` might be ``False`` if ``s``
2603 contains uncased characters or if the Unicode category of the resulting
2604 character(s) is not "Lu" (Letter, uppercase), but e.g. "Lt" (Letter,
2605 titlecase).
2606
2607 The uppercasing algorithm used is
2608 `described in section 3.13 'Default Case Folding' of the Unicode Standard
2609 <https://www.unicode.org/versions/Unicode15.1.0/ch03.pdf>`__.
2610
2611
2612 .. method:: str.zfill(width, /)
2613
2614 Return a copy of the string left filled with ASCII ``'0'`` digits to
2615 make a string of length *width*. A leading sign prefix (``'+'``/``'-'``)
2616 is handled by inserting the padding *after* the sign character rather
2617 than before. The original string is returned if *width* is less than
2618 or equal to ``len(s)``.
2619
2620 For example::
2621
2622 >>> "42".zfill(5)
2623 '00042'
2624 >>> "-42".zfill(5)
2625 '-0042'
2626
2627
2628 .. index::
2629 single: ! formatted string literal
2630 single: formatted string literals
2631 single: ! f-string
2632 single: f-strings
2633 single: fstring
2634 single: interpolated string literal
2635 single: string; formatted literal
2636 single: string; interpolated literal
2637 single: {} (curly brackets); in formatted string literal
2638 single: ! (exclamation mark); in formatted string literal
2639 single: : (colon); in formatted string literal
2640 single: = (equals); for help in debugging using string literals
2641
2642 Formatted String Literals (f-strings)
2643 -------------------------------------
2644
2645 .. versionadded:: 3.6
2646 .. versionchanged:: 3.7
2647 The :keyword:`await` and :keyword:`async for` can be used in expressions
2648 within f-strings.
2649 .. versionchanged:: 3.8
2650 Added the debugging operator (``=``)
2651 .. versionchanged:: 3.12
2652 Many restrictions on expressions within f-strings have been removed.
2653 Notably, nested strings, comments, and backslashes are now permitted.
2654
2655 An :dfn:`f-string` (formally a :dfn:`formatted string literal`) is
2656 a string literal that is prefixed with ``f`` or ``F``.
2657 This type of string literal allows embedding arbitrary Python expressions
2658 within *replacement fields*, which are delimited by curly brackets (``{}``).
2659 These expressions are evaluated at runtime, similarly to :meth:`str.format`,
2660 and are converted into regular :class:`str` objects.
2661 For example:
2662
2663 .. doctest::
2664
2665 >>> who = 'nobody'
2666 >>> nationality = 'Spanish'
2667 >>> f'{who.title()} expects the {nationality} Inquisition!'
2668 'Nobody expects the Spanish Inquisition!'
2669
2670 It is also possible to use a multi line f-string:
2671
2672 .. doctest::
2673
2674 >>> f'''This is a string
2675 ... on two lines'''
2676 'This is a string\non two lines'
2677
2678 A single opening curly bracket, ``'{'``, marks a *replacement field* that
2679 can contain any Python expression:
2680
2681 .. doctest::
2682
2683 >>> nationality = 'Spanish'
2684 >>> f'The {nationality} Inquisition!'
2685 'The Spanish Inquisition!'
2686
2687 To include a literal ``{`` or ``}``, use a double bracket:
2688
2689 .. doctest::
2690
2691 >>> x = 42
2692 >>> f'{{x}} is {x}'
2693 '{x} is 42'
2694
2695 Functions can also be used, and :ref:`format specifiers <formatstrings>`:
2696
2697 .. doctest::
2698
2699 >>> from math import sqrt
2700 >>> f'√2 \N{ALMOST EQUAL TO} {sqrt(2):.5f}'
2701 '√2 ≈ 1.41421'
2702
2703 Any non-string expression is converted using :func:`str`, by default:
2704
2705 .. doctest::
2706
2707 >>> from fractions import Fraction
2708 >>> f'{Fraction(1, 3)}'
2709 '1/3'
2710
2711 To use an explicit conversion, use the ``!`` (exclamation mark) operator,
2712 followed by any of the valid formats, which are:
2713
2714 ========== ==============
2715 Conversion Meaning
2716 ========== ==============
2717 ``!a`` :func:`ascii`
2718 ``!r`` :func:`repr`
2719 ``!s`` :func:`str`
2720 ========== ==============
2721
2722 For example:
2723
2724 .. doctest::
2725
2726 >>> from fractions import Fraction
2727 >>> f'{Fraction(1, 3)!s}'
2728 '1/3'
2729 >>> f'{Fraction(1, 3)!r}'
2730 'Fraction(1, 3)'
2731 >>> question = '¿Dónde está el Presidente?'
2732 >>> print(f'{question!a}')
2733 '\xbfD\xf3nde est\xe1 el Presidente?'
2734
2735 While debugging it may be helpful to see both the expression and its value,
2736 by using the equals sign (``=``) after the expression.
2737 This preserves spaces within the brackets, and can be used with a converter.
2738 By default, the debugging operator uses the :func:`repr` (``!r``) conversion.
2739 For example:
2740
2741 .. doctest::
2742
2743 >>> from fractions import Fraction
2744 >>> calculation = Fraction(1, 3)
2745 >>> f'{calculation=}'
2746 'calculation=Fraction(1, 3)'
2747 >>> f'{calculation = }'
2748 'calculation = Fraction(1, 3)'
2749 >>> f'{calculation = !s}'
2750 'calculation = 1/3'
2751
2752 Once the output has been evaluated, it can be formatted using a
2753 :ref:`format specifier <formatstrings>` following a colon (``':'``).
2754 After the expression has been evaluated, and possibly converted to a string,
2755 the :meth:`!__format__` method of the result is called with the format specifier,
2756 or the empty string if no format specifier is given.
2757 The formatted result is then used as the final value for the replacement field.
2758 For example:
2759
2760 .. doctest::
2761
2762 >>> from fractions import Fraction
2763 >>> f'{Fraction(1, 7):.6f}'
2764 '0.142857'
2765 >>> f'{Fraction(1, 7):_^+10}'
2766 '___+1/7___'
2767
2768
2769 .. _old-string-formatting:
2770
2771 ``printf``-style String Formatting
2772 ----------------------------------
2773
2774 .. index::
2775 single: formatting, string (%)
2776 single: interpolation, string (%)
2777 single: string; formatting, printf
2778 single: string; interpolation, printf
2779 single: printf-style formatting
2780 single: sprintf-style formatting
2781 single: % (percent); printf-style formatting
2782
2783 .. note::
2784
2785 The formatting operations described here exhibit a variety of quirks that
2786 lead to a number of common errors (such as failing to display tuples and
2787 dictionaries correctly). Using the newer :ref:`formatted string literals
2788 <f-strings>`, the :meth:`str.format` interface, or :ref:`template strings
2789 <template-strings>` may help avoid these errors. Each of these
2790 alternatives provides their own trade-offs and benefits of simplicity,
2791 flexibility, and/or extensibility.
2792
2793 String objects have one unique built-in operation: the ``%`` operator (modulo).
2794 This is also known as the string *formatting* or *interpolation* operator.
2795 Given ``format % values`` (where *format* is a string), ``%`` conversion
2796 specifications in *format* are replaced with zero or more elements of *values*.
2797 The effect is similar to using the :c:func:`sprintf` function in the C language.
2798 For example:
2799
2800 .. doctest::
2801
2802 >>> print('%s has %d quote types.' % ('Python', 2))
2803 Python has 2 quote types.
2804
2805 If *format* requires a single argument, *values* may be a single non-tuple
2806 object. [5]_ Otherwise, *values* must be a tuple with exactly the number of
2807 items specified by the format string, or a single mapping object (for example, a
2808 dictionary).
2809
2810 .. index::
2811 single: () (parentheses); in printf-style formatting
2812 single: * (asterisk); in printf-style formatting
2813 single: . (dot); in printf-style formatting
2814
2815 A conversion specifier contains two or more characters and has the following
2816 components, which must occur in this order:
2817
2818 #. The ``'%'`` character, which marks the start of the specifier.
2819
2820 #. Mapping key (optional), consisting of a parenthesised sequence of characters
2821 (for example, ``(somename)``).
2822
2823 #. Conversion flags (optional), which affect the result of some conversion
2824 types.
2825
2826 #. Minimum field width (optional). If specified as an ``'*'`` (asterisk), the
2827 actual width is read from the next element of the tuple in *values*, and the
2828 object to convert comes after the minimum field width and optional precision.
2829
2830 #. Precision (optional), given as a ``'.'`` (dot) followed by the precision. If
2831 specified as ``'*'`` (an asterisk), the actual precision is read from the next
2832 element of the tuple in *values*, and the value to convert comes after the
2833 precision.
2834
2835 #. Length modifier (optional).
2836
2837 #. Conversion type.
2838
2839 When the right argument is a dictionary (or other mapping type), then the
2840 formats in the string *must* include a parenthesised mapping key into that
2841 dictionary inserted immediately after the ``'%'`` character. The mapping key
2842 selects the value to be formatted from the mapping. For example:
2843
2844 >>> print('%(language)s has %(number)03d quote types.' %
2845 ... {'language': "Python", "number": 2})
2846 Python has 002 quote types.
2847
2848 In this case no ``*`` specifiers may occur in a format (since they require a
2849 sequential parameter list).
2850
2851 The conversion flag characters are:
2852
2853 .. index::
2854 single: # (hash); in printf-style formatting
2855 single: - (minus); in printf-style formatting
2856 single: + (plus); in printf-style formatting
2857 single: space; in printf-style formatting
2858
2859 +---------+---------------------------------------------------------------------+
2860 | Flag | Meaning |
2861 +=========+=====================================================================+
2862 | ``'#'`` | The value conversion will use the "alternate form" (where defined |
2863 | | below). |
2864 +---------+---------------------------------------------------------------------+
2865 | ``'0'`` | The conversion will be zero padded for numeric values. |
2866 +---------+---------------------------------------------------------------------+
2867 | ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` |
2868 | | conversion if both are given). |
2869 +---------+---------------------------------------------------------------------+
2870 | ``' '`` | (a space) A blank should be left before a positive number (or empty |
2871 | | string) produced by a signed conversion. |
2872 +---------+---------------------------------------------------------------------+
2873 | ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion |
2874 | | (overrides a "space" flag). |
2875 +---------+---------------------------------------------------------------------+
2876
2877 A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it
2878 is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``.
2879
2880 The conversion types are:
2881
2882 +------------+-----------------------------------------------------+-------+
2883 | Conversion | Meaning | Notes |
2884 +============+=====================================================+=======+
2885 | ``'d'`` | Signed integer decimal. | |
2886 +------------+-----------------------------------------------------+-------+
2887 | ``'i'`` | Signed integer decimal. | |
2888 +------------+-----------------------------------------------------+-------+
2889 | ``'o'`` | Signed octal value. | \(1) |
2890 +------------+-----------------------------------------------------+-------+
2891 | ``'u'`` | Obsolete type -- it is identical to ``'d'``. | \(6) |
2892 +------------+-----------------------------------------------------+-------+
2893 | ``'x'`` | Signed hexadecimal (lowercase). | \(2) |
2894 +------------+-----------------------------------------------------+-------+
2895 | ``'X'`` | Signed hexadecimal (uppercase). | \(2) |
2896 +------------+-----------------------------------------------------+-------+
2897 | ``'e'`` | Floating-point exponential format (lowercase). | \(3) |
2898 +------------+-----------------------------------------------------+-------+
2899 | ``'E'`` | Floating-point exponential format (uppercase). | \(3) |
2900 +------------+-----------------------------------------------------+-------+
2901 | ``'f'`` | Floating-point decimal format. | \(3) |
2902 +------------+-----------------------------------------------------+-------+
2903 | ``'F'`` | Floating-point decimal format. | \(3) |
2904 +------------+-----------------------------------------------------+-------+
2905 | ``'g'`` | Floating-point format. Uses lowercase exponential | \(4) |
2906 | | format if exponent is less than -4 or not less than | |
2907 | | precision, decimal format otherwise. | |
2908 +------------+-----------------------------------------------------+-------+
2909 | ``'G'`` | Floating-point format. Uses uppercase exponential | \(4) |
2910 | | format if exponent is less than -4 or not less than | |
2911 | | precision, decimal format otherwise. | |
2912 +------------+-----------------------------------------------------+-------+
2913 | ``'c'`` | Single character (accepts integer or single | |
2914 | | character string). | |
2915 +------------+-----------------------------------------------------+-------+
2916 | ``'r'`` | String (converts any Python object using | \(5) |
2917 | | :func:`repr`). | |
2918 +------------+-----------------------------------------------------+-------+
2919 | ``'s'`` | String (converts any Python object using | \(5) |
2920 | | :func:`str`). | |
2921 +------------+-----------------------------------------------------+-------+
2922 | ``'a'`` | String (converts any Python object using | \(5) |
2923 | | :func:`ascii`). | |
2924 +------------+-----------------------------------------------------+-------+
2925 | ``'%'`` | No argument is converted, results in a ``'%'`` | |
2926 | | character in the result. | |
2927 +------------+-----------------------------------------------------+-------+
2928
2929 Notes:
2930
2931 (1)
2932 The alternate form causes a leading octal specifier (``'0o'``) to be
2933 inserted before the first digit.
2934
2935 (2)
2936 The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether
2937 the ``'x'`` or ``'X'`` format was used) to be inserted before the first digit.
2938
2939 (3)
2940 The alternate form causes the result to always contain a decimal point, even if
2941 no digits follow it.
2942
2943 The precision determines the number of digits after the decimal point and
2944 defaults to 6.
2945
2946 (4)
2947 The alternate form causes the result to always contain a decimal point, and
2948 trailing zeroes are not removed as they would otherwise be.
2949
2950 The precision determines the number of significant digits before and after the
2951 decimal point and defaults to 6.
2952
2953 (5)
2954 If precision is ``N``, the output is truncated to ``N`` characters.
2955
2956 (6)
2957 See :pep:`237`.
2958
2959 Since Python strings have an explicit length, ``%s`` conversions do not assume
2960 that ``'\0'`` is the end of the string.
2961
2962 .. XXX Examples?
2963
2964 .. versionchanged:: 3.1
2965 ``%f`` conversions for numbers whose absolute value is over 1e50 are no
2966 longer replaced by ``%g`` conversions.
2967
2968
2969 .. index::
2970 single: buffer protocol; binary sequence types
2971
2972 .. _binaryseq:
2973
2974 Binary Sequence Types --- :class:`bytes`, :class:`bytearray`, :class:`memoryview`
2975 =================================================================================
2976
2977 .. index::
2978 pair: object; bytes
2979 pair: object; bytearray
2980 pair: object; memoryview
2981 pair: module; array
2982
2983 The core built-in types for manipulating binary data are :class:`bytes` and
2984 :class:`bytearray`. They are supported by :class:`memoryview` which uses
2985 the :ref:`buffer protocol <bufferobjects>` to access the memory of other
2986 binary objects without needing to make a copy.
2987
2988 The :mod:`array` module supports efficient storage of basic data types like
2989 32-bit integers and IEEE754 double-precision floating values.
2990
2991 .. _typebytes:
2992
2993 Bytes Objects
2994 -------------
2995
2996 .. index:: pair: object; bytes
2997
2998 Bytes objects are immutable sequences of single bytes. Since many major
2999 binary protocols are based on the ASCII text encoding, bytes objects offer
3000 several methods that are only valid when working with ASCII compatible
3001 data and are closely related to string objects in a variety of other ways.
3002
3003 .. class:: bytes(source=b'')
3004 bytes(source, encoding, errors='strict')
3005
3006 Firstly, the syntax for bytes literals is largely the same as that for string
3007 literals, except that a ``b`` prefix is added:
3008
3009 * Single quotes: ``b'still allows embedded "double" quotes'``
3010 * Double quotes: ``b"still allows embedded 'single' quotes"``
3011 * Triple quoted: ``b'''3 single quotes'''``, ``b"""3 double quotes"""``
3012
3013 Only ASCII characters are permitted in bytes literals (regardless of the
3014 declared source code encoding). Any binary values over 127 must be entered
3015 into bytes literals using the appropriate escape sequence.
3016
3017 As with string literals, bytes literals may also use a ``r`` prefix to disable
3018 processing of escape sequences. See :ref:`strings` for more about the various
3019 forms of bytes literal, including supported escape sequences.
3020
3021 While bytes literals and representations are based on ASCII text, bytes
3022 objects actually behave like immutable sequences of integers, with each
3023 value in the sequence restricted such that ``0 <= x < 256`` (attempts to
3024 violate this restriction will trigger :exc:`ValueError`). This is done
3025 deliberately to emphasise that while many binary formats include ASCII based
3026 elements and can be usefully manipulated with some text-oriented algorithms,
3027 this is not generally the case for arbitrary binary data (blindly applying
3028 text processing algorithms to binary data formats that are not ASCII
3029 compatible will usually lead to data corruption).
3030
3031 In addition to the literal forms, bytes objects can be created in a number of
3032 other ways:
3033
3034 * A zero-filled bytes object of a specified length: ``bytes(10)``
3035 * From an iterable of integers: ``bytes(range(20))``
3036 * Copying existing binary data via the buffer protocol: ``bytes(obj)``
3037
3038 Also see the :ref:`bytes <func-bytes>` built-in.
3039
3040 Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal
3041 numbers are a commonly used format for describing binary data. Accordingly,
3042 the bytes type has an additional class method to read data in that format:
3043
3044 .. classmethod:: fromhex(string, /)
3045
3046 This :class:`bytes` class method returns a bytes object, decoding the
3047 given string object. The string must contain two hexadecimal digits per
3048 byte, with ASCII whitespace being ignored.
3049
3050 >>> bytes.fromhex('2Ef0 F1f2 ')
3051 b'.\xf0\xf1\xf2'
3052
3053 .. versionchanged:: 3.7
3054 :meth:`bytes.fromhex` now skips all ASCII whitespace in the string,
3055 not just spaces.
3056
3057 A reverse conversion function exists to transform a bytes object into its
3058 hexadecimal representation.
3059
3060 .. method:: hex(*, bytes_per_sep=1)
3061 hex(sep, bytes_per_sep=1)
3062
3063 Return a string object containing two hexadecimal digits for each
3064 byte in the instance.
3065
3066 >>> b'\xf0\xf1\xf2'.hex()
3067 'f0f1f2'
3068
3069 If you want to make the hex string easier to read, you can specify a
3070 single character separator *sep* parameter to include in the output.
3071 By default, this separator will be included between each byte.
3072 A second optional *bytes_per_sep* parameter controls the spacing.
3073 Positive values calculate the separator position from the right,
3074 negative values from the left.
3075
3076 >>> value = b'\xf0\xf1\xf2'
3077 >>> value.hex('-')
3078 'f0-f1-f2'
3079 >>> value.hex('_', 2)
3080 'f0_f1f2'
3081 >>> b'UUDDLRLRAB'.hex(' ', -4)
3082 '55554444 4c524c52 4142'
3083
3084 .. versionadded:: 3.5
3085
3086 .. versionchanged:: 3.8
3087 :meth:`bytes.hex` now supports optional *sep* and *bytes_per_sep*
3088 parameters to insert separators between bytes in the hex output.
3089
3090 Since bytes objects are sequences of integers (akin to a tuple), for a bytes
3091 object *b*, ``b[0]`` will be an integer, while ``b[0:1]`` will be a bytes
3092 object of length 1. (This contrasts with text strings, where both indexing
3093 and slicing will produce a string of length 1)
3094
3095 The representation of bytes objects uses the literal format (``b'...'``)
3096 since it is often more useful than e.g. ``bytes([46, 46, 46])``. You can
3097 always convert a bytes object into a list of integers using ``list(b)``.
3098
3099
3100 .. _typebytearray:
3101
3102 Bytearray Objects
3103 -----------------
3104
3105 .. index:: pair: object; bytearray
3106
3107 :class:`bytearray` objects are a mutable counterpart to :class:`bytes`
3108 objects.
3109
3110 .. class:: bytearray(source=b'')
3111 bytearray(source, encoding, errors='strict')
3112
3113 There is no dedicated literal syntax for bytearray objects, instead
3114 they are always created by calling the constructor:
3115
3116 * Creating an empty instance: ``bytearray()``
3117 * Creating a zero-filled instance with a given length: ``bytearray(10)``
3118 * From an iterable of integers: ``bytearray(range(20))``
3119 * Copying existing binary data via the buffer protocol: ``bytearray(b'Hi!')``
3120
3121 As bytearray objects are mutable, they support the
3122 :ref:`mutable <typesseq-mutable>` sequence operations in addition to the
3123 common bytes and bytearray operations described in :ref:`bytes-methods`.
3124
3125 Also see the :ref:`bytearray <func-bytearray>` built-in.
3126
3127 Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal
3128 numbers are a commonly used format for describing binary data. Accordingly,
3129 the bytearray type has an additional class method to read data in that format:
3130
3131 .. classmethod:: fromhex(string, /)
3132
3133 This :class:`bytearray` class method returns bytearray object, decoding
3134 the given string object. The string must contain two hexadecimal digits
3135 per byte, with ASCII whitespace being ignored.
3136
3137 >>> bytearray.fromhex('2Ef0 F1f2 ')
3138 bytearray(b'.\xf0\xf1\xf2')
3139
3140 .. versionchanged:: 3.7
3141 :meth:`bytearray.fromhex` now skips all ASCII whitespace in the string,
3142 not just spaces.
3143
3144 A reverse conversion function exists to transform a bytearray object into its
3145 hexadecimal representation.
3146
3147 .. method:: hex(*, bytes_per_sep=1)
3148 hex(sep, bytes_per_sep=1)
3149
3150 Return a string object containing two hexadecimal digits for each
3151 byte in the instance.
3152
3153 >>> bytearray(b'\xf0\xf1\xf2').hex()
3154 'f0f1f2'
3155
3156 .. versionadded:: 3.5
3157
3158 .. versionchanged:: 3.8
3159 Similar to :meth:`bytes.hex`, :meth:`bytearray.hex` now supports
3160 optional *sep* and *bytes_per_sep* parameters to insert separators
3161 between bytes in the hex output.
3162
3163 Since bytearray objects are sequences of integers (akin to a list), for a
3164 bytearray object *b*, ``b[0]`` will be an integer, while ``b[0:1]`` will be
3165 a bytearray object of length 1. (This contrasts with text strings, where
3166 both indexing and slicing will produce a string of length 1)
3167
3168 The representation of bytearray objects uses the bytes literal format
3169 (``bytearray(b'...')``) since it is often more useful than e.g.
3170 ``bytearray([46, 46, 46])``. You can always convert a bytearray object into
3171 a list of integers using ``list(b)``.
3172
3173
3174 .. _bytes-methods:
3175
3176 Bytes and Bytearray Operations
3177 ------------------------------
3178
3179 .. index:: pair: bytes; methods
3180 pair: bytearray; methods
3181
3182 Both bytes and bytearray objects support the :ref:`common <typesseq-common>`
3183 sequence operations. They interoperate not just with operands of the same
3184 type, but with any :term:`bytes-like object`. Due to this flexibility, they can be
3185 freely mixed in operations without causing errors. However, the return type
3186 of the result may depend on the order of operands.
3187
3188 .. note::
3189
3190 The methods on bytes and bytearray objects don't accept strings as their
3191 arguments, just as the methods on strings don't accept bytes as their
3192 arguments. For example, you have to write::
3193
3194 a = "abc"
3195 b = a.replace("a", "f")
3196
3197 and::
3198
3199 a = b"abc"
3200 b = a.replace(b"a", b"f")
3201
3202 Some bytes and bytearray operations assume the use of ASCII compatible
3203 binary formats, and hence should be avoided when working with arbitrary
3204 binary data. These restrictions are covered below.
3205
3206 .. note::
3207 Using these ASCII based operations to manipulate binary data that is not
3208 stored in an ASCII based format may lead to data corruption.
3209
3210 The following methods on bytes and bytearray objects can be used with
3211 arbitrary binary data.
3212
3213 .. method:: bytes.count(sub[, start[, end]])
3214 bytearray.count(sub[, start[, end]])
3215
3216 Return the number of non-overlapping occurrences of subsequence *sub* in
3217 the range [*start*, *end*]. Optional arguments *start* and *end* are
3218 interpreted as in slice notation.
3219
3220 The subsequence to search for may be any :term:`bytes-like object` or an
3221 integer in the range 0 to 255.
3222
3223 If *sub* is empty, returns the number of empty slices between characters
3224 which is the length of the bytes object plus one.
3225
3226 .. versionchanged:: 3.3
3227 Also accept an integer in the range 0 to 255 as the subsequence.
3228
3229
3230 .. method:: bytes.removeprefix(prefix, /)
3231 bytearray.removeprefix(prefix, /)
3232
3233 If the binary data starts with the *prefix* string, return
3234 ``bytes[len(prefix):]``. Otherwise, return a copy of the original
3235 binary data::
3236
3237 >>> b'TestHook'.removeprefix(b'Test')
3238 b'Hook'
3239 >>> b'BaseTestCase'.removeprefix(b'Test')
3240 b'BaseTestCase'
3241
3242 The *prefix* may be any :term:`bytes-like object`.
3243
3244 .. note::
3245
3246 The bytearray version of this method does *not* operate in place -
3247 it always produces a new object, even if no changes were made.
3248
3249 .. versionadded:: 3.9
3250
3251
3252 .. method:: bytes.removesuffix(suffix, /)
3253 bytearray.removesuffix(suffix, /)
3254
3255 If the binary data ends with the *suffix* string and that *suffix* is
3256 not empty, return ``bytes[:-len(suffix)]``. Otherwise, return a copy of
3257 the original binary data::
3258
3259 >>> b'MiscTests'.removesuffix(b'Tests')
3260 b'Misc'
3261 >>> b'TmpDirMixin'.removesuffix(b'Tests')
3262 b'TmpDirMixin'
3263
3264 The *suffix* may be any :term:`bytes-like object`.
3265
3266 .. note::
3267
3268 The bytearray version of this method does *not* operate in place -
3269 it always produces a new object, even if no changes were made.
3270
3271 .. versionadded:: 3.9
3272
3273
3274 .. method:: bytes.decode(encoding="utf-8", errors="strict")
3275 bytearray.decode(encoding="utf-8", errors="strict")
3276
3277 Return the bytes decoded to a :class:`str`.
3278
3279 *encoding* defaults to ``'utf-8'``;
3280 see :ref:`standard-encodings` for possible values.
3281
3282 *errors* controls how decoding errors are handled.
3283 If ``'strict'`` (the default), a :exc:`UnicodeError` exception is raised.
3284 Other possible values are ``'ignore'``, ``'replace'``,
3285 and any other name registered via :func:`codecs.register_error`.
3286 See :ref:`error-handlers` for details.
3287
3288 For performance reasons, the value of *errors* is not checked for validity
3289 unless a decoding error actually occurs,
3290 :ref:`devmode` is enabled or a :ref:`debug build <debug-build>` is used.
3291
3292 .. note::
3293
3294 Passing the *encoding* argument to :class:`str` allows decoding any
3295 :term:`bytes-like object` directly, without needing to make a temporary
3296 :class:`!bytes` or :class:`!bytearray` object.
3297
3298 .. versionchanged:: 3.1
3299 Added support for keyword arguments.
3300
3301 .. versionchanged:: 3.9
3302 The value of the *errors* argument is now checked in :ref:`devmode` and
3303 in :ref:`debug mode <debug-build>`.
3304
3305
3306 .. method:: bytes.endswith(suffix[, start[, end]])
3307 bytearray.endswith(suffix[, start[, end]])
3308
3309 Return ``True`` if the binary data ends with the specified *suffix*,
3310 otherwise return ``False``. *suffix* can also be a tuple of suffixes to
3311 look for. With optional *start*, test beginning at that position. With
3312 optional *end*, stop comparing at that position.
3313
3314 The suffix(es) to search for may be any :term:`bytes-like object`.
3315
3316
3317 .. method:: bytes.find(sub[, start[, end]])
3318 bytearray.find(sub[, start[, end]])
3319
3320 Return the lowest index in the data where the subsequence *sub* is found,
3321 such that *sub* is contained in the slice ``s[start:end]``. Optional
3322 arguments *start* and *end* are interpreted as in slice notation. Return
3323 ``-1`` if *sub* is not found.
3324
3325 The subsequence to search for may be any :term:`bytes-like object` or an
3326 integer in the range 0 to 255.
3327
3328 .. note::
3329
3330 The :meth:`~bytes.find` method should be used only if you need to know the
3331 position of *sub*. To check if *sub* is a substring or not, use the
3332 :keyword:`in` operator::
3333
3334 >>> b'Py' in b'Python'
3335 True
3336
3337 .. versionchanged:: 3.3
3338 Also accept an integer in the range 0 to 255 as the subsequence.
3339
3340
3341 .. method:: bytes.index(sub[, start[, end]])
3342 bytearray.index(sub[, start[, end]])
3343
3344 Like :meth:`~bytes.find`, but raise :exc:`ValueError` when the
3345 subsequence is not found.
3346
3347 The subsequence to search for may be any :term:`bytes-like object` or an
3348 integer in the range 0 to 255.
3349
3350 .. versionchanged:: 3.3
3351 Also accept an integer in the range 0 to 255 as the subsequence.
3352
3353
3354 .. method:: bytes.join(iterable, /)
3355 bytearray.join(iterable, /)
3356
3357 Return a bytes or bytearray object which is the concatenation of the
3358 binary data sequences in *iterable*. A :exc:`TypeError` will be raised
3359 if there are any values in *iterable* that are not :term:`bytes-like
3360 objects <bytes-like object>`, including :class:`str` objects. The
3361 separator between elements is the contents of the bytes or
3362 bytearray object providing this method.
3363
3364
3365 .. staticmethod:: bytes.maketrans(from, to, /)
3366 bytearray.maketrans(from, to, /)
3367
3368 This static method returns a translation table usable for
3369 :meth:`bytes.translate` that will map each character in *from* into the
3370 character at the same position in *to*; *from* and *to* must both be
3371 :term:`bytes-like objects <bytes-like object>` and have the same length.
3372
3373 .. versionadded:: 3.1
3374
3375
3376 .. method:: bytes.partition(sep, /)
3377 bytearray.partition(sep, /)
3378
3379 Split the sequence at the first occurrence of *sep*, and return a 3-tuple
3380 containing the part before the separator, the separator itself or its
3381 bytearray copy, and the part after the separator.
3382 If the separator is not found, return a 3-tuple
3383 containing a copy of the original sequence, followed by two empty bytes or
3384 bytearray objects.
3385
3386 The separator to search for may be any :term:`bytes-like object`.
3387
3388
3389 .. method:: bytes.replace(old, new, count=-1, /)
3390 bytearray.replace(old, new, count=-1, /)
3391
3392 Return a copy of the sequence with all occurrences of subsequence *old*
3393 replaced by *new*. If the optional argument *count* is given, only the
3394 first *count* occurrences are replaced.
3395
3396 The subsequence to search for and its replacement may be any
3397 :term:`bytes-like object`.
3398
3399 .. note::
3400
3401 The bytearray version of this method does *not* operate in place - it
3402 always produces a new object, even if no changes were made.
3403
3404
3405 .. method:: bytes.rfind(sub[, start[, end]])
3406 bytearray.rfind(sub[, start[, end]])
3407
3408 Return the highest index in the sequence where the subsequence *sub* is
3409 found, such that *sub* is contained within ``s[start:end]``. Optional
3410 arguments *start* and *end* are interpreted as in slice notation. Return
3411 ``-1`` on failure.
3412
3413 The subsequence to search for may be any :term:`bytes-like object` or an
3414 integer in the range 0 to 255.
3415
3416 .. versionchanged:: 3.3
3417 Also accept an integer in the range 0 to 255 as the subsequence.
3418
3419
3420 .. method:: bytes.rindex(sub[, start[, end]])
3421 bytearray.rindex(sub[, start[, end]])
3422
3423 Like :meth:`~bytes.rfind` but raises :exc:`ValueError` when the
3424 subsequence *sub* is not found.
3425
3426 The subsequence to search for may be any :term:`bytes-like object` or an
3427 integer in the range 0 to 255.
3428
3429 .. versionchanged:: 3.3
3430 Also accept an integer in the range 0 to 255 as the subsequence.
3431
3432
3433 .. method:: bytes.rpartition(sep, /)
3434 bytearray.rpartition(sep, /)
3435
3436 Split the sequence at the last occurrence of *sep*, and return a 3-tuple
3437 containing the part before the separator, the separator itself or its
3438 bytearray copy, and the part after the separator.
3439 If the separator is not found, return a 3-tuple
3440 containing two empty bytes or bytearray objects, followed by a copy of the
3441 original sequence.
3442
3443 The separator to search for may be any :term:`bytes-like object`.
3444
3445
3446 .. method:: bytes.startswith(prefix[, start[, end]])
3447 bytearray.startswith(prefix[, start[, end]])
3448
3449 Return ``True`` if the binary data starts with the specified *prefix*,
3450 otherwise return ``False``. *prefix* can also be a tuple of prefixes to
3451 look for. With optional *start*, test beginning at that position. With
3452 optional *end*, stop comparing at that position.
3453
3454 The prefix(es) to search for may be any :term:`bytes-like object`.
3455
3456
3457 .. method:: bytes.translate(table, /, delete=b'')
3458 bytearray.translate(table, /, delete=b'')
3459
3460 Return a copy of the bytes or bytearray object where all bytes occurring in
3461 the optional argument *delete* are removed, and the remaining bytes have
3462 been mapped through the given translation table, which must be a bytes
3463 object of length 256.
3464
3465 You can use the :func:`bytes.maketrans` method to create a translation
3466 table.
3467
3468 Set the *table* argument to ``None`` for translations that only delete
3469 characters::
3470
3471 >>> b'read this short text'.translate(None, b'aeiou')
3472 b'rd ths shrt txt'
3473
3474 .. versionchanged:: 3.6
3475 *delete* is now supported as a keyword argument.
3476
3477
3478 The following methods on bytes and bytearray objects have default behaviours
3479 that assume the use of ASCII compatible binary formats, but can still be used
3480 with arbitrary binary data by passing appropriate arguments. Note that all of
3481 the bytearray methods in this section do *not* operate in place, and instead
3482 produce new objects.
3483
3484 .. method:: bytes.center(width, fillbyte=b' ', /)
3485 bytearray.center(width, fillbyte=b' ', /)
3486
3487 Return a copy of the object centered in a sequence of length *width*.
3488 Padding is done using the specified *fillbyte* (default is an ASCII
3489 space). For :class:`bytes` objects, the original sequence is returned if
3490 *width* is less than or equal to ``len(s)``.
3491
3492 .. note::
3493
3494 The bytearray version of this method does *not* operate in place -
3495 it always produces a new object, even if no changes were made.
3496
3497
3498 .. method:: bytes.ljust(width, fillbyte=b' ', /)
3499 bytearray.ljust(width, fillbyte=b' ', /)
3500
3501 Return a copy of the object left justified in a sequence of length *width*.
3502 Padding is done using the specified *fillbyte* (default is an ASCII
3503 space). For :class:`bytes` objects, the original sequence is returned if
3504 *width* is less than or equal to ``len(s)``.
3505
3506 .. note::
3507
3508 The bytearray version of this method does *not* operate in place -
3509 it always produces a new object, even if no changes were made.
3510
3511
3512 .. method:: bytes.lstrip(bytes=None, /)
3513 bytearray.lstrip(bytes=None, /)
3514
3515 Return a copy of the sequence with specified leading bytes removed. The
3516 *bytes* argument is a binary sequence specifying the set of byte values to
3517 be removed. If omitted or ``None``, the *bytes* argument defaults
3518 to removing ASCII whitespace. The *bytes* argument is not a prefix;
3519 rather, all combinations of its values are stripped::
3520
3521 >>> b' spacious '.lstrip()
3522 b'spacious '
3523 >>> b'www.example.com'.lstrip(b'cmowz.')
3524 b'example.com'
3525
3526 The binary sequence of byte values to remove may be any
3527 :term:`bytes-like object`. See :meth:`~bytes.removeprefix` for a method
3528 that will remove a single prefix string rather than all of a set of
3529 characters. For example::
3530
3531 >>> b'Arthur: three!'.lstrip(b'Arthur: ')
3532 b'ee!'
3533 >>> b'Arthur: three!'.removeprefix(b'Arthur: ')
3534 b'three!'
3535
3536 .. note::
3537
3538 The bytearray version of this method does *not* operate in place -
3539 it always produces a new object, even if no changes were made.
3540
3541
3542 .. method:: bytes.rjust(width, fillbyte=b' ', /)
3543 bytearray.rjust(width, fillbyte=b' ', /)
3544
3545 Return a copy of the object right justified in a sequence of length *width*.
3546 Padding is done using the specified *fillbyte* (default is an ASCII
3547 space). For :class:`bytes` objects, the original sequence is returned if
3548 *width* is less than or equal to ``len(s)``.
3549
3550 .. note::
3551
3552 The bytearray version of this method does *not* operate in place -
3553 it always produces a new object, even if no changes were made.
3554
3555
3556 .. method:: bytes.rsplit(sep=None, maxsplit=-1)
3557 bytearray.rsplit(sep=None, maxsplit=-1)
3558
3559 Split the binary sequence into subsequences of the same type, using *sep*
3560 as the delimiter string. If *maxsplit* is given, at most *maxsplit* splits
3561 are done, the *rightmost* ones. If *sep* is not specified or ``None``,
3562 any subsequence consisting solely of ASCII whitespace is a separator.
3563 Except for splitting from the right, :meth:`rsplit` behaves like
3564 :meth:`split` which is described in detail below.
3565
3566
3567 .. method:: bytes.rstrip(bytes=None, /)
3568 bytearray.rstrip(bytes=None, /)
3569
3570 Return a copy of the sequence with specified trailing bytes removed. The
3571 *bytes* argument is a binary sequence specifying the set of byte values to
3572 be removed. If omitted or ``None``, the *bytes* argument defaults to
3573 removing ASCII whitespace. The *bytes* argument is not a suffix; rather,
3574 all combinations of its values are stripped::
3575
3576 >>> b' spacious '.rstrip()
3577 b' spacious'
3578 >>> b'mississippi'.rstrip(b'ipz')
3579 b'mississ'
3580
3581 The binary sequence of byte values to remove may be any
3582 :term:`bytes-like object`. See :meth:`~bytes.removesuffix` for a method
3583 that will remove a single suffix string rather than all of a set of
3584 characters. For example::
3585
3586 >>> b'Monty Python'.rstrip(b' Python')
3587 b'M'
3588 >>> b'Monty Python'.removesuffix(b' Python')
3589 b'Monty'
3590
3591 .. note::
3592
3593 The bytearray version of this method does *not* operate in place -
3594 it always produces a new object, even if no changes were made.
3595
3596
3597 .. method:: bytes.split(sep=None, maxsplit=-1)
3598 bytearray.split(sep=None, maxsplit=-1)
3599
3600 Split the binary sequence into subsequences of the same type, using *sep*
3601 as the delimiter string. If *maxsplit* is given and non-negative, at most
3602 *maxsplit* splits are done (thus, the list will have at most ``maxsplit+1``
3603 elements). If *maxsplit* is not specified or is ``-1``, then there is no
3604 limit on the number of splits (all possible splits are made).
3605
3606 If *sep* is given, consecutive delimiters are not grouped together and are
3607 deemed to delimit empty subsequences (for example, ``b'1,,2'.split(b',')``
3608 returns ``[b'1', b'', b'2']``). The *sep* argument may consist of a
3609 multibyte sequence as a single delimiter. Splitting an empty sequence with
3610 a specified separator returns ``[b'']`` or ``[bytearray(b'')]`` depending
3611 on the type of object being split. The *sep* argument may be any
3612 :term:`bytes-like object`.
3613
3614 For example::
3615
3616 >>> b'1,2,3'.split(b',')
3617 [b'1', b'2', b'3']
3618 >>> b'1,2,3'.split(b',', maxsplit=1)
3619 [b'1', b'2,3']
3620 >>> b'1,2,,3,'.split(b',')
3621 [b'1', b'2', b'', b'3', b'']
3622 >>> b'1<>2<>3<4'.split(b'<>')
3623 [b'1', b'2', b'3<4']
3624
3625 If *sep* is not specified or is ``None``, a different splitting algorithm
3626 is applied: runs of consecutive ASCII whitespace are regarded as a single
3627 separator, and the result will contain no empty strings at the start or
3628 end if the sequence has leading or trailing whitespace. Consequently,
3629 splitting an empty sequence or a sequence consisting solely of ASCII
3630 whitespace without a specified separator returns ``[]``.
3631
3632 For example::
3633
3634
3635 >>> b'1 2 3'.split()
3636 [b'1', b'2', b'3']
3637 >>> b'1 2 3'.split(maxsplit=1)
3638 [b'1', b'2 3']
3639 >>> b' 1 2 3 '.split()
3640 [b'1', b'2', b'3']
3641
3642
3643 .. method:: bytes.strip(bytes=None, /)
3644 bytearray.strip(bytes=None, /)
3645
3646 Return a copy of the sequence with specified leading and trailing bytes
3647 removed. The *bytes* argument is a binary sequence specifying the set of
3648 byte values to be removed. If omitted or ``None``, the *bytes*
3649 argument defaults to removing ASCII whitespace. The *bytes* argument is
3650 not a prefix or suffix; rather, all combinations of its values are
3651 stripped::
3652
3653 >>> b' spacious '.strip()
3654 b'spacious'
3655 >>> b'www.example.com'.strip(b'cmowz.')
3656 b'example'
3657
3658 The binary sequence of byte values to remove may be any
3659 :term:`bytes-like object`.
3660
3661 .. note::
3662
3663 The bytearray version of this method does *not* operate in place -
3664 it always produces a new object, even if no changes were made.
3665
3666
3667 The following methods on bytes and bytearray objects assume the use of ASCII
3668 compatible binary formats and should not be applied to arbitrary binary data.
3669 Note that all of the bytearray methods in this section do *not* operate in
3670 place, and instead produce new objects.
3671
3672 .. method:: bytes.capitalize()
3673 bytearray.capitalize()
3674
3675 Return a copy of the sequence with each byte interpreted as an ASCII
3676 character, and the first byte capitalized and the rest lowercased.
3677 Non-ASCII byte values are passed through unchanged.
3678
3679 .. note::
3680
3681 The bytearray version of this method does *not* operate in place - it
3682 always produces a new object, even if no changes were made.
3683
3684
3685 .. method:: bytes.expandtabs(tabsize=8)
3686 bytearray.expandtabs(tabsize=8)
3687
3688 Return a copy of the sequence where all ASCII tab characters are replaced
3689 by one or more ASCII spaces, depending on the current column and the given
3690 tab size. Tab positions occur every *tabsize* bytes (default is 8,
3691 giving tab positions at columns 0, 8, 16 and so on). To expand the
3692 sequence, the current column is set to zero and the sequence is examined
3693 byte by byte. If the byte is an ASCII tab character (``b'\t'``), one or
3694 more space characters are inserted in the result until the current column
3695 is equal to the next tab position. (The tab character itself is not
3696 copied.) If the current byte is an ASCII newline (``b'\n'``) or
3697 carriage return (``b'\r'``), it is copied and the current column is reset
3698 to zero. Any other byte value is copied unchanged and the current column
3699 is incremented by one regardless of how the byte value is represented when
3700 printed::
3701
3702 >>> b'01\t012\t0123\t01234'.expandtabs()
3703 b'01 012 0123 01234'
3704 >>> b'01\t012\t0123\t01234'.expandtabs(4)
3705 b'01 012 0123 01234'
3706
3707 .. note::
3708
3709 The bytearray version of this method does *not* operate in place - it
3710 always produces a new object, even if no changes were made.
3711
3712
3713 .. method:: bytes.isalnum()
3714 bytearray.isalnum()
3715
3716 Return ``True`` if all bytes in the sequence are alphabetical ASCII characters
3717 or ASCII decimal digits and the sequence is not empty, ``False`` otherwise.
3718 Alphabetic ASCII characters are those byte values in the sequence
3719 ``b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'``. ASCII decimal
3720 digits are those byte values in the sequence ``b'0123456789'``.
3721
3722 For example::
3723
3724 >>> b'ABCabc1'.isalnum()
3725 True
3726 >>> b'ABC abc1'.isalnum()
3727 False
3728
3729
3730 .. method:: bytes.isalpha()
3731 bytearray.isalpha()
3732
3733 Return ``True`` if all bytes in the sequence are alphabetic ASCII characters
3734 and the sequence is not empty, ``False`` otherwise. Alphabetic ASCII
3735 characters are those byte values in the sequence
3736 ``b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'``.
3737
3738 For example::
3739
3740 >>> b'ABCabc'.isalpha()
3741 True
3742 >>> b'ABCabc1'.isalpha()
3743 False
3744
3745
3746 .. method:: bytes.isascii()
3747 bytearray.isascii()
3748
3749 Return ``True`` if the sequence is empty or all bytes in the sequence are ASCII,
3750 ``False`` otherwise.
3751 ASCII bytes are in the range 0-0x7F.
3752
3753 .. versionadded:: 3.7
3754
3755
3756 .. method:: bytes.isdigit()
3757 bytearray.isdigit()
3758
3759 Return ``True`` if all bytes in the sequence are ASCII decimal digits
3760 and the sequence is not empty, ``False`` otherwise. ASCII decimal digits are
3761 those byte values in the sequence ``b'0123456789'``.
3762
3763 For example::
3764
3765 >>> b'1234'.isdigit()
3766 True
3767 >>> b'1.23'.isdigit()
3768 False
3769
3770
3771 .. method:: bytes.islower()
3772 bytearray.islower()
3773
3774 Return ``True`` if there is at least one lowercase ASCII character
3775 in the sequence and no uppercase ASCII characters, ``False`` otherwise.
3776
3777 For example::
3778
3779 >>> b'hello world'.islower()
3780 True
3781 >>> b'Hello world'.islower()
3782 False
3783
3784 Lowercase ASCII characters are those byte values in the sequence
3785 ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters
3786 are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``.
3787
3788
3789 .. method:: bytes.isspace()
3790 bytearray.isspace()
3791
3792 Return ``True`` if all bytes in the sequence are ASCII whitespace and the
3793 sequence is not empty, ``False`` otherwise. ASCII whitespace characters are
3794 those byte values in the sequence ``b' \t\n\r\x0b\f'`` (space, tab, newline,
3795 carriage return, vertical tab, form feed).
3796
3797
3798 .. method:: bytes.istitle()
3799 bytearray.istitle()
3800
3801 Return ``True`` if the sequence is ASCII titlecase and the sequence is not
3802 empty, ``False`` otherwise. See :meth:`bytes.title` for more details on the
3803 definition of "titlecase".
3804
3805 For example::
3806
3807 >>> b'Hello World'.istitle()
3808 True
3809 >>> b'Hello world'.istitle()
3810 False
3811
3812
3813 .. method:: bytes.isupper()
3814 bytearray.isupper()
3815
3816 Return ``True`` if there is at least one uppercase alphabetic ASCII character
3817 in the sequence and no lowercase ASCII characters, ``False`` otherwise.
3818
3819 For example::
3820
3821 >>> b'HELLO WORLD'.isupper()
3822 True
3823 >>> b'Hello world'.isupper()
3824 False
3825
3826 Lowercase ASCII characters are those byte values in the sequence
3827 ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters
3828 are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``.
3829
3830
3831 .. method:: bytes.lower()
3832 bytearray.lower()
3833
3834 Return a copy of the sequence with all the uppercase ASCII characters
3835 converted to their corresponding lowercase counterpart.
3836
3837 For example::
3838
3839 >>> b'Hello World'.lower()
3840 b'hello world'
3841
3842 Lowercase ASCII characters are those byte values in the sequence
3843 ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters
3844 are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``.
3845
3846 .. note::
3847
3848 The bytearray version of this method does *not* operate in place - it
3849 always produces a new object, even if no changes were made.
3850
3851
3852 .. index::
3853 single: universal newlines; bytes.splitlines method
3854 single: universal newlines; bytearray.splitlines method
3855
3856 .. method:: bytes.splitlines(keepends=False)
3857 bytearray.splitlines(keepends=False)
3858
3859 Return a list of the lines in the binary sequence, breaking at ASCII
3860 line boundaries. This method uses the :term:`universal newlines` approach
3861 to splitting lines. Line breaks are not included in the resulting list
3862 unless *keepends* is given and true.
3863
3864 For example::
3865
3866 >>> b'ab c\n\nde fg\rkl\r\n'.splitlines()
3867 [b'ab c', b'', b'de fg', b'kl']
3868 >>> b'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
3869 [b'ab c\n', b'\n', b'de fg\r', b'kl\r\n']
3870
3871 Unlike :meth:`~bytes.split` when a delimiter string *sep* is given, this
3872 method returns an empty list for the empty string, and a terminal line
3873 break does not result in an extra line::
3874
3875 >>> b"".split(b'\n'), b"Two lines\n".split(b'\n')
3876 ([b''], [b'Two lines', b''])
3877 >>> b"".splitlines(), b"One line\n".splitlines()
3878 ([], [b'One line'])
3879
3880
3881 .. method:: bytes.swapcase()
3882 bytearray.swapcase()
3883
3884 Return a copy of the sequence with all the lowercase ASCII characters
3885 converted to their corresponding uppercase counterpart and vice-versa.
3886
3887 For example::
3888
3889 >>> b'Hello World'.swapcase()
3890 b'hELLO wORLD'
3891
3892 Lowercase ASCII characters are those byte values in the sequence
3893 ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters
3894 are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``.
3895
3896 Unlike :func:`str.swapcase`, it is always the case that
3897 ``bin.swapcase().swapcase() == bin`` for the binary versions. Case
3898 conversions are symmetrical in ASCII, even though that is not generally
3899 true for arbitrary Unicode code points.
3900
3901 .. note::
3902
3903 The bytearray version of this method does *not* operate in place - it
3904 always produces a new object, even if no changes were made.
3905
3906
3907 .. method:: bytes.title()
3908 bytearray.title()
3909
3910 Return a titlecased version of the binary sequence where words start with
3911 an uppercase ASCII character and the remaining characters are lowercase.
3912 Uncased byte values are left unmodified.
3913
3914 For example::
3915
3916 >>> b'Hello world'.title()
3917 b'Hello World'
3918
3919 Lowercase ASCII characters are those byte values in the sequence
3920 ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters
3921 are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``.
3922 All other byte values are uncased.
3923
3924 The algorithm uses a simple language-independent definition of a word as
3925 groups of consecutive letters. The definition works in many contexts but
3926 it means that apostrophes in contractions and possessives form word
3927 boundaries, which may not be the desired result::
3928
3929 >>> b"they're bill's friends from the UK".title()
3930 b"They'Re Bill'S Friends From The Uk"
3931
3932 A workaround for apostrophes can be constructed using regular expressions::
3933
3934 >>> import re
3935 >>> def titlecase(s):
3936 ... return re.sub(rb"[A-Za-z]+('[A-Za-z]+)?",
3937 ... lambda mo: mo.group(0)[0:1].upper() +
3938 ... mo.group(0)[1:].lower(),
3939 ... s)
3940 ...
3941 >>> titlecase(b"they're bill's friends.")
3942 b"They're Bill's Friends."
3943
3944 .. note::
3945
3946 The bytearray version of this method does *not* operate in place - it
3947 always produces a new object, even if no changes were made.
3948
3949
3950 .. method:: bytes.upper()
3951 bytearray.upper()
3952
3953 Return a copy of the sequence with all the lowercase ASCII characters
3954 converted to their corresponding uppercase counterpart.
3955
3956 For example::
3957
3958 >>> b'Hello World'.upper()
3959 b'HELLO WORLD'
3960
3961 Lowercase ASCII characters are those byte values in the sequence
3962 ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters
3963 are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``.
3964
3965 .. note::
3966
3967 The bytearray version of this method does *not* operate in place - it
3968 always produces a new object, even if no changes were made.
3969
3970
3971 .. method:: bytes.zfill(width, /)
3972 bytearray.zfill(width, /)
3973
3974 Return a copy of the sequence left filled with ASCII ``b'0'`` digits to
3975 make a sequence of length *width*. A leading sign prefix (``b'+'``/
3976 ``b'-'``) is handled by inserting the padding *after* the sign character
3977 rather than before. For :class:`bytes` objects, the original sequence is
3978 returned if *width* is less than or equal to ``len(seq)``.
3979
3980 For example::
3981
3982 >>> b"42".zfill(5)
3983 b'00042'
3984 >>> b"-42".zfill(5)
3985 b'-0042'
3986
3987 .. note::
3988
3989 The bytearray version of this method does *not* operate in place - it
3990 always produces a new object, even if no changes were made.
3991
3992
3993 .. _bytes-formatting:
3994
3995 ``printf``-style Bytes Formatting
3996 ----------------------------------
3997
3998 .. index::
3999 single: formatting; bytes (%)
4000 single: formatting; bytearray (%)
4001 single: interpolation; bytes (%)
4002 single: interpolation; bytearray (%)
4003 single: bytes; formatting
4004 single: bytearray; formatting
4005 single: bytes; interpolation
4006 single: bytearray; interpolation
4007 single: printf-style formatting
4008 single: sprintf-style formatting
4009 single: % (percent); printf-style formatting
4010
4011 .. note::
4012
4013 The formatting operations described here exhibit a variety of quirks that
4014 lead to a number of common errors (such as failing to display tuples and
4015 dictionaries correctly). If the value being printed may be a tuple or
4016 dictionary, wrap it in a tuple.
4017
4018 Bytes objects (``bytes``/``bytearray``) have one unique built-in operation:
4019 the ``%`` operator (modulo).
4020 This is also known as the bytes *formatting* or *interpolation* operator.
4021 Given ``format % values`` (where *format* is a bytes object), ``%`` conversion
4022 specifications in *format* are replaced with zero or more elements of *values*.
4023 The effect is similar to using the :c:func:`sprintf` in the C language.
4024
4025 If *format* requires a single argument, *values* may be a single non-tuple
4026 object. [5]_ Otherwise, *values* must be a tuple with exactly the number of
4027 items specified by the format bytes object, or a single mapping object (for
4028 example, a dictionary).
4029
4030 .. index::
4031 single: () (parentheses); in printf-style formatting
4032 single: * (asterisk); in printf-style formatting
4033 single: . (dot); in printf-style formatting
4034
4035 A conversion specifier contains two or more characters and has the following
4036 components, which must occur in this order:
4037
4038 #. The ``'%'`` character, which marks the start of the specifier.
4039
4040 #. Mapping key (optional), consisting of a parenthesised sequence of characters
4041 (for example, ``(somename)``).
4042
4043 #. Conversion flags (optional), which affect the result of some conversion
4044 types.
4045
4046 #. Minimum field width (optional). If specified as an ``'*'`` (asterisk), the
4047 actual width is read from the next element of the tuple in *values*, and the
4048 object to convert comes after the minimum field width and optional precision.
4049
4050 #. Precision (optional), given as a ``'.'`` (dot) followed by the precision. If
4051 specified as ``'*'`` (an asterisk), the actual precision is read from the next
4052 element of the tuple in *values*, and the value to convert comes after the
4053 precision.
4054
4055 #. Length modifier (optional).
4056
4057 #. Conversion type.
4058
4059 When the right argument is a dictionary (or other mapping type), then the
4060 formats in the bytes object *must* include a parenthesised mapping key into that
4061 dictionary inserted immediately after the ``'%'`` character. The mapping key
4062 selects the value to be formatted from the mapping. For example:
4063
4064 >>> print(b'%(language)s has %(number)03d quote types.' %
4065 ... {b'language': b"Python", b"number": 2})
4066 b'Python has 002 quote types.'
4067
4068 In this case no ``*`` specifiers may occur in a format (since they require a
4069 sequential parameter list).
4070
4071 The conversion flag characters are:
4072
4073 .. index::
4074 single: # (hash); in printf-style formatting
4075 single: - (minus); in printf-style formatting
4076 single: + (plus); in printf-style formatting
4077 single: space; in printf-style formatting
4078
4079 +---------+---------------------------------------------------------------------+
4080 | Flag | Meaning |
4081 +=========+=====================================================================+
4082 | ``'#'`` | The value conversion will use the "alternate form" (where defined |
4083 | | below). |
4084 +---------+---------------------------------------------------------------------+
4085 | ``'0'`` | The conversion will be zero padded for numeric values. |
4086 +---------+---------------------------------------------------------------------+
4087 | ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` |
4088 | | conversion if both are given). |
4089 +---------+---------------------------------------------------------------------+
4090 | ``' '`` | (a space) A blank should be left before a positive number (or empty |
4091 | | string) produced by a signed conversion. |
4092 +---------+---------------------------------------------------------------------+
4093 | ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion |
4094 | | (overrides a "space" flag). |
4095 +---------+---------------------------------------------------------------------+
4096
4097 A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it
4098 is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``.
4099
4100 The conversion types are:
4101
4102 +------------+-----------------------------------------------------+-------+
4103 | Conversion | Meaning | Notes |
4104 +============+=====================================================+=======+
4105 | ``'d'`` | Signed integer decimal. | |
4106 +------------+-----------------------------------------------------+-------+
4107 | ``'i'`` | Signed integer decimal. | |
4108 +------------+-----------------------------------------------------+-------+
4109 | ``'o'`` | Signed octal value. | \(1) |
4110 +------------+-----------------------------------------------------+-------+
4111 | ``'u'`` | Obsolete type -- it is identical to ``'d'``. | \(8) |
4112 +------------+-----------------------------------------------------+-------+
4113 | ``'x'`` | Signed hexadecimal (lowercase). | \(2) |
4114 +------------+-----------------------------------------------------+-------+
4115 | ``'X'`` | Signed hexadecimal (uppercase). | \(2) |
4116 +------------+-----------------------------------------------------+-------+
4117 | ``'e'`` | Floating-point exponential format (lowercase). | \(3) |
4118 +------------+-----------------------------------------------------+-------+
4119 | ``'E'`` | Floating-point exponential format (uppercase). | \(3) |
4120 +------------+-----------------------------------------------------+-------+
4121 | ``'f'`` | Floating-point decimal format. | \(3) |
4122 +------------+-----------------------------------------------------+-------+
4123 | ``'F'`` | Floating-point decimal format. | \(3) |
4124 +------------+-----------------------------------------------------+-------+
4125 | ``'g'`` | Floating-point format. Uses lowercase exponential | \(4) |
4126 | | format if exponent is less than -4 or not less than | |
4127 | | precision, decimal format otherwise. | |
4128 +------------+-----------------------------------------------------+-------+
4129 | ``'G'`` | Floating-point format. Uses uppercase exponential | \(4) |
4130 | | format if exponent is less than -4 or not less than | |
4131 | | precision, decimal format otherwise. | |
4132 +------------+-----------------------------------------------------+-------+
4133 | ``'c'`` | Single byte (accepts integer or single | |
4134 | | byte objects). | |
4135 +------------+-----------------------------------------------------+-------+
4136 | ``'b'`` | Bytes (any object that follows the | \(5) |
4137 | | :ref:`buffer protocol <bufferobjects>` or has | |
4138 | | :meth:`~object.__bytes__`). | |
4139 +------------+-----------------------------------------------------+-------+
4140 | ``'s'`` | ``'s'`` is an alias for ``'b'`` and should only | \(6) |
4141 | | be used for Python2/3 code bases. | |
4142 +------------+-----------------------------------------------------+-------+
4143 | ``'a'`` | Bytes (converts any Python object using | \(5) |
4144 | | ``repr(obj).encode('ascii', 'backslashreplace')``). | |
4145 +------------+-----------------------------------------------------+-------+
4146 | ``'r'`` | ``'r'`` is an alias for ``'a'`` and should only | \(7) |
4147 | | be used for Python2/3 code bases. | |
4148 +------------+-----------------------------------------------------+-------+
4149 | ``'%'`` | No argument is converted, results in a ``'%'`` | |
4150 | | character in the result. | |
4151 +------------+-----------------------------------------------------+-------+
4152
4153 Notes:
4154
4155 (1)
4156 The alternate form causes a leading octal specifier (``'0o'``) to be
4157 inserted before the first digit.
4158
4159 (2)
4160 The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether
4161 the ``'x'`` or ``'X'`` format was used) to be inserted before the first digit.
4162
4163 (3)
4164 The alternate form causes the result to always contain a decimal point, even if
4165 no digits follow it.
4166
4167 The precision determines the number of digits after the decimal point and
4168 defaults to 6.
4169
4170 (4)
4171 The alternate form causes the result to always contain a decimal point, and
4172 trailing zeroes are not removed as they would otherwise be.
4173
4174 The precision determines the number of significant digits before and after the
4175 decimal point and defaults to 6.
4176
4177 (5)
4178 If precision is ``N``, the output is truncated to ``N`` characters.
4179
4180 (6)
4181 ``b'%s'`` is deprecated, but will not be removed during the 3.x series.
4182
4183 (7)
4184 ``b'%r'`` is deprecated, but will not be removed during the 3.x series.
4185
4186 (8)
4187 See :pep:`237`.
4188
4189 .. note::
4190
4191 The bytearray version of this method does *not* operate in place - it
4192 always produces a new object, even if no changes were made.
4193
4194 .. seealso::
4195
4196 :pep:`461` - Adding % formatting to bytes and bytearray
4197
4198 .. versionadded:: 3.5
4199
4200 .. _typememoryview:
4201
4202 Memory Views
4203 ------------
4204
4205 :class:`memoryview` objects allow Python code to access the internal data
4206 of an object that supports the :ref:`buffer protocol <bufferobjects>` without
4207 copying.
4208
4209 .. class:: memoryview(object)
4210
4211 Create a :class:`memoryview` that references *object*. *object* must
4212 support the buffer protocol. Built-in objects that support the buffer
4213 protocol include :class:`bytes` and :class:`bytearray`.
4214
4215 A :class:`memoryview` has the notion of an *element*, which is the
4216 atomic memory unit handled by the originating *object*. For many simple
4217 types such as :class:`bytes` and :class:`bytearray`, an element is a single
4218 byte, but other types such as :class:`array.array` may have bigger elements.
4219
4220 ``len(view)`` is equal to the length of :class:`~memoryview.tolist`, which
4221 is the nested list representation of the view. If ``view.ndim = 1``,
4222 this is equal to the number of elements in the view.
4223
4224 .. versionchanged:: 3.12
4225 If ``view.ndim == 0``, ``len(view)`` now raises :exc:`TypeError` instead of returning 1.
4226
4227 The :class:`~memoryview.itemsize` attribute will give you the number of
4228 bytes in a single element.
4229
4230 A :class:`memoryview` supports slicing and indexing to expose its data.
4231 One-dimensional slicing will result in a subview::
4232
4233 >>> v = memoryview(b'abcefg')
4234 >>> v[1]
4235 98
4236 >>> v[-1]
4237 103
4238 >>> v[1:4]
4239 <memory at 0x7f3ddc9f4350>
4240 >>> bytes(v[1:4])
4241 b'bce'
4242
4243 If :class:`~memoryview.format` is one of the native format specifiers
4244 from the :mod:`struct` module, indexing with an integer or a tuple of
4245 integers is also supported and returns a single *element* with
4246 the correct type. One-dimensional memoryviews can be indexed
4247 with an integer or a one-integer tuple. Multi-dimensional memoryviews
4248 can be indexed with tuples of exactly *ndim* integers where *ndim* is
4249 the number of dimensions. Zero-dimensional memoryviews can be indexed
4250 with the empty tuple.
4251
4252 Here is an example with a non-byte format::
4253
4254 >>> import array
4255 >>> a = array.array('l', [-11111111, 22222222, -33333333, 44444444])
4256 >>> m = memoryview(a)
4257 >>> m[0]
4258 -11111111
4259 >>> m[-1]
4260 44444444
4261 >>> m[::2].tolist()
4262 [-11111111, -33333333]
4263
4264 If the underlying object is writable, the memoryview supports
4265 one-dimensional slice assignment. Resizing is not allowed::
4266
4267 >>> data = bytearray(b'abcefg')
4268 >>> v = memoryview(data)
4269 >>> v.readonly
4270 False
4271 >>> v[0] = ord(b'z')
4272 >>> data
4273 bytearray(b'zbcefg')
4274 >>> v[1:4] = b'123'
4275 >>> data
4276 bytearray(b'z123fg')
4277 >>> v[2:3] = b'spam'
4278 Traceback (most recent call last):
4279 File "<stdin>", line 1, in <module>
4280 ValueError: memoryview assignment: lvalue and rvalue have different structures
4281 >>> v[2:6] = b'spam'
4282 >>> data
4283 bytearray(b'z1spam')
4284
4285 One-dimensional memoryviews of :term:`hashable` (read-only) types with formats
4286 'B', 'b' or 'c' are also hashable. The hash is defined as
4287 ``hash(m) == hash(m.tobytes())``::
4288
4289 >>> v = memoryview(b'abcefg')
4290 >>> hash(v) == hash(b'abcefg')
4291 True
4292 >>> hash(v[2:4]) == hash(b'ce')
4293 True
4294 >>> hash(v[::-2]) == hash(b'abcefg'[::-2])
4295 True
4296
4297 .. versionchanged:: 3.3
4298 One-dimensional memoryviews can now be sliced.
4299 One-dimensional memoryviews with formats 'B', 'b' or 'c' are now :term:`hashable`.
4300
4301 .. versionchanged:: 3.4
4302 memoryview is now registered automatically with
4303 :class:`collections.abc.Sequence`
4304
4305 .. versionchanged:: 3.5
4306 memoryviews can now be indexed with tuple of integers.
4307
4308 :class:`memoryview` has several methods:
4309
4310 .. method:: __eq__(exporter)
4311
4312 A memoryview and a :pep:`3118` exporter are equal if their shapes are
4313 equivalent and if all corresponding values are equal when the operands'
4314 respective format codes are interpreted using :mod:`struct` syntax.
4315
4316 For the subset of :mod:`struct` format strings currently supported by
4317 :meth:`tolist`, ``v`` and ``w`` are equal if ``v.tolist() == w.tolist()``::
4318
4319 >>> import array
4320 >>> a = array.array('I', [1, 2, 3, 4, 5])
4321 >>> b = array.array('d', [1.0, 2.0, 3.0, 4.0, 5.0])
4322 >>> c = array.array('b', [5, 3, 1])
4323 >>> x = memoryview(a)
4324 >>> y = memoryview(b)
4325 >>> x == a == y == b
4326 True
4327 >>> x.tolist() == a.tolist() == y.tolist() == b.tolist()
4328 True
4329 >>> z = y[::-2]
4330 >>> z == c
4331 True
4332 >>> z.tolist() == c.tolist()
4333 True
4334
4335 If either format string is not supported by the :mod:`struct` module,
4336 then the objects will always compare as unequal (even if the format
4337 strings and buffer contents are identical)::
4338
4339 >>> from ctypes import BigEndianStructure, c_long
4340 >>> class BEPoint(BigEndianStructure):
4341 ... _fields_ = [("x", c_long), ("y", c_long)]
4342 ...
4343 >>> point = BEPoint(100, 200)
4344 >>> a = memoryview(point)
4345 >>> b = memoryview(point)
4346 >>> a == point
4347 False
4348 >>> a == b
4349 False
4350
4351 Note that, as with floating-point numbers, ``v is w`` does *not* imply
4352 ``v == w`` for memoryview objects.
4353
4354 .. versionchanged:: 3.3
4355 Previous versions compared the raw memory disregarding the item format
4356 and the logical array structure.
4357
4358 .. method:: tobytes(order='C')
4359
4360 Return the data in the buffer as a bytestring. This is equivalent to
4361 calling the :class:`bytes` constructor on the memoryview. ::
4362
4363 >>> m = memoryview(b"abc")
4364 >>> m.tobytes()
4365 b'abc'
4366 >>> bytes(m)
4367 b'abc'
4368
4369 For non-contiguous arrays the result is equal to the flattened list
4370 representation with all elements converted to bytes. :meth:`tobytes`
4371 supports all format strings, including those that are not in
4372 :mod:`struct` module syntax.
4373
4374 .. versionadded:: 3.8
4375 *order* can be {'C', 'F', 'A'}. When *order* is 'C' or 'F', the data
4376 of the original array is converted to C or Fortran order. For contiguous
4377 views, 'A' returns an exact copy of the physical memory. In particular,
4378 in-memory Fortran order is preserved. For non-contiguous views, the
4379 data is converted to C first. *order=None* is the same as *order='C'*.
4380
4381 .. method:: hex(*, bytes_per_sep=1)
4382 hex(sep, bytes_per_sep=1)
4383
4384 Return a string object containing two hexadecimal digits for each
4385 byte in the buffer. ::
4386
4387 >>> m = memoryview(b"abc")
4388 >>> m.hex()
4389 '616263'
4390
4391 .. versionadded:: 3.5
4392
4393 .. versionchanged:: 3.8
4394 Similar to :meth:`bytes.hex`, :meth:`memoryview.hex` now supports
4395 optional *sep* and *bytes_per_sep* parameters to insert separators
4396 between bytes in the hex output.
4397
4398 .. method:: tolist()
4399
4400 Return the data in the buffer as a list of elements. ::
4401
4402 >>> memoryview(b'abc').tolist()
4403 [97, 98, 99]
4404 >>> import array
4405 >>> a = array.array('d', [1.1, 2.2, 3.3])
4406 >>> m = memoryview(a)
4407 >>> m.tolist()
4408 [1.1, 2.2, 3.3]
4409
4410 .. versionchanged:: 3.3
4411 :meth:`tolist` now supports all single character native formats in
4412 :mod:`struct` module syntax as well as multi-dimensional
4413 representations.
4414
4415 .. method:: toreadonly()
4416
4417 Return a readonly version of the memoryview object. The original
4418 memoryview object is unchanged. ::
4419
4420 >>> m = memoryview(bytearray(b'abc'))
4421 >>> mm = m.toreadonly()
4422 >>> mm.tolist()
4423 [97, 98, 99]
4424 >>> mm[0] = 42
4425 Traceback (most recent call last):
4426 File "<stdin>", line 1, in <module>
4427 TypeError: cannot modify read-only memory
4428 >>> m[0] = 43
4429 >>> mm.tolist()
4430 [43, 98, 99]
4431
4432 .. versionadded:: 3.8
4433
4434 .. method:: release()
4435
4436 Release the underlying buffer exposed by the memoryview object. Many
4437 objects take special actions when a view is held on them (for example,
4438 a :class:`bytearray` would temporarily forbid resizing); therefore,
4439 calling release() is handy to remove these restrictions (and free any
4440 dangling resources) as soon as possible.
4441
4442 After this method has been called, any further operation on the view
4443 raises a :class:`ValueError` (except :meth:`release` itself which can
4444 be called multiple times)::
4445
4446 >>> m = memoryview(b'abc')
4447 >>> m.release()
4448 >>> m[0]
4449 Traceback (most recent call last):
4450 File "<stdin>", line 1, in <module>
4451 ValueError: operation forbidden on released memoryview object
4452
4453 The context management protocol can be used for a similar effect,
4454 using the ``with`` statement::
4455
4456 >>> with memoryview(b'abc') as m:
4457 ... m[0]
4458 ...
4459 97
4460 >>> m[0]
4461 Traceback (most recent call last):
4462 File "<stdin>", line 1, in <module>
4463 ValueError: operation forbidden on released memoryview object
4464
4465 .. versionadded:: 3.2
4466
4467 .. method:: cast(format, /)
4468 cast(format, shape, /)
4469
4470 Cast a memoryview to a new format or shape. *shape* defaults to
4471 ``[byte_length//new_itemsize]``, which means that the result view
4472 will be one-dimensional. The return value is a new memoryview, but
4473 the buffer itself is not copied. Supported casts are 1D -> C-:term:`contiguous`
4474 and C-contiguous -> 1D.
4475
4476 The destination format is restricted to a single element native format in
4477 :mod:`struct` syntax. One of the formats must be a byte format
4478 ('B', 'b' or 'c'). The byte length of the result must be the same
4479 as the original length.
4480 Note that all byte lengths may depend on the operating system.
4481
4482 Cast 1D/long to 1D/unsigned bytes::
4483
4484 >>> import array
4485 >>> a = array.array('l', [1,2,3])
4486 >>> x = memoryview(a)
4487 >>> x.format
4488 'l'
4489 >>> x.itemsize
4490 8
4491 >>> len(x)
4492 3
4493 >>> x.nbytes
4494 24
4495 >>> y = x.cast('B')
4496 >>> y.format
4497 'B'
4498 >>> y.itemsize
4499 1
4500 >>> len(y)
4501 24
4502 >>> y.nbytes
4503 24
4504
4505 Cast 1D/unsigned bytes to 1D/char::
4506
4507 >>> b = bytearray(b'zyz')
4508 >>> x = memoryview(b)
4509 >>> x[0] = b'a'
4510 Traceback (most recent call last):
4511 ...
4512 TypeError: memoryview: invalid type for format 'B'
4513 >>> y = x.cast('c')
4514 >>> y[0] = b'a'
4515 >>> b
4516 bytearray(b'ayz')
4517
4518 Cast 1D/bytes to 3D/ints to 1D/signed char::
4519
4520 >>> import struct
4521 >>> buf = struct.pack("i"*12, *list(range(12)))
4522 >>> x = memoryview(buf)
4523 >>> y = x.cast('i', shape=[2,2,3])
4524 >>> y.tolist()
4525 [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]
4526 >>> y.format
4527 'i'
4528 >>> y.itemsize
4529 4
4530 >>> len(y)
4531 2
4532 >>> y.nbytes
4533 48
4534 >>> z = y.cast('b')
4535 >>> z.format
4536 'b'
4537 >>> z.itemsize
4538 1
4539 >>> len(z)
4540 48
4541 >>> z.nbytes
4542 48
4543
4544 Cast 1D/unsigned long to 2D/unsigned long::
4545
4546 >>> buf = struct.pack("L"*6, *list(range(6)))
4547 >>> x = memoryview(buf)
4548 >>> y = x.cast('L', shape=[2,3])
4549 >>> len(y)
4550 2
4551 >>> y.nbytes
4552 48
4553 >>> y.tolist()
4554 [[0, 1, 2], [3, 4, 5]]
4555
4556 .. versionadded:: 3.3
4557
4558 .. versionchanged:: 3.5
4559 The source format is no longer restricted when casting to a byte view.
4560
4561 There are also several readonly attributes available:
4562
4563 .. attribute:: obj
4564
4565 The underlying object of the memoryview::
4566
4567 >>> b = bytearray(b'xyz')
4568 >>> m = memoryview(b)
4569 >>> m.obj is b
4570 True
4571
4572 .. versionadded:: 3.3
4573
4574 .. attribute:: nbytes
4575
4576 ``nbytes == product(shape) * itemsize == len(m.tobytes())``. This is
4577 the amount of space in bytes that the array would use in a contiguous
4578 representation. It is not necessarily equal to ``len(m)``::
4579
4580 >>> import array
4581 >>> a = array.array('i', [1,2,3,4,5])
4582 >>> m = memoryview(a)
4583 >>> len(m)
4584 5
4585 >>> m.nbytes
4586 20
4587 >>> y = m[::2]
4588 >>> len(y)
4589 3
4590 >>> y.nbytes
4591 12
4592 >>> len(y.tobytes())
4593 12
4594
4595 Multi-dimensional arrays::
4596
4597 >>> import struct
4598 >>> buf = struct.pack("d"*12, *[1.5*x for x in range(12)])
4599 >>> x = memoryview(buf)
4600 >>> y = x.cast('d', shape=[3,4])
4601 >>> y.tolist()
4602 [[0.0, 1.5, 3.0, 4.5], [6.0, 7.5, 9.0, 10.5], [12.0, 13.5, 15.0, 16.5]]
4603 >>> len(y)
4604 3
4605 >>> y.nbytes
4606 96
4607
4608 .. versionadded:: 3.3
4609
4610 .. attribute:: readonly
4611
4612 A bool indicating whether the memory is read only.
4613
4614 .. attribute:: format
4615
4616 A string containing the format (in :mod:`struct` module style) for each
4617 element in the view. A memoryview can be created from exporters with
4618 arbitrary format strings, but some methods (e.g. :meth:`tolist`) are
4619 restricted to native single element formats.
4620
4621 .. versionchanged:: 3.3
4622 format ``'B'`` is now handled according to the struct module syntax.
4623 This means that ``memoryview(b'abc')[0] == b'abc'[0] == 97``.
4624
4625 .. attribute:: itemsize
4626
4627 The size in bytes of each element of the memoryview::
4628
4629 >>> import array, struct
4630 >>> m = memoryview(array.array('H', [32000, 32001, 32002]))
4631 >>> m.itemsize
4632 2
4633 >>> m[0]
4634 32000
4635 >>> struct.calcsize('H') == m.itemsize
4636 True
4637
4638 .. attribute:: ndim
4639
4640 An integer indicating how many dimensions of a multi-dimensional array the
4641 memory represents.
4642
4643 .. attribute:: shape
4644
4645 A tuple of integers the length of :attr:`ndim` giving the shape of the
4646 memory as an N-dimensional array.
4647
4648 .. versionchanged:: 3.3
4649 An empty tuple instead of ``None`` when ndim = 0.
4650
4651 .. attribute:: strides
4652
4653 A tuple of integers the length of :attr:`ndim` giving the size in bytes to
4654 access each element for each dimension of the array.
4655
4656 .. versionchanged:: 3.3
4657 An empty tuple instead of ``None`` when ndim = 0.
4658
4659 .. attribute:: suboffsets
4660
4661 Used internally for PIL-style arrays. The value is informational only.
4662
4663 .. attribute:: c_contiguous
4664
4665 A bool indicating whether the memory is C-:term:`contiguous`.
4666
4667 .. versionadded:: 3.3
4668
4669 .. attribute:: f_contiguous
4670
4671 A bool indicating whether the memory is Fortran :term:`contiguous`.
4672
4673 .. versionadded:: 3.3
4674
4675 .. attribute:: contiguous
4676
4677 A bool indicating whether the memory is :term:`contiguous`.
4678
4679 .. versionadded:: 3.3
4680
4681
4682 .. _types-set:
4683
4684 Set Types --- :class:`set`, :class:`frozenset`
4685 ==============================================
4686
4687 .. index:: pair: object; set
4688
4689 A :dfn:`set` object is an unordered collection of distinct :term:`hashable` objects.
4690 Common uses include membership testing, removing duplicates from a sequence, and
4691 computing mathematical operations such as intersection, union, difference, and
4692 symmetric difference.
4693 (For other containers see the built-in :class:`dict`, :class:`list`,
4694 and :class:`tuple` classes, and the :mod:`collections` module.)
4695
4696 Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in
4697 set``. Being an unordered collection, sets do not record element position or
4698 order of insertion. Accordingly, sets do not support indexing, slicing, or
4699 other sequence-like behavior.
4700
4701 There are currently two built-in set types, :class:`set` and :class:`frozenset`.
4702 The :class:`set` type is mutable --- the contents can be changed using methods
4703 like :meth:`~set.add` and :meth:`~set.remove`. Since it is mutable, it has no
4704 hash value and cannot be used as either a dictionary key or as an element of
4705 another set. The :class:`frozenset` type is immutable and :term:`hashable` ---
4706 its contents cannot be altered after it is created; it can therefore be used as
4707 a dictionary key or as an element of another set.
4708
4709 Non-empty sets (not frozensets) can be created by placing a comma-separated list
4710 of elements within braces, for example: ``{'jack', 'sjoerd'}``, in addition to the
4711 :class:`set` constructor.
4712
4713 The constructors for both classes work the same:
4714
4715 .. class:: set(iterable=(), /)
4716 frozenset(iterable=(), /)
4717
4718 Return a new set or frozenset object whose elements are taken from
4719 *iterable*. The elements of a set must be :term:`hashable`. To
4720 represent sets of sets, the inner sets must be :class:`frozenset`
4721 objects. If *iterable* is not specified, a new empty set is
4722 returned.
4723
4724 Sets can be created by several means:
4725
4726 * Use a comma-separated list of elements within braces: ``{'jack', 'sjoerd'}``
4727 * Use a set comprehension: ``{c for c in 'abracadabra' if c not in 'abc'}``
4728 * Use the type constructor: ``set()``, ``set('foobar')``, ``set(['a', 'b', 'foo'])``
4729
4730 Instances of :class:`set` and :class:`frozenset` provide the following
4731 operations:
4732
4733 .. describe:: len(s)
4734
4735 Return the number of elements in set *s* (cardinality of *s*).
4736
4737 .. describe:: x in s
4738
4739 Test *x* for membership in *s*.
4740
4741 .. describe:: x not in s
4742
4743 Test *x* for non-membership in *s*.
4744
4745 .. method:: frozenset.isdisjoint(other, /)
4746 set.isdisjoint(other, /)
4747
4748 Return ``True`` if the set has no elements in common with *other*. Sets are
4749 disjoint if and only if their intersection is the empty set.
4750
4751 .. method:: frozenset.issubset(other, /)
4752 set.issubset(other, /)
4753 .. describe:: set <= other
4754
4755 Test whether every element in the set is in *other*.
4756
4757 .. describe:: set < other
4758
4759 Test whether the set is a proper subset of *other*, that is,
4760 ``set <= other and set != other``.
4761
4762 .. method:: frozenset.issuperset(other, /)
4763 set.issuperset(other, /)
4764 .. describe:: set >= other
4765
4766 Test whether every element in *other* is in the set.
4767
4768 .. describe:: set > other
4769
4770 Test whether the set is a proper superset of *other*, that is, ``set >=
4771 other and set != other``.
4772
4773 .. method:: frozenset.union(*others)
4774 set.union(*others)
4775 .. describe:: set | other | ...
4776
4777 Return a new set with elements from the set and all others.
4778
4779 .. method:: frozenset.intersection(*others)
4780 set.intersection(*others)
4781 .. describe:: set & other & ...
4782
4783 Return a new set with elements common to the set and all others.
4784
4785 .. method:: frozenset.difference(*others)
4786 set.difference(*others)
4787 .. describe:: set - other - ...
4788
4789 Return a new set with elements in the set that are not in the others.
4790
4791 .. method:: frozenset.symmetric_difference(other, /)
4792 set.symmetric_difference(other, /)
4793 .. describe:: set ^ other
4794
4795 Return a new set with elements in either the set or *other* but not both.
4796
4797 .. method:: frozenset.copy()
4798 set.copy()
4799
4800 Return a shallow copy of the set.
4801
4802
4803 Note, the non-operator versions of :meth:`~frozenset.union`,
4804 :meth:`~frozenset.intersection`, :meth:`~frozenset.difference`, :meth:`~frozenset.symmetric_difference`, :meth:`~frozenset.issubset`, and
4805 :meth:`~frozenset.issuperset` methods will accept any iterable as an argument. In
4806 contrast, their operator based counterparts require their arguments to be
4807 sets. This precludes error-prone constructions like ``set('abc') & 'cbs'``
4808 in favor of the more readable ``set('abc').intersection('cbs')``.
4809
4810 Both :class:`set` and :class:`frozenset` support set to set comparisons. Two
4811 sets are equal if and only if every element of each set is contained in the
4812 other (each is a subset of the other). A set is less than another set if and
4813 only if the first set is a proper subset of the second set (is a subset, but
4814 is not equal). A set is greater than another set if and only if the first set
4815 is a proper superset of the second set (is a superset, but is not equal).
4816
4817 Instances of :class:`set` are compared to instances of :class:`frozenset`
4818 based on their members. For example, ``set('abc') == frozenset('abc')``
4819 returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``.
4820
4821 The subset and equality comparisons do not generalize to a total ordering
4822 function. For example, any two nonempty disjoint sets are not equal and are not
4823 subsets of each other, so *all* of the following return ``False``: ``a<b``,
4824 ``a==b``, or ``a>b``.
4825
4826 Since sets only define partial ordering (subset relationships), the output of
4827 the :meth:`list.sort` method is undefined for lists of sets.
4828
4829 Set elements, like dictionary keys, must be :term:`hashable`.
4830
4831 Binary operations that mix :class:`set` instances with :class:`frozenset`
4832 return the type of the first operand. For example: ``frozenset('ab') |
4833 set('bc')`` returns an instance of :class:`frozenset`.
4834
4835 The following table lists operations available for :class:`set` that do not
4836 apply to immutable instances of :class:`frozenset`:
4837
4838 .. method:: set.update(*others)
4839 .. describe:: set |= other | ...
4840
4841 Update the set, adding elements from all others.
4842
4843 .. method:: set.intersection_update(*others)
4844 .. describe:: set &= other & ...
4845
4846 Update the set, keeping only elements found in it and all others.
4847
4848 .. method:: set.difference_update(*others)
4849 .. describe:: set -= other | ...
4850
4851 Update the set, removing elements found in others.
4852
4853 .. method:: set.symmetric_difference_update(other, /)
4854 .. describe:: set ^= other
4855
4856 Update the set, keeping only elements found in either set, but not in both.
4857
4858 .. method:: set.add(elem, /)
4859
4860 Add element *elem* to the set.
4861
4862 .. method:: set.remove(elem, /)
4863
4864 Remove element *elem* from the set. Raises :exc:`KeyError` if *elem* is
4865 not contained in the set.
4866
4867 .. method:: set.discard(elem, /)
4868
4869 Remove element *elem* from the set if it is present.
4870
4871 .. method:: set.pop()
4872
4873 Remove and return an arbitrary element from the set. Raises
4874 :exc:`KeyError` if the set is empty.
4875
4876 .. method:: set.clear()
4877
4878 Remove all elements from the set.
4879
4880
4881 Note, the non-operator versions of the :meth:`~set.update`,
4882 :meth:`~set.intersection_update`, :meth:`~set.difference_update`, and
4883 :meth:`~set.symmetric_difference_update` methods will accept any iterable as an
4884 argument.
4885
4886 Note, the *elem* argument to the :meth:`~object.__contains__`,
4887 :meth:`~set.remove`, and
4888 :meth:`~set.discard` methods may be a set. To support searching for an equivalent
4889 frozenset, a temporary one is created from *elem*.
4890
4891
4892 .. _typesmapping:
4893
4894 Mapping Types --- :class:`dict`
4895 ===============================
4896
4897 .. index::
4898 pair: object; mapping
4899 pair: object; dictionary
4900 triple: operations on; mapping; types
4901 triple: operations on; dictionary; type
4902 pair: statement; del
4903 pair: built-in function; len
4904
4905 A :term:`mapping` object maps :term:`hashable` values to arbitrary objects.
4906 Mappings are mutable objects. There is currently only one standard mapping
4907 type, the :dfn:`dictionary`. (For other containers see the built-in
4908 :class:`list`, :class:`set`, and :class:`tuple` classes, and the
4909 :mod:`collections` module.)
4910
4911 A dictionary's keys are *almost* arbitrary values. Values that are not
4912 :term:`hashable`, that is, values containing lists, dictionaries or other
4913 mutable types (that are compared by value rather than by object identity) may
4914 not be used as keys.
4915 Values that compare equal (such as ``1``, ``1.0``, and ``True``)
4916 can be used interchangeably to index the same dictionary entry.
4917
4918 .. class:: dict(**kwargs)
4919 dict(mapping, /, **kwargs)
4920 dict(iterable, /, **kwargs)
4921
4922 Return a new dictionary initialized from an optional positional argument
4923 and a possibly empty set of keyword arguments.
4924
4925 Dictionaries can be created by several means:
4926
4927 * Use a comma-separated list of ``key: value`` pairs within braces:
4928 ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098: 'jack', 4127: 'sjoerd'}``
4929 * Use a dict comprehension: ``{}``, ``{x: x ** 2 for x in range(10)}``
4930 * Use the type constructor: ``dict()``,
4931 ``dict([('foo', 100), ('bar', 200)])``, ``dict(foo=100, bar=200)``
4932
4933 If no positional argument is given, an empty dictionary is created.
4934 If a positional argument is given and it defines a ``keys()`` method, a
4935 dictionary is created by calling :meth:`~object.__getitem__` on the argument with
4936 each returned key from the method. Otherwise, the positional argument must be an
4937 :term:`iterable` object. Each item in the iterable must itself be an iterable
4938 with exactly two elements. The first element of each item becomes a key in the
4939 new dictionary, and the second element the corresponding value. If a key occurs
4940 more than once, the last value for that key becomes the corresponding value in
4941 the new dictionary.
4942
4943 If keyword arguments are given, the keyword arguments and their values are
4944 added to the dictionary created from the positional argument. If a key
4945 being added is already present, the value from the keyword argument
4946 replaces the value from the positional argument.
4947
4948 Dictionaries compare equal if and only if they have the same ``(key,
4949 value)`` pairs (regardless of ordering). Order comparisons ('<', '<=', '>=', '>') raise
4950 :exc:`TypeError`. To illustrate dictionary creation and equality,
4951 the following examples all return a dictionary equal to
4952 ``{"one": 1, "two": 2, "three": 3}``::
4953
4954 >>> a = dict(one=1, two=2, three=3)
4955 >>> b = {'one': 1, 'two': 2, 'three': 3}
4956 >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
4957 >>> d = dict([('two', 2), ('one', 1), ('three', 3)])
4958 >>> e = dict({'three': 3, 'one': 1, 'two': 2})
4959 >>> f = dict({'one': 1, 'three': 3}, two=2)
4960 >>> a == b == c == d == e == f
4961 True
4962
4963 Providing keyword arguments as in the first example only works for keys that
4964 are valid Python identifiers. Otherwise, any valid keys can be used.
4965
4966 Dictionaries preserve insertion order. Note that updating a key does not
4967 affect the order. Keys added after deletion are inserted at the end. ::
4968
4969 >>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
4970 >>> d
4971 {'one': 1, 'two': 2, 'three': 3, 'four': 4}
4972 >>> list(d)
4973 ['one', 'two', 'three', 'four']
4974 >>> list(d.values())
4975 [1, 2, 3, 4]
4976 >>> d["one"] = 42
4977 >>> d
4978 {'one': 42, 'two': 2, 'three': 3, 'four': 4}
4979 >>> del d["two"]
4980 >>> d["two"] = None
4981 >>> d
4982 {'one': 42, 'three': 3, 'four': 4, 'two': None}
4983
4984 .. versionchanged:: 3.7
4985 Dictionary order is guaranteed to be insertion order. This behavior was
4986 an implementation detail of CPython from 3.6.
4987
4988 These are the operations that dictionaries support (and therefore, custom
4989 mapping types should support too):
4990
4991 .. describe:: list(d)
4992
4993 Return a list of all the keys used in the dictionary *d*.
4994
4995 .. describe:: len(d)
4996
4997 Return the number of items in the dictionary *d*.
4998
4999 .. describe:: d[key]
5000
5001 Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key* is
5002 not in the map.
5003
5004 .. index:: __missing__()
5005
5006 If a subclass of dict defines a method :meth:`~object.__missing__` and *key*
5007 is not present, the ``d[key]`` operation calls that method with the key *key*
5008 as argument. The ``d[key]`` operation then returns or raises whatever is
5009 returned or raised by the ``__missing__(key)`` call.
5010 No other operations or methods invoke :meth:`~object.__missing__`. If
5011 :meth:`~object.__missing__` is not defined, :exc:`KeyError` is raised.
5012 :meth:`~object.__missing__` must be a method; it cannot be an instance variable::
5013
5014 >>> class Counter(dict):
5015 ... def __missing__(self, key):
5016 ... return 0
5017 ...
5018 >>> c = Counter()
5019 >>> c['red']
5020 0
5021 >>> c['red'] += 1
5022 >>> c['red']
5023 1
5024
5025 The example above shows part of the implementation of
5026 :class:`collections.Counter`.
5027 A different :meth:`!__missing__` method is used
5028 by :class:`collections.defaultdict`.
5029
5030 .. describe:: d[key] = value
5031
5032 Set ``d[key]`` to *value*.
5033
5034 .. describe:: del d[key]
5035
5036 Remove ``d[key]`` from *d*. Raises a :exc:`KeyError` if *key* is not in the
5037 map.
5038
5039 .. describe:: key in d
5040
5041 Return ``True`` if *d* has a key *key*, else ``False``.
5042
5043 .. describe:: key not in d
5044
5045 Equivalent to ``not key in d``.
5046
5047 .. describe:: iter(d)
5048
5049 Return an iterator over the keys of the dictionary. This is a shortcut
5050 for ``iter(d.keys())``.
5051
5052 .. method:: clear()
5053
5054 Remove all items from the dictionary.
5055
5056 .. method:: copy()
5057
5058 Return a shallow copy of the dictionary.
5059
5060 .. classmethod:: fromkeys(iterable, value=None, /)
5061
5062 Create a new dictionary with keys from *iterable* and values set to *value*.
5063
5064 :meth:`fromkeys` is a class method that returns a new dictionary. *value*
5065 defaults to ``None``. All of the values refer to just a single instance,
5066 so it generally doesn't make sense for *value* to be a mutable object
5067 such as an empty list. To get distinct values, use a :ref:`dict
5068 comprehension <dict>` instead.
5069
5070 .. method:: get(key, default=None, /)
5071
5072 Return the value for *key* if *key* is in the dictionary, else *default*.
5073 If *default* is not given, it defaults to ``None``, so that this method
5074 never raises a :exc:`KeyError`.
5075
5076 .. method:: items()
5077
5078 Return a new view of the dictionary's items (``(key, value)`` pairs).
5079 See the :ref:`documentation of view objects <dict-views>`.
5080
5081 .. method:: keys()
5082
5083 Return a new view of the dictionary's keys. See the :ref:`documentation
5084 of view objects <dict-views>`.
5085
5086 .. method:: pop(key, /)
5087 pop(key, default, /)
5088
5089 If *key* is in the dictionary, remove it and return its value, else return
5090 *default*. If *default* is not given and *key* is not in the dictionary,
5091 a :exc:`KeyError` is raised.
5092
5093 .. method:: popitem()
5094
5095 Remove and return a ``(key, value)`` pair from the dictionary.
5096 Pairs are returned in :abbr:`LIFO (last-in, first-out)` order.
5097
5098 :meth:`popitem` is useful to destructively iterate over a dictionary, as
5099 often used in set algorithms. If the dictionary is empty, calling
5100 :meth:`popitem` raises a :exc:`KeyError`.
5101
5102 .. versionchanged:: 3.7
5103 LIFO order is now guaranteed. In prior versions, :meth:`popitem` would
5104 return an arbitrary key/value pair.
5105
5106 .. describe:: reversed(d)
5107
5108 Return a reverse iterator over the keys of the dictionary. This is a
5109 shortcut for ``reversed(d.keys())``.
5110
5111 .. versionadded:: 3.8
5112
5113 .. method:: setdefault(key, default=None, /)
5114
5115 If *key* is in the dictionary, return its value. If not, insert *key*
5116 with a value of *default* and return *default*. *default* defaults to
5117 ``None``.
5118
5119 .. method:: update(**kwargs)
5120 update(mapping, /, **kwargs)
5121 update(iterable, /, **kwargs)
5122
5123 Update the dictionary with the key/value pairs from *mapping* or *iterable* and *kwargs*, overwriting
5124 existing keys. Return ``None``.
5125
5126 :meth:`update` accepts either another object with a ``keys()`` method (in
5127 which case :meth:`~object.__getitem__` is called with every key returned from
5128 the method) or an iterable of key/value pairs (as tuples or other iterables
5129 of length two). If keyword arguments are specified, the dictionary is then
5130 updated with those key/value pairs: ``d.update(red=1, blue=2)``.
5131
5132 .. method:: values()
5133
5134 Return a new view of the dictionary's values. See the
5135 :ref:`documentation of view objects <dict-views>`.
5136
5137 An equality comparison between one ``dict.values()`` view and another
5138 will always return ``False``. This also applies when comparing
5139 ``dict.values()`` to itself::
5140
5141 >>> d = {'a': 1}
5142 >>> d.values() == d.values()
5143 False
5144
5145 .. describe:: d | other
5146
5147 Create a new dictionary with the merged keys and values of *d* and
5148 *other*, which must both be dictionaries. The values of *other* take
5149 priority when *d* and *other* share keys.
5150
5151 .. versionadded:: 3.9
5152
5153 .. describe:: d |= other
5154
5155 Update the dictionary *d* with keys and values from *other*, which may be
5156 either a :term:`mapping` or an :term:`iterable` of key/value pairs. The
5157 values of *other* take priority when *d* and *other* share keys.
5158
5159 .. versionadded:: 3.9
5160
5161 Dictionaries and dictionary views are reversible. ::
5162
5163 >>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
5164 >>> d
5165 {'one': 1, 'two': 2, 'three': 3, 'four': 4}
5166 >>> list(reversed(d))
5167 ['four', 'three', 'two', 'one']
5168 >>> list(reversed(d.values()))
5169 [4, 3, 2, 1]
5170 >>> list(reversed(d.items()))
5171 [('four', 4), ('three', 3), ('two', 2), ('one', 1)]
5172
5173 .. versionchanged:: 3.8
5174 Dictionaries are now reversible.
5175
5176
5177 .. seealso::
5178 :class:`types.MappingProxyType` can be used to create a read-only view
5179 of a :class:`dict`.
5180
5181
5182 .. _dict-views:
5183
5184 Dictionary view objects
5185 -----------------------
5186
5187 The objects returned by :meth:`dict.keys`, :meth:`dict.values` and
5188 :meth:`dict.items` are *view objects*. They provide a dynamic view on the
5189 dictionary's entries, which means that when the dictionary changes, the view
5190 reflects these changes.
5191
5192 Dictionary views can be iterated over to yield their respective data, and
5193 support membership tests:
5194
5195 .. describe:: len(dictview)
5196
5197 Return the number of entries in the dictionary.
5198
5199 .. describe:: iter(dictview)
5200
5201 Return an iterator over the keys, values or items (represented as tuples of
5202 ``(key, value)``) in the dictionary.
5203
5204 Keys and values are iterated over in insertion order.
5205 This allows the creation of ``(value, key)`` pairs
5206 using :func:`zip`: ``pairs = zip(d.values(), d.keys())``. Another way to
5207 create the same list is ``pairs = [(v, k) for (k, v) in d.items()]``.
5208
5209 Iterating views while adding or deleting entries in the dictionary may raise
5210 a :exc:`RuntimeError` or fail to iterate over all entries.
5211
5212 .. versionchanged:: 3.7
5213 Dictionary order is guaranteed to be insertion order.
5214
5215 .. describe:: x in dictview
5216
5217 Return ``True`` if *x* is in the underlying dictionary's keys, values or
5218 items (in the latter case, *x* should be a ``(key, value)`` tuple).
5219
5220 .. describe:: reversed(dictview)
5221
5222 Return a reverse iterator over the keys, values or items of the dictionary.
5223 The view will be iterated in reverse order of the insertion.
5224
5225 .. versionchanged:: 3.8
5226 Dictionary views are now reversible.
5227
5228 .. describe:: dictview.mapping
5229
5230 Return a :class:`types.MappingProxyType` that wraps the original
5231 dictionary to which the view refers.
5232
5233 .. versionadded:: 3.10
5234
5235 Keys views are set-like since their entries are unique and :term:`hashable`.
5236 Items views also have set-like operations since the (key, value) pairs
5237 are unique and the keys are hashable.
5238 If all values in an items view are hashable as well,
5239 then the items view can interoperate with other sets.
5240 (Values views are not treated as set-like
5241 since the entries are generally not unique.) For set-like views, all of the
5242 operations defined for the abstract base class :class:`collections.abc.Set` are
5243 available (for example, ``==``, ``<``, or ``^``). While using set operators,
5244 set-like views accept any iterable as the other operand,
5245 unlike sets which only accept sets as the input.
5246
5247 An example of dictionary view usage::
5248
5249 >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
5250 >>> keys = dishes.keys()
5251 >>> values = dishes.values()
5252
5253 >>> # iteration
5254 >>> n = 0
5255 >>> for val in values:
5256 ... n += val
5257 ...
5258 >>> print(n)
5259 504
5260
5261 >>> # keys and values are iterated over in the same order (insertion order)
5262 >>> list(keys)
5263 ['eggs', 'sausage', 'bacon', 'spam']
5264 >>> list(values)
5265 [2, 1, 1, 500]
5266
5267 >>> # view objects are dynamic and reflect dict changes
5268 >>> del dishes['eggs']
5269 >>> del dishes['sausage']
5270 >>> list(keys)
5271 ['bacon', 'spam']
5272
5273 >>> # set operations
5274 >>> keys & {'eggs', 'bacon', 'salad'}
5275 {'bacon'}
5276 >>> keys ^ {'sausage', 'juice'} == {'juice', 'sausage', 'bacon', 'spam'}
5277 True
5278 >>> keys | ['juice', 'juice', 'juice'] == {'bacon', 'spam', 'juice'}
5279 True
5280
5281 >>> # get back a read-only proxy for the original dictionary
5282 >>> values.mapping
5283 mappingproxy({'bacon': 1, 'spam': 500})
5284 >>> values.mapping['spam']
5285 500
5286
5287
5288 .. _typecontextmanager:
5289
5290 Context Manager Types
5291 =====================
5292
5293 .. index::
5294 single: context manager
5295 single: context management protocol
5296 single: protocol; context management
5297
5298 Python's :keyword:`with` statement supports the concept of a runtime context
5299 defined by a context manager. This is implemented using a pair of methods
5300 that allow user-defined classes to define a runtime context that is entered
5301 before the statement body is executed and exited when the statement ends:
5302
5303
5304 .. method:: contextmanager.__enter__()
5305
5306 Enter the runtime context and return either this object or another object
5307 related to the runtime context. The value returned by this method is bound to
5308 the identifier in the :keyword:`!as` clause of :keyword:`with` statements using
5309 this context manager.
5310
5311 An example of a context manager that returns itself is a :term:`file object`.
5312 File objects return themselves from __enter__() to allow :func:`open` to be
5313 used as the context expression in a :keyword:`with` statement.
5314
5315 An example of a context manager that returns a related object is the one
5316 returned by :func:`decimal.localcontext`. These managers set the active
5317 decimal context to a copy of the original decimal context and then return the
5318 copy. This allows changes to be made to the current decimal context in the body
5319 of the :keyword:`with` statement without affecting code outside the
5320 :keyword:`!with` statement.
5321
5322
5323 .. method:: contextmanager.__exit__(exc_type, exc_val, exc_tb)
5324
5325 Exit the runtime context and return a Boolean flag indicating if any exception
5326 that occurred should be suppressed. If an exception occurred while executing the
5327 body of the :keyword:`with` statement, the arguments contain the exception type,
5328 value and traceback information. Otherwise, all three arguments are ``None``.
5329
5330 Returning a true value from this method will cause the :keyword:`with` statement
5331 to suppress the exception and continue execution with the statement immediately
5332 following the :keyword:`!with` statement. Otherwise the exception continues
5333 propagating after this method has finished executing.
5334
5335 If this method raises an exception while handling an earlier exception from the
5336 :keyword:`with` block, the new exception is raised, and the original exception
5337 is stored in its :attr:`~BaseException.__context__` attribute.
5338
5339 The exception passed in should never be reraised explicitly - instead, this
5340 method should return a false value to indicate that the method completed
5341 successfully and does not want to suppress the raised exception. This allows
5342 context management code to easily detect whether or not an :meth:`~object.__exit__`
5343 method has actually failed.
5344
5345 Python defines several context managers to support easy thread synchronisation,
5346 prompt closure of files or other objects, and simpler manipulation of the active
5347 decimal arithmetic context. The specific types are not treated specially beyond
5348 their implementation of the context management protocol. See the
5349 :mod:`contextlib` module for some examples.
5350
5351 Python's :term:`generator`\s and the :class:`contextlib.contextmanager` decorator
5352 provide a convenient way to implement these protocols. If a generator function is
5353 decorated with the :class:`contextlib.contextmanager` decorator, it will return a
5354 context manager implementing the necessary :meth:`~contextmanager.__enter__` and
5355 :meth:`~contextmanager.__exit__` methods, rather than the iterator produced by an
5356 undecorated generator function.
5357
5358 Note that there is no specific slot for any of these methods in the type
5359 structure for Python objects in the Python/C API. Extension types wanting to
5360 define these methods must provide them as a normal Python accessible method.
5361 Compared to the overhead of setting up the runtime context, the overhead of a
5362 single class dictionary lookup is negligible.
5363
5364
5365 Type Annotation Types --- :ref:`Generic Alias <types-genericalias>`, :ref:`Union <types-union>`
5366 ===============================================================================================
5367
5368 .. index::
5369 single: annotation; type annotation; type hint
5370
5371 The core built-in types for :term:`type annotations <annotation>` are
5372 :ref:`Generic Alias <types-genericalias>` and :ref:`Union <types-union>`.
5373
5374
5375 .. _types-genericalias:
5376
5377 Generic Alias Type
5378 ------------------
5379
5380 .. index::
5381 pair: object; GenericAlias
5382 pair: Generic; Alias
5383
5384 ``GenericAlias`` objects are generally created by
5385 :ref:`subscripting <subscriptions>` a class. They are most often used with
5386 :ref:`container classes <sequence-types>`, such as :class:`list` or
5387 :class:`dict`. For example, ``list[int]`` is a ``GenericAlias`` object created
5388 by subscripting the ``list`` class with the argument :class:`int`.
5389 ``GenericAlias`` objects are intended primarily for use with
5390 :term:`type annotations <annotation>`.
5391
5392 .. note::
5393
5394 It is generally only possible to subscript a class if the class implements
5395 the special method :meth:`~object.__class_getitem__`.
5396
5397 A ``GenericAlias`` object acts as a proxy for a :term:`generic type`,
5398 implementing *parameterized generics*.
5399
5400 For a container class, the
5401 argument(s) supplied to a :ref:`subscription <subscriptions>` of the class may
5402 indicate the type(s) of the elements an object contains. For example,
5403 ``set[bytes]`` can be used in type annotations to signify a :class:`set` in
5404 which all the elements are of type :class:`bytes`.
5405
5406 For a class which defines :meth:`~object.__class_getitem__` but is not a
5407 container, the argument(s) supplied to a subscription of the class will often
5408 indicate the return type(s) of one or more methods defined on an object. For
5409 example, :mod:`regular expressions <re>` can be used on both the :class:`str` data
5410 type and the :class:`bytes` data type:
5411
5412 * If ``x = re.search('foo', 'foo')``, ``x`` will be a
5413 :ref:`re.Match <match-objects>` object where the return values of
5414 ``x.group(0)`` and ``x[0]`` will both be of type :class:`str`. We can
5415 represent this kind of object in type annotations with the ``GenericAlias``
5416 ``re.Match[str]``.
5417
5418 * If ``y = re.search(b'bar', b'bar')``, (note the ``b`` for :class:`bytes`),
5419 ``y`` will also be an instance of ``re.Match``, but the return
5420 values of ``y.group(0)`` and ``y[0]`` will both be of type
5421 :class:`bytes`. In type annotations, we would represent this
5422 variety of :ref:`re.Match <match-objects>` objects with ``re.Match[bytes]``.
5423
5424 ``GenericAlias`` objects are instances of the class
5425 :class:`types.GenericAlias`, which can also be used to create ``GenericAlias``
5426 objects directly.
5427
5428 .. describe:: T[X, Y, ...]
5429
5430 Creates a ``GenericAlias`` representing a type ``T`` parameterized by types
5431 *X*, *Y*, and more depending on the ``T`` used.
5432 For example, a function expecting a :class:`list` containing
5433 :class:`float` elements::
5434
5435 def average(values: list[float]) -> float:
5436 return sum(values) / len(values)
5437
5438 Another example for :term:`mapping` objects, using a :class:`dict`, which
5439 is a generic type expecting two type parameters representing the key type
5440 and the value type. In this example, the function expects a ``dict`` with
5441 keys of type :class:`str` and values of type :class:`int`::
5442
5443 def send_post_request(url: str, body: dict[str, int]) -> None:
5444 ...
5445
5446 The builtin functions :func:`isinstance` and :func:`issubclass` do not accept
5447 ``GenericAlias`` types for their second argument::
5448
5449 >>> isinstance([1, 2], list[str])
5450 Traceback (most recent call last):
5451 File "<stdin>", line 1, in <module>
5452 TypeError: isinstance() argument 2 cannot be a parameterized generic
5453
5454 The Python runtime does not enforce :term:`type annotations <annotation>`.
5455 This extends to generic types and their type parameters. When creating
5456 a container object from a ``GenericAlias``, the elements in the container are not checked
5457 against their type. For example, the following code is discouraged, but will
5458 run without errors::
5459
5460 >>> t = list[str]
5461 >>> t([1, 2, 3])
5462 [1, 2, 3]
5463
5464 Furthermore, parameterized generics erase type parameters during object
5465 creation::
5466
5467 >>> t = list[str]
5468 >>> type(t)
5469 <class 'types.GenericAlias'>
5470
5471 >>> l = t()
5472 >>> type(l)
5473 <class 'list'>
5474
5475 Calling :func:`repr` or :func:`str` on a generic shows the parameterized type::
5476
5477 >>> repr(list[int])
5478 'list[int]'
5479
5480 >>> str(list[int])
5481 'list[int]'
5482
5483 The :meth:`~object.__getitem__` method of generic containers will raise an
5484 exception to disallow mistakes like ``dict[str][str]``::
5485
5486 >>> dict[str][str]
5487 Traceback (most recent call last):
5488 ...
5489 TypeError: dict[str] is not a generic class
5490
5491 However, such expressions are valid when :ref:`type variables <generics>` are
5492 used. The index must have as many elements as there are type variable items
5493 in the ``GenericAlias`` object's :attr:`~genericalias.__args__`. ::
5494
5495 >>> from typing import TypeVar
5496 >>> Y = TypeVar('Y')
5497 >>> dict[str, Y][int]
5498 dict[str, int]
5499
5500
5501 Standard Generic Classes
5502 ^^^^^^^^^^^^^^^^^^^^^^^^
5503
5504 The following standard library classes support parameterized generics. This
5505 list is non-exhaustive.
5506
5507 * :class:`tuple`
5508 * :class:`list`
5509 * :class:`dict`
5510 * :class:`set`
5511 * :class:`frozenset`
5512 * :class:`type`
5513 * :class:`asyncio.Future`
5514 * :class:`asyncio.Task`
5515 * :class:`collections.deque`
5516 * :class:`collections.defaultdict`
5517 * :class:`collections.OrderedDict`
5518 * :class:`collections.Counter`
5519 * :class:`collections.ChainMap`
5520 * :class:`collections.abc.Awaitable`
5521 * :class:`collections.abc.Coroutine`
5522 * :class:`collections.abc.AsyncIterable`
5523 * :class:`collections.abc.AsyncIterator`
5524 * :class:`collections.abc.AsyncGenerator`
5525 * :class:`collections.abc.Iterable`
5526 * :class:`collections.abc.Iterator`
5527 * :class:`collections.abc.Generator`
5528 * :class:`collections.abc.Reversible`
5529 * :class:`collections.abc.Container`
5530 * :class:`collections.abc.Collection`
5531 * :class:`collections.abc.Callable`
5532 * :class:`collections.abc.Set`
5533 * :class:`collections.abc.MutableSet`
5534 * :class:`collections.abc.Mapping`
5535 * :class:`collections.abc.MutableMapping`
5536 * :class:`collections.abc.Sequence`
5537 * :class:`collections.abc.MutableSequence`
5538 * :class:`collections.abc.ByteString`
5539 * :class:`collections.abc.MappingView`
5540 * :class:`collections.abc.KeysView`
5541 * :class:`collections.abc.ItemsView`
5542 * :class:`collections.abc.ValuesView`
5543 * :class:`contextlib.AbstractContextManager`
5544 * :class:`contextlib.AbstractAsyncContextManager`
5545 * :class:`dataclasses.Field`
5546 * :class:`functools.cached_property`
5547 * :class:`functools.partialmethod`
5548 * :class:`os.PathLike`
5549 * :class:`queue.LifoQueue`
5550 * :class:`queue.Queue`
5551 * :class:`queue.PriorityQueue`
5552 * :class:`queue.SimpleQueue`
5553 * :ref:`re.Pattern <re-objects>`
5554 * :ref:`re.Match <match-objects>`
5555 * :class:`shelve.BsdDbShelf`
5556 * :class:`shelve.DbfilenameShelf`
5557 * :class:`shelve.Shelf`
5558 * :class:`types.MappingProxyType`
5559 * :class:`weakref.WeakKeyDictionary`
5560 * :class:`weakref.WeakMethod`
5561 * :class:`weakref.WeakSet`
5562 * :class:`weakref.WeakValueDictionary`
5563
5564
5565
5566 Special Attributes of ``GenericAlias`` objects
5567 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
5568
5569 All parameterized generics implement special read-only attributes.
5570
5571 .. attribute:: genericalias.__origin__
5572
5573 This attribute points at the non-parameterized generic class::
5574
5575 >>> list[int].__origin__
5576 <class 'list'>
5577
5578
5579 .. attribute:: genericalias.__args__
5580
5581 This attribute is a :class:`tuple` (possibly of length 1) of generic
5582 types passed to the original :meth:`~object.__class_getitem__` of the
5583 generic class::
5584
5585 >>> dict[str, list[int]].__args__
5586 (<class 'str'>, list[int])
5587
5588
5589 .. attribute:: genericalias.__parameters__
5590
5591 This attribute is a lazily computed tuple (possibly empty) of unique type
5592 variables found in ``__args__``::
5593
5594 >>> from typing import TypeVar
5595
5596 >>> T = TypeVar('T')
5597 >>> list[T].__parameters__
5598 (~T,)
5599
5600
5601 .. note::
5602 A ``GenericAlias`` object with :class:`typing.ParamSpec` parameters may not
5603 have correct ``__parameters__`` after substitution because
5604 :class:`typing.ParamSpec` is intended primarily for static type checking.
5605
5606
5607 .. attribute:: genericalias.__unpacked__
5608
5609 A boolean that is true if the alias has been unpacked using the
5610 ``*`` operator (see :data:`~typing.TypeVarTuple`).
5611
5612 .. versionadded:: 3.11
5613
5614
5615 .. seealso::
5616
5617 :pep:`484` - Type Hints
5618 Introducing Python's framework for type annotations.
5619
5620 :pep:`585` - Type Hinting Generics In Standard Collections
5621 Introducing the ability to natively parameterize standard-library
5622 classes, provided they implement the special class method
5623 :meth:`~object.__class_getitem__`.
5624
5625 :ref:`Generics`, :ref:`user-defined generics <user-defined-generics>` and :class:`typing.Generic`
5626 Documentation on how to implement generic classes that can be
5627 parameterized at runtime and understood by static type-checkers.
5628
5629 .. versionadded:: 3.9
5630
5631
5632 .. _types-union:
5633
5634 Union Type
5635 ----------
5636
5637 .. index::
5638 pair: object; Union
5639 pair: union; type
5640
5641 A union object holds the value of the ``|`` (bitwise or) operation on
5642 multiple :ref:`type objects <bltin-type-objects>`. These types are intended
5643 primarily for :term:`type annotations <annotation>`. The union type expression
5644 enables cleaner type hinting syntax compared to :data:`typing.Union`.
5645
5646 .. describe:: X | Y | ...
5647
5648 Defines a union object which holds types *X*, *Y*, and so forth. ``X | Y``
5649 means either X or Y. It is equivalent to ``typing.Union[X, Y]``.
5650 For example, the following function expects an argument of type
5651 :class:`int` or :class:`float`::
5652
5653 def square(number: int | float) -> int | float:
5654 return number ** 2
5655
5656 .. note::
5657
5658 The ``|`` operand cannot be used at runtime to define unions where one or
5659 more members is a forward reference. For example, ``int | "Foo"``, where
5660 ``"Foo"`` is a reference to a class not yet defined, will fail at
5661 runtime. For unions which include forward references, present the
5662 whole expression as a string, e.g. ``"int | Foo"``.
5663
5664 .. describe:: union_object == other
5665
5666 Union objects can be tested for equality with other union objects. Details:
5667
5668 * Unions of unions are flattened::
5669
5670 (int | str) | float == int | str | float
5671
5672 * Redundant types are removed::
5673
5674 int | str | int == int | str
5675
5676 * When comparing unions, the order is ignored::
5677
5678 int | str == str | int
5679
5680 * It is compatible with :data:`typing.Union`::
5681
5682 int | str == typing.Union[int, str]
5683
5684 * Optional types can be spelled as a union with ``None``::
5685
5686 str | None == typing.Optional[str]
5687
5688 .. describe:: isinstance(obj, union_object)
5689 .. describe:: issubclass(obj, union_object)
5690
5691 Calls to :func:`isinstance` and :func:`issubclass` are also supported with a
5692 union object::
5693
5694 >>> isinstance("", int | str)
5695 True
5696
5697 However, :ref:`parameterized generics <types-genericalias>` in
5698 union objects cannot be checked::
5699
5700 >>> isinstance(1, int | list[int]) # short-circuit evaluation
5701 True
5702 >>> isinstance([1], int | list[int])
5703 Traceback (most recent call last):
5704 ...
5705 TypeError: isinstance() argument 2 cannot be a parameterized generic
5706
5707 The user-exposed type for the union object can be accessed from
5708 :data:`types.UnionType` and used for :func:`isinstance` checks. An object cannot be
5709 instantiated from the type::
5710
5711 >>> import types
5712 >>> isinstance(int | str, types.UnionType)
5713 True
5714 >>> types.UnionType()
5715 Traceback (most recent call last):
5716 File "<stdin>", line 1, in <module>
5717 TypeError: cannot create 'types.UnionType' instances
5718
5719 .. note::
5720 The :meth:`!__or__` method for type objects was added to support the syntax
5721 ``X | Y``. If a metaclass implements :meth:`!__or__`, the Union may
5722 override it:
5723
5724 .. doctest::
5725
5726 >>> class M(type):
5727 ... def __or__(self, other):
5728 ... return "Hello"
5729 ...
5730 >>> class C(metaclass=M):
5731 ... pass
5732 ...
5733 >>> C | int
5734 'Hello'
5735 >>> int | C
5736 int | C
5737
5738 .. seealso::
5739
5740 :pep:`604` -- PEP proposing the ``X | Y`` syntax and the Union type.
5741
5742 .. versionadded:: 3.10
5743
5744
5745 .. _typesother:
5746
5747 Other Built-in Types
5748 ====================
5749
5750 The interpreter supports several other kinds of objects. Most of these support
5751 only one or two operations.
5752
5753
5754 .. _typesmodules:
5755
5756 Modules
5757 -------
5758
5759 The only special operation on a module is attribute access: ``m.name``, where
5760 *m* is a module and *name* accesses a name defined in *m*'s symbol table.
5761 Module attributes can be assigned to. (Note that the :keyword:`import`
5762 statement is not, strictly speaking, an operation on a module object; ``import
5763 foo`` does not require a module object named *foo* to exist, rather it requires
5764 an (external) *definition* for a module named *foo* somewhere.)
5765
5766 A special attribute of every module is :attr:`~object.__dict__`. This is the
5767 dictionary containing the module's symbol table. Modifying this dictionary will
5768 actually change the module's symbol table, but direct assignment to the
5769 :attr:`~object.__dict__` attribute is not possible (you can write
5770 ``m.__dict__['a'] = 1``, which defines ``m.a`` to be ``1``, but you can't write
5771 ``m.__dict__ = {}``). Modifying :attr:`~object.__dict__` directly is
5772 not recommended.
5773
5774 Modules built into the interpreter are written like this: ``<module 'sys'
5775 (built-in)>``. If loaded from a file, they are written as ``<module 'os' from
5776 '/usr/local/lib/pythonX.Y/os.pyc'>``.
5777
5778
5779 .. _typesobjects:
5780
5781 Classes and Class Instances
5782 ---------------------------
5783
5784 See :ref:`objects` and :ref:`class` for these.
5785
5786
5787 .. _typesfunctions:
5788
5789 Functions
5790 ---------
5791
5792 Function objects are created by function definitions. The only operation on a
5793 function object is to call it: ``func(argument-list)``.
5794
5795 There are really two flavors of function objects: built-in functions and
5796 user-defined functions. Both support the same operation (to call the function),
5797 but the implementation is different, hence the different object types.
5798
5799 See :ref:`function` for more information.
5800
5801
5802 .. _typesmethods:
5803
5804 Methods
5805 -------
5806
5807 .. index:: pair: object; method
5808
5809 Methods are functions that are called using the attribute notation.
5810 There are two flavors: :ref:`built-in methods <builtin-methods>`
5811 (such as :meth:`~list.append` on lists)
5812 and :ref:`class instance method <instance-methods>`.
5813 Built-in methods are described with the types that support them.
5814
5815 If you access a method (a function defined in a class namespace) through an
5816 instance, you get a special object: a :dfn:`bound method` (also called
5817 :ref:`instance method <instance-methods>`) object. When called, it will add
5818 the ``self`` argument
5819 to the argument list. Bound methods have two special read-only attributes:
5820 :attr:`m.__self__ <method.__self__>` is the object on which the method
5821 operates, and :attr:`m.__func__ <method.__func__>` is
5822 the function implementing the method. Calling ``m(arg-1, arg-2, ..., arg-n)``
5823 is completely equivalent to calling ``m.__func__(m.__self__, arg-1, arg-2, ...,
5824 arg-n)``.
5825
5826 Like :ref:`function objects <user-defined-funcs>`, bound method objects support
5827 getting arbitrary
5828 attributes. However, since method attributes are actually stored on the
5829 underlying function object (:attr:`method.__func__`), setting method attributes on
5830 bound methods is disallowed. Attempting to set an attribute on a method
5831 results in an :exc:`AttributeError` being raised. In order to set a method
5832 attribute, you need to explicitly set it on the underlying function object:
5833
5834 .. doctest::
5835
5836 >>> class C:
5837 ... def method(self):
5838 ... pass
5839 ...
5840 >>> c = C()
5841 >>> c.method.whoami = 'my name is method' # can't set on the method
5842 Traceback (most recent call last):
5843 File "<stdin>", line 1, in <module>
5844 AttributeError: 'method' object has no attribute 'whoami'
5845 >>> c.method.__func__.whoami = 'my name is method'
5846 >>> c.method.whoami
5847 'my name is method'
5848
5849 See :ref:`instance-methods` for more information.
5850
5851
5852 .. index:: object; code, code object
5853
5854 .. _bltin-code-objects:
5855
5856 Code Objects
5857 ------------
5858
5859 .. index::
5860 pair: built-in function; compile
5861 single: __code__ (function object attribute)
5862
5863 Code objects are used by the implementation to represent "pseudo-compiled"
5864 executable Python code such as a function body. They differ from function
5865 objects because they don't contain a reference to their global execution
5866 environment. Code objects are returned by the built-in :func:`compile` function
5867 and can be extracted from function objects through their
5868 :attr:`~function.__code__` attribute. See also the :mod:`code` module.
5869
5870 Accessing :attr:`~function.__code__` raises an :ref:`auditing event <auditing>`
5871 ``object.__getattr__`` with arguments ``obj`` and ``"__code__"``.
5872
5873 .. index::
5874 pair: built-in function; exec
5875 pair: built-in function; eval
5876
5877 A code object can be executed or evaluated by passing it (instead of a source
5878 string) to the :func:`exec` or :func:`eval` built-in functions.
5879
5880 See :ref:`types` for more information.
5881
5882
5883 .. _bltin-type-objects:
5884
5885 Type Objects
5886 ------------
5887
5888 .. index::
5889 pair: built-in function; type
5890 pair: module; types
5891
5892 Type objects represent the various object types. An object's type is accessed
5893 by the built-in function :func:`type`. There are no special operations on
5894 types. The standard module :mod:`types` defines names for all standard built-in
5895 types.
5896
5897 Types are written like this: ``<class 'int'>``.
5898
5899
5900 .. _bltin-null-object:
5901
5902 The Null Object
5903 ---------------
5904
5905 This object is returned by functions that don't explicitly return a value. It
5906 supports no special operations. There is exactly one null object, named
5907 ``None`` (a built-in name). ``type(None)()`` produces the same singleton.
5908
5909 It is written as ``None``.
5910
5911
5912 .. index:: single: ...; ellipsis literal
5913 .. _bltin-ellipsis-object:
5914
5915 The Ellipsis Object
5916 -------------------
5917
5918 This object is commonly used to indicate that something is omitted.
5919 It supports no special operations. There is exactly one ellipsis object, named
5920 :const:`Ellipsis` (a built-in name). ``type(Ellipsis)()`` produces the
5921 :const:`Ellipsis` singleton.
5922
5923 It is written as ``Ellipsis`` or ``...``.
5924
5925 In typical use, ``...`` as the ``Ellipsis`` object appears in a few different
5926 places, for instance:
5927
5928 - In type annotations, such as :ref:`callable arguments <annotating-callables>`
5929 or :ref:`tuple elements <annotating-tuples>`.
5930
5931 - As the body of a function instead of a :ref:`pass statement <tut-pass>`.
5932
5933 - In third-party libraries, such as `Numpy's slicing and striding
5934 <https://numpy.org/doc/stable/user/basics.indexing.html#slicing-and-striding>`_.
5935
5936 Python also uses three dots in ways that are not ``Ellipsis`` objects, for instance:
5937
5938 - Doctest's :const:`ELLIPSIS <doctest.ELLIPSIS>`, as a pattern for missing content.
5939
5940 - The default Python prompt of the :term:`interactive` shell when partial input is incomplete.
5941
5942 Lastly, the Python documentation often uses three dots in conventional English
5943 usage to mean omitted content, even in code examples that also use them as the
5944 ``Ellipsis``.
5945
5946
5947 .. _bltin-notimplemented-object:
5948
5949 The NotImplemented Object
5950 -------------------------
5951
5952 This object is returned from comparisons and binary operations when they are
5953 asked to operate on types they don't support. See :ref:`comparisons` for more
5954 information. There is exactly one :data:`NotImplemented` object.
5955 :code:`type(NotImplemented)()` produces the singleton instance.
5956
5957 It is written as :code:`NotImplemented`.
5958
5959
5960 .. _typesinternal:
5961
5962 Internal Objects
5963 ----------------
5964
5965 See :ref:`types` for this information. It describes
5966 :ref:`stack frame objects <frame-objects>`,
5967 :ref:`traceback objects <traceback-objects>`, and slice objects.
5968
5969
5970 .. _specialattrs:
5971
5972 Special Attributes
5973 ==================
5974
5975 The implementation adds a few special read-only attributes to several object
5976 types, where they are relevant. Some of these are not reported by the
5977 :func:`dir` built-in function.
5978
5979
5980 .. attribute:: definition.__name__
5981
5982 The name of the class, function, method, descriptor, or
5983 generator instance.
5984
5985
5986 .. attribute:: definition.__qualname__
5987
5988 The :term:`qualified name` of the class, function, method, descriptor,
5989 or generator instance.
5990
5991 .. versionadded:: 3.3
5992
5993
5994 .. attribute:: definition.__module__
5995
5996 The name of the module in which a class or function was defined.
5997
5998
5999 .. attribute:: definition.__doc__
6000
6001 The documentation string of a class or function, or ``None`` if undefined.
6002
6003
6004 .. attribute:: definition.__type_params__
6005
6006 The :ref:`type parameters <type-params>` of generic classes, functions,
6007 and :ref:`type aliases <type-aliases>`. For classes and functions that
6008 are not generic, this will be an empty tuple.
6009
6010 .. versionadded:: 3.12
6011
6012
6013 .. _int_max_str_digits:
6014
6015 Integer string conversion length limitation
6016 ===========================================
6017
6018 CPython has a global limit for converting between :class:`int` and :class:`str`
6019 to mitigate denial of service attacks. This limit *only* applies to decimal or
6020 other non-power-of-two number bases. Hexadecimal, octal, and binary conversions
6021 are unlimited. The limit can be configured.
6022
6023 The :class:`int` type in CPython is an arbitrary length number stored in binary
6024 form (commonly known as a "bignum"). There exists no algorithm that can convert
6025 a string to a binary integer or a binary integer to a string in linear time,
6026 *unless* the base is a power of 2. Even the best known algorithms for base 10
6027 have sub-quadratic complexity. Converting a large value such as ``int('1' *
6028 500_000)`` can take over a second on a fast CPU.
6029
6030 Limiting conversion size offers a practical way to avoid :cve:`2020-10735`.
6031
6032 The limit is applied to the number of digit characters in the input or output
6033 string when a non-linear conversion algorithm would be involved. Underscores
6034 and the sign are not counted towards the limit.
6035
6036 When an operation would exceed the limit, a :exc:`ValueError` is raised:
6037
6038 .. doctest::
6039
6040 >>> import sys
6041 >>> sys.set_int_max_str_digits(4300) # Illustrative, this is the default.
6042 >>> _ = int('2' * 5432)
6043 Traceback (most recent call last):
6044 ...
6045 ValueError: Exceeds the limit (4300 digits) for integer string conversion: value has 5432 digits; use sys.set_int_max_str_digits() to increase the limit
6046 >>> i = int('2' * 4300)
6047 >>> len(str(i))
6048 4300
6049 >>> i_squared = i*i
6050 >>> len(str(i_squared))
6051 Traceback (most recent call last):
6052 ...
6053 ValueError: Exceeds the limit (4300 digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit
6054 >>> len(hex(i_squared))
6055 7144
6056 >>> assert int(hex(i_squared), base=16) == i*i # Hexadecimal is unlimited.
6057
6058 The default limit is 4300 digits as provided in
6059 :data:`sys.int_info.default_max_str_digits <sys.int_info>`.
6060 The lowest limit that can be configured is 640 digits as provided in
6061 :data:`sys.int_info.str_digits_check_threshold <sys.int_info>`.
6062
6063 Verification:
6064
6065 .. doctest::
6066
6067 >>> import sys
6068 >>> assert sys.int_info.default_max_str_digits == 4300, sys.int_info
6069 >>> assert sys.int_info.str_digits_check_threshold == 640, sys.int_info
6070 >>> msg = int('578966293710682886880994035146873798396722250538762761564'
6071 ... '9252925514383915483333812743580549779436104706260696366600'
6072 ... '571186405732').to_bytes(53, 'big')
6073 ...
6074
6075 .. versionadded:: 3.11
6076
6077 Affected APIs
6078 -------------
6079
6080 The limitation only applies to potentially slow conversions between :class:`int`
6081 and :class:`str` or :class:`bytes`:
6082
6083 * ``int(string)`` with default base 10.
6084 * ``int(string, base)`` for all bases that are not a power of 2.
6085 * ``str(integer)``.
6086 * ``repr(integer)``.
6087 * any other string conversion to base 10, for example ``f"{integer}"``,
6088 ``"{}".format(integer)``, or ``b"%d" % integer``.
6089
6090 The limitations do not apply to functions with a linear algorithm:
6091
6092 * ``int(string, base)`` with base 2, 4, 8, 16, or 32.
6093 * :func:`int.from_bytes` and :func:`int.to_bytes`.
6094 * :func:`hex`, :func:`oct`, :func:`bin`.
6095 * :ref:`formatspec` for hex, octal, and binary numbers.
6096 * :class:`str` to :class:`float`.
6097 * :class:`str` to :class:`decimal.Decimal`.
6098
6099 Configuring the limit
6100 ---------------------
6101
6102 Before Python starts up you can use an environment variable or an interpreter
6103 command line flag to configure the limit:
6104
6105 * :envvar:`PYTHONINTMAXSTRDIGITS`, e.g.
6106 ``PYTHONINTMAXSTRDIGITS=640 python3`` to set the limit to 640 or
6107 ``PYTHONINTMAXSTRDIGITS=0 python3`` to disable the limitation.
6108 * :option:`-X int_max_str_digits <-X>`, e.g.
6109 ``python3 -X int_max_str_digits=640``
6110 * :data:`sys.flags.int_max_str_digits` contains the value of
6111 :envvar:`PYTHONINTMAXSTRDIGITS` or :option:`-X int_max_str_digits <-X>`.
6112 If both the env var and the ``-X`` option are set, the ``-X`` option takes
6113 precedence. A value of *-1* indicates that both were unset, thus a value of
6114 :data:`sys.int_info.default_max_str_digits` was used during initialization.
6115
6116 From code, you can inspect the current limit and set a new one using these
6117 :mod:`sys` APIs:
6118
6119 * :func:`sys.get_int_max_str_digits` and :func:`sys.set_int_max_str_digits` are
6120 a getter and setter for the interpreter-wide limit. Subinterpreters have
6121 their own limit.
6122
6123 Information about the default and minimum can be found in :data:`sys.int_info`:
6124
6125 * :data:`sys.int_info.default_max_str_digits <sys.int_info>` is the compiled-in
6126 default limit.
6127 * :data:`sys.int_info.str_digits_check_threshold <sys.int_info>` is the lowest
6128 accepted value for the limit (other than 0 which disables it).
6129
6130 .. versionadded:: 3.11
6131
6132 .. caution::
6133
6134 Setting a low limit *can* lead to problems. While rare, code exists that
6135 contains integer constants in decimal in their source that exceed the
6136 minimum threshold. A consequence of setting the limit is that Python source
6137 code containing decimal integer literals longer than the limit will
6138 encounter an error during parsing, usually at startup time or import time or
6139 even at installation time - anytime an up to date ``.pyc`` does not already
6140 exist for the code. A workaround for source that contains such large
6141 constants is to convert them to ``0x`` hexadecimal form as it has no limit.
6142
6143 Test your application thoroughly if you use a low limit. Ensure your tests
6144 run with the limit set early via the environment or flag so that it applies
6145 during startup and even during any installation step that may invoke Python
6146 to precompile ``.py`` sources to ``.pyc`` files.
6147
6148 Recommended configuration
6149 -------------------------
6150
6151 The default :data:`sys.int_info.default_max_str_digits` is expected to be
6152 reasonable for most applications. If your application requires a different
6153 limit, set it from your main entry point using Python version agnostic code as
6154 these APIs were added in security patch releases in versions before 3.12.
6155
6156 Example::
6157
6158 >>> import sys
6159 >>> if hasattr(sys, "set_int_max_str_digits"):
6160 ... upper_bound = 68000
6161 ... lower_bound = 4004
6162 ... current_limit = sys.get_int_max_str_digits()
6163 ... if current_limit == 0 or current_limit > upper_bound:
6164 ... sys.set_int_max_str_digits(upper_bound)
6165 ... elif current_limit < lower_bound:
6166 ... sys.set_int_max_str_digits(lower_bound)
6167
6168 If you need to disable it entirely, set it to ``0``.
6169
6170
6171 .. rubric:: Footnotes
6172
6173 .. [1] Additional information on these special methods may be found in the Python
6174 Reference Manual (:ref:`customization`).
6175
6176 .. [2] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and
6177 similarly for tuples.
6178
6179 .. [3] They must have since the parser can't tell the type of the operands.
6180
6181 .. [4] Cased characters are those with general category property being one of
6182 "Lu" (Letter, uppercase), "Ll" (Letter, lowercase), or "Lt" (Letter, titlecase).
6183
6184 .. [5] To format only a tuple you should therefore provide a singleton tuple whose only
6185 element is the tuple to be formatted.