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 are :ref:`generic <generics>` over the types of their items.
1355
1356 Lists implement all of the :ref:`common <typesseq-common>` and
1357 :ref:`mutable <typesseq-mutable>` sequence operations. Lists also provide the
1358 following additional method:
1359
1360 .. method:: list.sort(*, key=None, reverse=False)
1361
1362 This method sorts the list in place, using only ``<`` comparisons
1363 between items. Exceptions are not suppressed - if any comparison operations
1364 fail, the entire sort operation will fail (and the list will likely be left
1365 in a partially modified state).
1366
1367 :meth:`sort` accepts two arguments that can only be passed by keyword
1368 (:ref:`keyword-only arguments <keyword-only_parameter>`):
1369
1370 *key* specifies a function of one argument that is used to extract a
1371 comparison key from each list element (for example, ``key=str.lower``).
1372 The key corresponding to each item in the list is calculated once and
1373 then used for the entire sorting process. The default value of ``None``
1374 means that list items are sorted directly without calculating a separate
1375 key value.
1376
1377 The :func:`functools.cmp_to_key` utility is available to convert a 2.x
1378 style *cmp* function to a *key* function.
1379
1380 *reverse* is a boolean value. If set to ``True``, then the list elements
1381 are sorted as if each comparison were reversed.
1382
1383 This method modifies the sequence in place for economy of space when
1384 sorting a large sequence. To remind users that it operates by side
1385 effect, it does not return the sorted sequence (use :func:`sorted` to
1386 explicitly request a new sorted list instance).
1387
1388 The :meth:`sort` method is guaranteed to be stable. A sort is stable if it
1389 guarantees not to change the relative order of elements that compare equal
1390 --- this is helpful for sorting in multiple passes (for example, sort by
1391 department, then by salary grade).
1392
1393 For sorting examples and a brief sorting tutorial, see :ref:`sortinghowto`.
1394
1395 .. impl-detail::
1396
1397 While a list is being sorted, the effect of attempting to mutate, or even
1398 inspect, the list is undefined. The C implementation of Python makes the
1399 list appear empty for the duration, and raises :exc:`ValueError` if it can
1400 detect that the list has been mutated during a sort.
1401
1402
1403 .. _typesseq-tuple:
1404
1405 Tuples
1406 ------
1407
1408 .. index:: pair: object; tuple
1409
1410 Tuples are immutable sequences, typically used to store collections of
1411 heterogeneous data (such as the 2-tuples produced by the :func:`enumerate`
1412 built-in). Tuples are also used for cases where an immutable sequence of
1413 homogeneous data is needed (such as allowing storage in a :class:`set` or
1414 :class:`dict` instance).
1415
1416 .. class:: tuple(iterable=(), /)
1417
1418 Tuples may be constructed in a number of ways:
1419
1420 * Using a pair of parentheses to denote the empty tuple: ``()``
1421 * Using a trailing comma for a singleton tuple: ``a,`` or ``(a,)``
1422 * Separating items with commas: ``a, b, c`` or ``(a, b, c)``
1423 * Using the :func:`tuple` built-in: ``tuple()`` or ``tuple(iterable)``
1424
1425 The constructor builds a tuple whose items are the same and in the same
1426 order as *iterable*'s items. *iterable* may be either a sequence, a
1427 container that supports iteration, or an iterator object. If *iterable*
1428 is already a tuple, it is returned unchanged. For example,
1429 ``tuple('abc')`` returns ``('a', 'b', 'c')`` and
1430 ``tuple( [1, 2, 3] )`` returns ``(1, 2, 3)``.
1431 If no argument is given, the constructor creates a new empty tuple, ``()``.
1432
1433 Note that it is actually the comma which makes a tuple, not the parentheses.
1434 The parentheses are optional, except in the empty tuple case, or
1435 when they are needed to avoid syntactic ambiguity. For example,
1436 ``f(a, b, c)`` is a function call with three arguments, while
1437 ``f((a, b, c))`` is a function call with a 3-tuple as the sole argument.
1438
1439 Tuples implement all of the :ref:`common <typesseq-common>` sequence
1440 operations.
1441
1442 Tuples are :ref:`generic <generics>` over the types of their contents.
1443 For more information, refer to
1444 :ref:`the typing documentation on annotating tuples <annotating-tuples>`.
1445
1446 For heterogeneous collections of data where access by name is clearer than
1447 access by index, :func:`collections.namedtuple` may be a more appropriate
1448 choice than a simple tuple object.
1449
1450
1451 .. _typesseq-range:
1452
1453 Ranges
1454 ------
1455
1456 .. index:: pair: object; range
1457
1458 The :class:`range` type represents an immutable sequence of numbers and is
1459 commonly used for looping a specific number of times in :keyword:`for`
1460 loops.
1461
1462 .. class:: range(stop, /)
1463 range(start, stop, step=1, /)
1464
1465 The arguments to the range constructor must be integers (either built-in
1466 :class:`int` or any object that implements the :meth:`~object.__index__` special
1467 method). If the *step* argument is omitted, it defaults to ``1``.
1468 If the *start* argument is omitted, it defaults to ``0``.
1469 If *step* is zero, :exc:`ValueError` is raised.
1470
1471 For a positive *step*, the contents of a range ``r`` are determined by the
1472 formula ``r[i] = start + step*i`` where ``i >= 0`` and
1473 ``r[i] < stop``.
1474
1475 For a negative *step*, the contents of the range are still determined by
1476 the formula ``r[i] = start + step*i``, but the constraints are ``i >= 0``
1477 and ``r[i] > stop``.
1478
1479 A range object will be empty if ``r[0]`` does not meet the value
1480 constraint. Ranges do support negative indices, but these are interpreted
1481 as indexing from the end of the sequence determined by the positive
1482 indices.
1483
1484 Ranges containing absolute values larger than :data:`sys.maxsize` are
1485 permitted but some features (such as :func:`len`) may raise
1486 :exc:`OverflowError`.
1487
1488 Range examples::
1489
1490 >>> list(range(10))
1491 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1492 >>> list(range(1, 11))
1493 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
1494 >>> list(range(0, 30, 5))
1495 [0, 5, 10, 15, 20, 25]
1496 >>> list(range(0, 10, 3))
1497 [0, 3, 6, 9]
1498 >>> list(range(0, -10, -1))
1499 [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
1500 >>> list(range(0))
1501 []
1502 >>> list(range(1, 0))
1503 []
1504
1505 Ranges implement all of the :ref:`common <typesseq-common>` sequence operations
1506 except concatenation and repetition (due to the fact that range objects can
1507 only represent sequences that follow a strict pattern and repetition and
1508 concatenation will usually violate that pattern).
1509
1510 .. attribute:: start
1511
1512 The value of the *start* parameter (or ``0`` if the parameter was
1513 not supplied)
1514
1515 .. attribute:: stop
1516
1517 The value of the *stop* parameter
1518
1519 .. attribute:: step
1520
1521 The value of the *step* parameter (or ``1`` if the parameter was
1522 not supplied)
1523
1524 The advantage of the :class:`range` type over a regular :class:`list` or
1525 :class:`tuple` is that a :class:`range` object will always take the same
1526 (small) amount of memory, no matter the size of the range it represents (as it
1527 only stores the ``start``, ``stop`` and ``step`` values, calculating individual
1528 items and subranges as needed).
1529
1530 Range objects implement the :class:`collections.abc.Sequence` ABC, and provide
1531 features such as containment tests, element index lookup, slicing and
1532 support for negative indices (see :ref:`typesseq`):
1533
1534 >>> r = range(0, 20, 2)
1535 >>> r
1536 range(0, 20, 2)
1537 >>> 11 in r
1538 False
1539 >>> 10 in r
1540 True
1541 >>> r.index(10)
1542 5
1543 >>> r[5]
1544 10
1545 >>> r[:5]
1546 range(0, 10, 2)
1547 >>> r[-1]
1548 18
1549
1550 Testing range objects for equality with ``==`` and ``!=`` compares
1551 them as sequences. That is, two range objects are considered equal if
1552 they represent the same sequence of values. (Note that two range
1553 objects that compare equal might have different :attr:`~range.start`,
1554 :attr:`~range.stop` and :attr:`~range.step` attributes, for example
1555 ``range(0) == range(2, 1, 3)`` or ``range(0, 3, 2) == range(0, 4, 2)``.)
1556
1557 .. versionchanged:: 3.2
1558 Implement the Sequence ABC.
1559 Support slicing and negative indices.
1560 Test :class:`int` objects for membership in constant time instead of
1561 iterating through all items.
1562
1563 .. versionchanged:: 3.3
1564 Define '==' and '!=' to compare range objects based on the
1565 sequence of values they define (instead of comparing based on
1566 object identity).
1567
1568 Added the :attr:`~range.start`, :attr:`~range.stop` and :attr:`~range.step`
1569 attributes.
1570
1571 .. seealso::
1572
1573 * The `linspace recipe <https://code.activestate.com/recipes/579000-equally-spaced-numbers-linspace/>`_
1574 shows how to implement a lazy version of range suitable for floating-point
1575 applications.
1576
1577 .. index::
1578 single: string; text sequence type
1579 single: str (built-in class); (see also string)
1580 pair: object; string
1581
1582 .. _textseq:
1583
1584 Text Sequence Type --- :class:`str`
1585 ===================================
1586
1587 Textual data in Python is handled with :class:`str` objects, or :dfn:`strings`.
1588 Strings are immutable
1589 :ref:`sequences <typesseq>` of Unicode code points. String literals are
1590 written in a variety of ways:
1591
1592 * Single quotes: ``'allows embedded "double" quotes'``
1593 * Double quotes: ``"allows embedded 'single' quotes"``
1594 * Triple quoted: ``'''Three single quotes'''``, ``"""Three double quotes"""``
1595
1596 Triple quoted strings may span multiple lines - all associated whitespace will
1597 be included in the string literal.
1598
1599 String literals that are part of a single expression and have only whitespace
1600 between them will be implicitly converted to a single string literal. That
1601 is, ``("spam " "eggs") == "spam eggs"``.
1602
1603 See :ref:`strings` for more about the various forms of string literal,
1604 including supported :ref:`escape sequences <escape-sequences>`, and the ``r`` ("raw") prefix that
1605 disables most escape sequence processing.
1606
1607 Strings may also be created from other objects using the :class:`str`
1608 constructor.
1609
1610 Since there is no separate "character" type, indexing a string produces
1611 strings of length 1. That is, for a non-empty string *s*, ``s[0] == s[0:1]``.
1612
1613 .. index::
1614 pair: object; io.StringIO
1615
1616 There is also no mutable string type, but :meth:`str.join` or
1617 :class:`io.StringIO` can be used to efficiently construct strings from
1618 multiple fragments.
1619
1620 .. versionchanged:: 3.3
1621 For backwards compatibility with the Python 2 series, the ``u`` prefix is
1622 once again permitted on string literals. It has no effect on the meaning
1623 of string literals and cannot be combined with the ``r`` prefix.
1624
1625
1626 .. index::
1627 single: string; str (built-in class)
1628
1629 .. class:: str(*, encoding='utf-8', errors='strict')
1630 str(object)
1631 str(object, encoding, errors='strict')
1632 str(object, *, errors)
1633
1634 Return a :ref:`string <textseq>` version of *object*. If *object* is not
1635 provided, returns the empty string. Otherwise, the behavior of ``str()``
1636 depends on whether *encoding* or *errors* is given, as follows.
1637
1638 If neither *encoding* nor *errors* is given, ``str(object)`` returns
1639 :meth:`type(object).__str__(object) <object.__str__>`,
1640 which is the "informal" or nicely
1641 printable string representation of *object*. For string objects, this is
1642 the string itself. If *object* does not have a :meth:`~object.__str__`
1643 method, then :func:`str` falls back to returning
1644 :func:`repr(object) <repr>`.
1645
1646 .. index::
1647 single: buffer protocol; str (built-in class)
1648 single: bytes; str (built-in class)
1649
1650 If at least one of *encoding* or *errors* is given, *object* should be a
1651 :term:`bytes-like object` (e.g. :class:`bytes` or :class:`bytearray`). In
1652 this case, if *object* is a :class:`bytes` (or :class:`bytearray`) object,
1653 then ``str(bytes, encoding, errors)`` is equivalent to
1654 :meth:`bytes.decode(encoding, errors) <bytes.decode>`. Otherwise, the bytes
1655 object underlying the buffer object is obtained before calling
1656 :meth:`bytes.decode`. See :ref:`binaryseq` and
1657 :ref:`bufferobjects` for information on buffer objects.
1658
1659 Passing a :class:`bytes` object to :func:`str` without the *encoding*
1660 or *errors* arguments falls under the first case of returning the informal
1661 string representation (see also the :option:`-b` command-line option to
1662 Python). For example::
1663
1664 >>> str(b'Zoot!')
1665 "b'Zoot!'"
1666
1667 For more information on the ``str`` class and its methods, see
1668 :ref:`textseq` and the :ref:`string-methods` section below. To output
1669 formatted strings, see the :ref:`f-strings` and :ref:`formatstrings`
1670 sections. In addition, see the :ref:`stringservices` section.
1671
1672
1673 .. index::
1674 pair: string; methods
1675
1676 .. _string-methods:
1677
1678 String Methods
1679 --------------
1680
1681 .. index::
1682 pair: module; re
1683
1684 Strings implement all of the :ref:`common <typesseq-common>` sequence
1685 operations, along with the additional methods described below.
1686
1687 Strings also support two styles of string formatting, one providing a large
1688 degree of flexibility and customization (see :meth:`str.format`,
1689 :ref:`formatstrings` and :ref:`string-formatting`) and the other based on C
1690 ``printf`` style formatting that handles a narrower range of types and is
1691 slightly harder to use correctly, but is often faster for the cases it can
1692 handle (:ref:`old-string-formatting`).
1693
1694 The :ref:`textservices` section of the standard library covers a number of
1695 other modules that provide various text related utilities (including regular
1696 expression support in the :mod:`re` module).
1697
1698 .. method:: str.capitalize()
1699
1700 Return a copy of the string with its first character capitalized and the
1701 rest lowercased.
1702
1703 .. versionchanged:: 3.8
1704 The first character is now put into titlecase rather than uppercase.
1705 This means that characters like digraphs will only have their first
1706 letter capitalized, instead of the full character.
1707
1708 .. method:: str.casefold()
1709
1710 Return a casefolded copy of the string. Casefolded strings may be used for
1711 caseless matching.
1712
1713 Casefolding is similar to lowercasing but more aggressive because it is
1714 intended to remove all case distinctions in a string. For example, the German
1715 lowercase letter ``'ß'`` is equivalent to ``"ss"``. Since it is already
1716 lowercase, :meth:`lower` would do nothing to ``'ß'``; :meth:`casefold`
1717 converts it to ``"ss"``.
1718 For example:
1719
1720 .. doctest::
1721
1722 >>> 'straße'.lower()
1723 'straße'
1724 >>> 'straße'.casefold()
1725 'strasse'
1726
1727 The casefolding algorithm is
1728 `described in section 3.13 'Default Case Folding' of the Unicode Standard
1729 <https://www.unicode.org/versions/Unicode15.1.0/ch03.pdf>`__.
1730
1731 .. versionadded:: 3.3
1732
1733
1734 .. method:: str.center(width, fillchar=' ', /)
1735
1736 Return centered in a string of length *width*. Padding is done using the
1737 specified *fillchar* (default is an ASCII space). The original string is
1738 returned if *width* is less than or equal to ``len(s)``. For example::
1739
1740 >>> 'Python'.center(10)
1741 ' Python '
1742 >>> 'Python'.center(10, '-')
1743 '--Python--'
1744 >>> 'Python'.center(4)
1745 'Python'
1746
1747
1748 .. method:: str.count(sub[, start[, end]])
1749
1750 Return the number of non-overlapping occurrences of substring *sub* in the
1751 range [*start*, *end*]. Optional arguments *start* and *end* are
1752 interpreted as in slice notation.
1753
1754 If *sub* is empty, returns the number of empty strings between characters
1755 which is the length of the string plus one. For example::
1756
1757 >>> 'spam, spam, spam'.count('spam')
1758 3
1759 >>> 'spam, spam, spam'.count('spam', 5)
1760 2
1761 >>> 'spam, spam, spam'.count('spam', 5, 10)
1762 1
1763 >>> 'spam, spam, spam'.count('eggs')
1764 0
1765 >>> 'spam, spam, spam'.count('')
1766 17
1767
1768 .. method:: str.encode(encoding="utf-8", errors="strict")
1769
1770 Return the string encoded to :class:`bytes`.
1771
1772 *encoding* defaults to ``'utf-8'``;
1773 see :ref:`standard-encodings` for possible values.
1774
1775 *errors* controls how encoding errors are handled.
1776 If ``'strict'`` (the default), a :exc:`UnicodeError` exception is raised.
1777 Other possible values are ``'ignore'``,
1778 ``'replace'``, ``'xmlcharrefreplace'``, ``'backslashreplace'`` and any
1779 other name registered via :func:`codecs.register_error`.
1780 See :ref:`error-handlers` for details.
1781
1782 For performance reasons, the value of *errors* is not checked for validity
1783 unless an encoding error actually occurs,
1784 :ref:`devmode` is enabled
1785 or a :ref:`debug build <debug-build>` is used.
1786 For example::
1787
1788 >>> encoded_str_to_bytes = 'Python'.encode()
1789 >>> type(encoded_str_to_bytes)
1790 <class 'bytes'>
1791 >>> encoded_str_to_bytes
1792 b'Python'
1793
1794
1795 .. versionchanged:: 3.1
1796 Added support for keyword arguments.
1797
1798 .. versionchanged:: 3.9
1799 The value of the *errors* argument is now checked in :ref:`devmode` and
1800 in :ref:`debug mode <debug-build>`.
1801
1802
1803 .. method:: str.endswith(suffix[, start[, end]])
1804
1805 Return ``True`` if the string ends with the specified *suffix*, otherwise return
1806 ``False``. *suffix* can also be a tuple of suffixes to look for. With optional
1807 *start*, test beginning at that position. With optional *end*, stop comparing
1808 at that position. Using *start* and *end* is equivalent to
1809 ``str[start:end].endswith(suffix)``. For example::
1810
1811 >>> 'Python'.endswith('on')
1812 True
1813 >>> 'a tuple of suffixes'.endswith(('at', 'in'))
1814 False
1815 >>> 'a tuple of suffixes'.endswith(('at', 'es'))
1816 True
1817 >>> 'Python is amazing'.endswith('is', 0, 9)
1818 True
1819
1820 See also :meth:`startswith` and :meth:`removesuffix`.
1821
1822
1823 .. method:: str.expandtabs(tabsize=8)
1824
1825 Return a copy of the string where all tab characters are replaced by one or
1826 more spaces, depending on the current column and the given tab size. Tab
1827 positions occur every *tabsize* characters (default is 8, giving tab
1828 positions at columns 0, 8, 16 and so on). To expand the string, the current
1829 column is set to zero and the string is examined character by character. If
1830 the character is a tab (``\t``), one or more space characters are inserted
1831 in the result until the current column is equal to the next tab position.
1832 (The tab character itself is not copied.) If the character is a newline
1833 (``\n``) or return (``\r``), it is copied and the current column is reset to
1834 zero. Any other character is copied unchanged and the current column is
1835 incremented by one regardless of how the character is represented when
1836 printed. For example::
1837
1838 >>> '01\t012\t0123\t01234'.expandtabs()
1839 '01 012 0123 01234'
1840 >>> '01\t012\t0123\t01234'.expandtabs(4)
1841 '01 012 0123 01234'
1842 >>> print('01\t012\n0123\t01234'.expandtabs(4))
1843 01 012
1844 0123 01234
1845
1846
1847 .. method:: str.find(sub[, start[, end]])
1848
1849 Return the lowest index in the string where substring *sub* is found within
1850 the slice ``s[start:end]``. Optional arguments *start* and *end* are
1851 interpreted as in slice notation. Return ``-1`` if *sub* is not found.
1852 For example::
1853
1854 >>> 'spam, spam, spam'.find('sp')
1855 0
1856 >>> 'spam, spam, spam'.find('sp', 5)
1857 6
1858
1859 See also :meth:`rfind` and :meth:`index`.
1860
1861 .. note::
1862
1863 The :meth:`~str.find` method should be used only if you need to know the
1864 position of *sub*. To check if *sub* is a substring or not, use the
1865 :keyword:`in` operator::
1866
1867 >>> 'Py' in 'Python'
1868 True
1869
1870
1871 .. method:: str.format(*args, **kwargs)
1872
1873 Perform a string formatting operation. The string on which this method is
1874 called can contain literal text or replacement fields delimited by braces
1875 ``{}``. Each replacement field contains either the numeric index of a
1876 positional argument, or the name of a keyword argument. Returns a copy of
1877 the string where each replacement field is replaced with the string value of
1878 the corresponding argument. For example:
1879
1880 .. doctest::
1881
1882 >>> "The sum of 1 + 2 is {0}".format(1+2)
1883 'The sum of 1 + 2 is 3'
1884 >>> "The sum of {a} + {b} is {answer}".format(answer=1+2, a=1, b=2)
1885 'The sum of 1 + 2 is 3'
1886 >>> "{1} expects the {0} Inquisition!".format("Spanish", "Nobody")
1887 'Nobody expects the Spanish Inquisition!'
1888
1889 See :ref:`formatstrings` for a description of the various formatting options
1890 that can be specified in format strings.
1891
1892 .. note::
1893 When formatting a number (:class:`int`, :class:`float`, :class:`complex`,
1894 :class:`decimal.Decimal` and subclasses) with the ``n`` type
1895 (ex: ``'{:n}'.format(1234)``), the function temporarily sets the
1896 ``LC_CTYPE`` locale to the ``LC_NUMERIC`` locale to decode
1897 ``decimal_point`` and ``thousands_sep`` fields of :c:func:`localeconv` if
1898 they are non-ASCII or longer than 1 byte, and the ``LC_NUMERIC`` locale is
1899 different than the ``LC_CTYPE`` locale. This temporary change affects
1900 other threads.
1901
1902 .. versionchanged:: 3.7
1903 When formatting a number with the ``n`` type, the function sets
1904 temporarily the ``LC_CTYPE`` locale to the ``LC_NUMERIC`` locale in some
1905 cases.
1906
1907
1908 .. method:: str.format_map(mapping, /)
1909
1910 Similar to ``str.format(**mapping)``, except that ``mapping`` is
1911 used directly and not copied to a :class:`dict`. This is useful
1912 if for example ``mapping`` is a dict subclass:
1913
1914 >>> class Default(dict):
1915 ... def __missing__(self, key):
1916 ... return key
1917 ...
1918 >>> '{name} was born in {country}'.format_map(Default(name='Guido'))
1919 'Guido was born in country'
1920
1921 .. versionadded:: 3.2
1922
1923
1924 .. method:: str.index(sub[, start[, end]])
1925
1926 Like :meth:`~str.find`, but raise :exc:`ValueError` when the substring is
1927 not found. For example:
1928
1929 .. doctest::
1930
1931 >>> 'spam, spam, spam'.index('spam')
1932 0
1933 >>> 'spam, spam, spam'.index('eggs')
1934 Traceback (most recent call last):
1935 File "<python-input-0>", line 1, in <module>
1936 'spam, spam, spam'.index('eggs')
1937 ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
1938 ValueError: substring not found
1939
1940 See also :meth:`rindex`.
1941
1942
1943 .. method:: str.isalnum()
1944
1945 Return ``True`` if all characters in the string are alphanumeric and there is at
1946 least one character, ``False`` otherwise. A character ``c`` is alphanumeric if one
1947 of the following returns ``True``: ``c.isalpha()``, ``c.isdecimal()``,
1948 ``c.isdigit()``, or ``c.isnumeric()``. For example:
1949
1950 .. doctest::
1951
1952 >>> 'abc123'.isalnum()
1953 True
1954 >>> 'abc123!@#'.isalnum()
1955 False
1956 >>> ''.isalnum()
1957 False
1958 >>> ' '.isalnum()
1959 False
1960
1961
1962 .. method:: str.isalpha()
1963
1964 Return ``True`` if all characters in the string are alphabetic and there is at least
1965 one character, ``False`` otherwise. Alphabetic characters are those characters defined
1966 in the Unicode character database as "Letter", i.e., those with general category
1967 property being one of "Lm", "Lt", "Lu", "Ll", or "Lo". Note that this is different
1968 from the `Alphabetic property defined in the section 4.10 'Letters, Alphabetic, and
1969 Ideographic' of the Unicode Standard
1970 <https://www.unicode.org/versions/Unicode15.1.0/ch04.pdf>`_.
1971 For example:
1972
1973 .. doctest::
1974
1975 >>> 'Letters and spaces'.isalpha()
1976 False
1977 >>> 'LettersOnly'.isalpha()
1978 True
1979 >>> 'µ'.isalpha() # non-ASCII characters can be considered alphabetical too
1980 True
1981
1982 See :ref:`unicode-properties`.
1983
1984
1985 .. method:: str.isascii()
1986
1987 Return ``True`` if the string is empty or all characters in the string are ASCII,
1988 ``False`` otherwise.
1989 ASCII characters have code points in the range U+0000-U+007F. For example:
1990
1991 .. doctest::
1992
1993 >>> 'ASCII characters'.isascii()
1994 True
1995 >>> 'µ'.isascii()
1996 False
1997
1998 .. versionadded:: 3.7
1999
2000
2001 .. method:: str.isdecimal()
2002
2003 Return ``True`` if all characters in the string are decimal
2004 characters and there is at least one character, ``False``
2005 otherwise. Decimal characters are those that can be used to form
2006 numbers in base 10, such as U+0660, ARABIC-INDIC DIGIT
2007 ZERO. Formally a decimal character is a character in the Unicode
2008 General Category "Nd". For example:
2009
2010 .. doctest::
2011
2012 >>> '0123456789'.isdecimal()
2013 True
2014 >>> '٠١٢٣٤٥٦٧٨٩'.isdecimal() # Arabic-Indic digits zero to nine
2015 True
2016 >>> 'alphabetic'.isdecimal()
2017 False
2018
2019
2020 .. method:: str.isdigit()
2021
2022 Return ``True`` if all characters in the string are digits and there is at least one
2023 character, ``False`` otherwise. Digits include decimal characters and digits that need
2024 special handling, such as the compatibility superscript digits.
2025 This covers digits which cannot be used to form numbers in base 10,
2026 like the `Kharosthi numbers <https://en.wikipedia.org/wiki/Kharosthi#Numerals>`__.
2027 Formally, a digit is a character that has the
2028 property value Numeric_Type=Digit or Numeric_Type=Decimal.
2029
2030 For example:
2031
2032 .. doctest::
2033
2034 >>> '0123456789'.isdigit()
2035 True
2036 >>> '٠١٢٣٤٥٦٧٨٩'.isdigit() # Arabic-Indic digits zero to nine
2037 True
2038 >>> 'â…•'.isdigit() # Vulgar fraction one fifth
2039 False
2040 >>> '²'.isdecimal(), '²'.isdigit(), '²'.isnumeric()
2041 (False, True, True)
2042
2043 See also :meth:`isdecimal` and :meth:`isnumeric`.
2044
2045
2046 .. method:: str.isidentifier()
2047
2048 Return ``True`` if the string is a valid identifier according to the language
2049 definition, section :ref:`identifiers`.
2050
2051 :func:`keyword.iskeyword` can be used to test whether string ``s`` is a reserved
2052 identifier, such as :keyword:`def` and :keyword:`class`.
2053
2054 Example:
2055 ::
2056
2057 >>> from keyword import iskeyword
2058
2059 >>> 'hello'.isidentifier(), iskeyword('hello')
2060 (True, False)
2061 >>> 'def'.isidentifier(), iskeyword('def')
2062 (True, True)
2063
2064
2065 .. method:: str.islower()
2066
2067 Return ``True`` if all cased characters [4]_ in the string are lowercase and
2068 there is at least one cased character, ``False`` otherwise.
2069
2070
2071 .. method:: str.isnumeric()
2072
2073 Return ``True`` if all characters in the string are numeric
2074 characters, and there is at least one character, ``False``
2075 otherwise. Numeric characters include digit characters, and all characters
2076 that have the Unicode numeric value property, e.g. U+2155,
2077 VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property
2078 value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.
2079 For example:
2080
2081 .. doctest::
2082
2083 >>> '0123456789'.isnumeric()
2084 True
2085 >>> '٠١٢٣٤٥٦٧٨٩'.isnumeric() # Arabic-Indic digits zero to nine
2086 True
2087 >>> 'â…•'.isnumeric() # Vulgar fraction one fifth
2088 True
2089 >>> '²'.isdecimal(), '²'.isdigit(), '²'.isnumeric()
2090 (False, True, True)
2091
2092 See also :meth:`isdecimal` and :meth:`isdigit`.
2093
2094
2095 .. method:: str.isprintable()
2096
2097 Return ``True`` if all characters in the string are printable, ``False`` if it
2098 contains at least one non-printable character.
2099
2100 Here "printable" means the character is suitable for :func:`repr` to use in
2101 its output; "non-printable" means that :func:`repr` on built-in types will
2102 hex-escape the character. It has no bearing on the handling of strings
2103 written to :data:`sys.stdout` or :data:`sys.stderr`.
2104
2105 The printable characters are those which in the Unicode character database
2106 (see :mod:`unicodedata`) have a general category in group Letter, Mark,
2107 Number, Punctuation, or Symbol (L, M, N, P, or S); plus the ASCII space 0x20.
2108 Nonprintable characters are those in group Separator or Other (Z or C),
2109 except the ASCII space.
2110
2111 For example:
2112
2113 .. doctest::
2114
2115 >>> ''.isprintable(), ' '.isprintable()
2116 (True, True)
2117 >>> '\t'.isprintable(), '\n'.isprintable()
2118 (False, False)
2119
2120 See also :meth:`isspace`.
2121
2122
2123 .. method:: str.isspace()
2124
2125 Return ``True`` if there are only whitespace characters in the string and there is
2126 at least one character, ``False`` otherwise.
2127
2128 For example:
2129
2130 .. doctest::
2131
2132 >>> ''.isspace()
2133 False
2134 >>> ' '.isspace()
2135 True
2136 >>> '\t\n'.isspace() # TAB and BREAK LINE
2137 True
2138 >>> '\u3000'.isspace() # IDEOGRAPHIC SPACE
2139 True
2140
2141 A character is *whitespace* if in the Unicode character database
2142 (see :mod:`unicodedata`), either its general category is ``Zs``
2143 ("Separator, space"), or its bidirectional class is one of ``WS``,
2144 ``B``, or ``S``.
2145
2146 See also :meth:`isprintable`.
2147
2148
2149 .. method:: str.istitle()
2150
2151 Return ``True`` if the string is a titlecased string and there is at least one
2152 character, for example uppercase characters may only follow uncased characters
2153 and lowercase characters only cased ones. Return ``False`` otherwise.
2154
2155 For example:
2156
2157 .. doctest::
2158
2159 >>> 'Spam, Spam, Spam'.istitle()
2160 True
2161 >>> 'spam, spam, spam'.istitle()
2162 False
2163 >>> 'SPAM, SPAM, SPAM'.istitle()
2164 False
2165
2166 See also :meth:`title`.
2167
2168
2169 .. method:: str.isupper()
2170
2171 Return ``True`` if all cased characters [4]_ in the string are uppercase and
2172 there is at least one cased character, ``False`` otherwise.
2173
2174 >>> 'BANANA'.isupper()
2175 True
2176 >>> 'banana'.isupper()
2177 False
2178 >>> 'baNana'.isupper()
2179 False
2180 >>> ' '.isupper()
2181 False
2182
2183
2184
2185 .. _meth-str-join:
2186
2187 .. method:: str.join(iterable, /)
2188
2189 Return a string which is the concatenation of the strings in *iterable*.
2190 A :exc:`TypeError` will be raised if there are any non-string values in
2191 *iterable*, including :class:`bytes` objects. The separator between
2192 elements is the string providing this method. For example:
2193
2194 .. doctest::
2195
2196 >>> ', '.join(['spam', 'spam', 'spam'])
2197 'spam, spam, spam'
2198 >>> '-'.join('Python')
2199 'P-y-t-h-o-n'
2200
2201 See also :meth:`split`.
2202
2203
2204 .. method:: str.ljust(width, fillchar=' ', /)
2205
2206 Return the string left justified in a string of length *width*. Padding is
2207 done using the specified *fillchar* (default is an ASCII space). The
2208 original string is returned if *width* is less than or equal to ``len(s)``.
2209
2210 For example:
2211
2212 .. doctest::
2213
2214 >>> 'Python'.ljust(10)
2215 'Python '
2216 >>> 'Python'.ljust(10, '.')
2217 'Python....'
2218 >>> 'Monty Python'.ljust(10, '.')
2219 'Monty Python'
2220
2221 See also :meth:`rjust`.
2222
2223
2224 .. method:: str.lower()
2225
2226 Return a copy of the string with all the cased characters [4]_ converted to
2227 lowercase. For example:
2228
2229 .. doctest::
2230
2231 >>> 'Lower Method Example'.lower()
2232 'lower method example'
2233
2234 The lowercasing algorithm used is
2235 `described in section 3.13 'Default Case Folding' of the Unicode Standard
2236 <https://www.unicode.org/versions/Unicode15.1.0/ch03.pdf>`__.
2237
2238
2239 .. method:: str.lstrip(chars=None, /)
2240
2241 Return a copy of the string with leading characters removed. The *chars*
2242 argument is a string specifying the set of characters to be removed. If omitted
2243 or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
2244 argument is not a prefix; rather, all combinations of its values are stripped::
2245
2246 >>> ' spacious '.lstrip()
2247 'spacious '
2248 >>> 'www.example.com'.lstrip('cmowz.')
2249 'example.com'
2250
2251 See :meth:`str.removeprefix` for a method that will remove a single prefix
2252 string rather than all of a set of characters. For example::
2253
2254 >>> 'Arthur: three!'.lstrip('Arthur: ')
2255 'ee!'
2256 >>> 'Arthur: three!'.removeprefix('Arthur: ')
2257 'three!'
2258
2259
2260 .. staticmethod:: str.maketrans(dict, /)
2261 str.maketrans(from, to, remove='', /)
2262
2263 This static method returns a translation table usable for :meth:`str.translate`.
2264
2265 If there is only one argument, it must be a dictionary mapping Unicode
2266 ordinals (integers) or characters (strings of length 1) to Unicode ordinals,
2267 strings (of arbitrary lengths) or ``None``. Character keys will then be
2268 converted to ordinals.
2269
2270 If there are two arguments, they must be strings of equal length, and in the
2271 resulting dictionary, each character in *from* will be mapped to the character at
2272 the same position in *to*. If there is a third argument, it must be a string,
2273 whose characters will be mapped to ``None`` in the result.
2274
2275
2276 .. method:: str.partition(sep, /)
2277
2278 Split the string at the first occurrence of *sep*, and return a 3-tuple
2279 containing the part before the separator, the separator itself, and the part
2280 after the separator. If the separator is not found, return a 3-tuple containing
2281 the string itself, followed by two empty strings.
2282
2283 For example:
2284
2285 .. doctest::
2286
2287 >>> 'Monty Python'.partition(' ')
2288 ('Monty', ' ', 'Python')
2289 >>> "Monty Python's Flying Circus".partition(' ')
2290 ('Monty', ' ', "Python's Flying Circus")
2291 >>> 'Monty Python'.partition('-')
2292 ('Monty Python', '', '')
2293
2294 See also :meth:`rpartition`.
2295
2296
2297 .. method:: str.removeprefix(prefix, /)
2298
2299 If the string starts with the *prefix* string, return
2300 ``string[len(prefix):]``. Otherwise, return a copy of the original
2301 string:
2302
2303 .. doctest::
2304
2305 >>> 'TestHook'.removeprefix('Test')
2306 'Hook'
2307 >>> 'BaseTestCase'.removeprefix('Test')
2308 'BaseTestCase'
2309
2310 .. versionadded:: 3.9
2311
2312 See also :meth:`removesuffix` and :meth:`startswith`.
2313
2314
2315 .. method:: str.removesuffix(suffix, /)
2316
2317 If the string ends with the *suffix* string and that *suffix* is not empty,
2318 return ``string[:-len(suffix)]``. Otherwise, return a copy of the
2319 original string:
2320
2321 .. doctest::
2322
2323 >>> 'MiscTests'.removesuffix('Tests')
2324 'Misc'
2325 >>> 'TmpDirMixin'.removesuffix('Tests')
2326 'TmpDirMixin'
2327
2328 .. versionadded:: 3.9
2329
2330 See also :meth:`removeprefix` and :meth:`endswith`.
2331
2332
2333 .. method:: str.replace(old, new, /, count=-1)
2334
2335 Return a copy of the string with all occurrences of substring *old* replaced by
2336 *new*. If *count* is given, only the first *count* occurrences are replaced.
2337 If *count* is not specified or ``-1``, then all occurrences are replaced.
2338 For example:
2339
2340 .. doctest::
2341
2342 >>> 'spam, spam, spam'.replace('spam', 'eggs')
2343 'eggs, eggs, eggs'
2344 >>> 'spam, spam, spam'.replace('spam', 'eggs', 1)
2345 'eggs, spam, spam'
2346
2347 .. versionchanged:: 3.13
2348 *count* is now supported as a keyword argument.
2349
2350
2351 .. method:: str.rfind(sub[, start[, end]])
2352
2353 Return the highest index in the string where substring *sub* is found, such
2354 that *sub* is contained within ``s[start:end]``. Optional arguments *start*
2355 and *end* are interpreted as in slice notation. Return ``-1`` on failure.
2356 For example:
2357
2358 .. doctest::
2359
2360 >>> 'spam, spam, spam'.rfind('sp')
2361 12
2362 >>> 'spam, spam, spam'.rfind('sp', 0, 10)
2363 6
2364
2365 See also :meth:`find` and :meth:`rindex`.
2366
2367
2368 .. method:: str.rindex(sub[, start[, end]])
2369
2370 Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not
2371 found.
2372 For example:
2373
2374 .. doctest::
2375
2376 >>> 'spam, spam, spam'.rindex('spam')
2377 12
2378 >>> 'spam, spam, spam'.rindex('eggs')
2379 Traceback (most recent call last):
2380 File "<stdin-0>", line 1, in <module>
2381 'spam, spam, spam'.rindex('eggs')
2382 ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
2383 ValueError: substring not found
2384
2385 See also :meth:`index` and :meth:`find`.
2386
2387
2388 .. method:: str.rjust(width, fillchar=' ', /)
2389
2390 Return the string right justified in a string of length *width*. Padding is
2391 done using the specified *fillchar* (default is an ASCII space). The
2392 original string is returned if *width* is less than or equal to ``len(s)``.
2393
2394 For example:
2395
2396 .. doctest::
2397
2398 >>> 'Python'.rjust(10)
2399 ' Python'
2400 >>> 'Python'.rjust(10, '.')
2401 '....Python'
2402 >>> 'Monty Python'.rjust(10, '.')
2403 'Monty Python'
2404
2405 See also :meth:`ljust` and :meth:`zfill`.
2406
2407
2408 .. method:: str.rpartition(sep, /)
2409
2410 Split the string at the last occurrence of *sep*, and return a 3-tuple
2411 containing the part before the separator, the separator itself, and the part
2412 after the separator. If the separator is not found, return a 3-tuple containing
2413 two empty strings, followed by the string itself.
2414
2415 For example:
2416
2417 .. doctest::
2418
2419 >>> 'Monty Python'.rpartition(' ')
2420 ('Monty', ' ', 'Python')
2421 >>> "Monty Python's Flying Circus".rpartition(' ')
2422 ("Monty Python's Flying", ' ', 'Circus')
2423 >>> 'Monty Python'.rpartition('-')
2424 ('', '', 'Monty Python')
2425
2426 See also :meth:`partition`.
2427
2428
2429 .. method:: str.rsplit(sep=None, maxsplit=-1)
2430
2431 Return a list of the words in the string, using *sep* as the delimiter string.
2432 If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost*
2433 ones. If *sep* is not specified or ``None``, any whitespace string is a
2434 separator. Except for splitting from the right, :meth:`rsplit` behaves like
2435 :meth:`split` which is described in detail below.
2436
2437
2438 .. method:: str.rstrip(chars=None, /)
2439
2440 Return a copy of the string with trailing characters removed. The *chars*
2441 argument is a string specifying the set of characters to be removed. If omitted
2442 or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
2443 argument is not a suffix; rather, all combinations of its values are stripped.
2444 For example:
2445
2446 .. doctest::
2447
2448 >>> ' spacious '.rstrip()
2449 ' spacious'
2450 >>> 'mississippi'.rstrip('ipz')
2451 'mississ'
2452
2453 See :meth:`removesuffix` for a method that will remove a single suffix
2454 string rather than all of a set of characters. For example::
2455
2456 >>> 'Monty Python'.rstrip(' Python')
2457 'M'
2458 >>> 'Monty Python'.removesuffix(' Python')
2459 'Monty'
2460
2461 See also :meth:`strip`.
2462
2463
2464 .. method:: str.split(sep=None, maxsplit=-1)
2465
2466 Return a list of the words in the string, using *sep* as the delimiter
2467 string. If *maxsplit* is given, at most *maxsplit* splits are done (thus,
2468 the list will have at most ``maxsplit+1`` elements). If *maxsplit* is not
2469 specified or ``-1``, then there is no limit on the number of splits
2470 (all possible splits are made).
2471
2472 If *sep* is given, consecutive delimiters are not grouped together and are
2473 deemed to delimit empty strings (for example, ``'1,,2'.split(',')`` returns
2474 ``['1', '', '2']``). The *sep* argument may consist of multiple characters
2475 as a single delimiter (to split with multiple delimiters, use
2476 :func:`re.split`). Splitting an empty string with a specified separator
2477 returns ``['']``.
2478
2479 For example:
2480
2481 .. doctest::
2482
2483 >>> '1,2,3'.split(',')
2484 ['1', '2', '3']
2485 >>> '1,2,3'.split(',', maxsplit=1)
2486 ['1', '2,3']
2487 >>> '1,2,,3,'.split(',')
2488 ['1', '2', '', '3', '']
2489 >>> '1<>2<>3<4'.split('<>')
2490 ['1', '2', '3<4']
2491
2492 If *sep* is not specified or is ``None``, a different splitting algorithm is
2493 applied: runs of consecutive whitespace are regarded as a single separator,
2494 and the result will contain no empty strings at the start or end if the
2495 string has leading or trailing whitespace. Consequently, splitting an empty
2496 string or a string consisting of just whitespace with a ``None`` separator
2497 returns ``[]``.
2498
2499 For example:
2500
2501 .. doctest::
2502
2503 >>> '1 2 3'.split()
2504 ['1', '2', '3']
2505 >>> '1 2 3'.split(maxsplit=1)
2506 ['1', '2 3']
2507 >>> ' 1 2 3 '.split()
2508 ['1', '2', '3']
2509
2510 If *sep* is not specified or is ``None`` and *maxsplit* is ``0``, only
2511 leading runs of consecutive whitespace are considered.
2512
2513 For example:
2514
2515 .. doctest::
2516
2517 >>> "".split(None, 0)
2518 []
2519 >>> " ".split(None, 0)
2520 []
2521 >>> " foo ".split(maxsplit=0)
2522 ['foo ']
2523
2524 See also :meth:`join` and :meth:`rsplit`.
2525
2526
2527 .. index::
2528 single: universal newlines; str.splitlines method
2529
2530 .. method:: str.splitlines(keepends=False)
2531
2532 Return a list of the lines in the string, breaking at line boundaries. Line
2533 breaks are not included in the resulting list unless *keepends* is given and
2534 true.
2535
2536 This method splits on the following line boundaries. In particular, the
2537 boundaries are a superset of :term:`universal newlines`.
2538
2539 +-----------------------+-----------------------------+
2540 | Representation | Description |
2541 +=======================+=============================+
2542 | ``\n`` | Line Feed |
2543 +-----------------------+-----------------------------+
2544 | ``\r`` | Carriage Return |
2545 +-----------------------+-----------------------------+
2546 | ``\r\n`` | Carriage Return + Line Feed |
2547 +-----------------------+-----------------------------+
2548 | ``\v`` or ``\x0b`` | Line Tabulation |
2549 +-----------------------+-----------------------------+
2550 | ``\f`` or ``\x0c`` | Form Feed |
2551 +-----------------------+-----------------------------+
2552 | ``\x1c`` | File Separator |
2553 +-----------------------+-----------------------------+
2554 | ``\x1d`` | Group Separator |
2555 +-----------------------+-----------------------------+
2556 | ``\x1e`` | Record Separator |
2557 +-----------------------+-----------------------------+
2558 | ``\x85`` | Next Line (C1 Control Code) |
2559 +-----------------------+-----------------------------+
2560 | ``\u2028`` | Line Separator |
2561 +-----------------------+-----------------------------+
2562 | ``\u2029`` | Paragraph Separator |
2563 +-----------------------+-----------------------------+
2564
2565 .. versionchanged:: 3.2
2566
2567 ``\v`` and ``\f`` added to list of line boundaries.
2568
2569 For example::
2570
2571 >>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
2572 ['ab c', '', 'de fg', 'kl']
2573 >>> 'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
2574 ['ab c\n', '\n', 'de fg\r', 'kl\r\n']
2575
2576 Unlike :meth:`~str.split` when a delimiter string *sep* is given, this
2577 method returns an empty list for the empty string, and a terminal line
2578 break does not result in an extra line::
2579
2580 >>> "".splitlines()
2581 []
2582 >>> "One line\n".splitlines()
2583 ['One line']
2584
2585 For comparison, ``split('\n')`` gives::
2586
2587 >>> ''.split('\n')
2588 ['']
2589 >>> 'Two lines\n'.split('\n')
2590 ['Two lines', '']
2591
2592
2593 .. method:: str.startswith(prefix[, start[, end]])
2594
2595 Return ``True`` if string starts with the *prefix*, otherwise return ``False``.
2596 *prefix* can also be a tuple of prefixes to look for. With optional *start*,
2597 test string beginning at that position. With optional *end*, stop comparing
2598 string at that position.
2599
2600 For example:
2601
2602 .. doctest::
2603
2604 >>> 'Python'.startswith('Py')
2605 True
2606 >>> 'a tuple of prefixes'.startswith(('at', 'a'))
2607 True
2608 >>> 'Python is amazing'.startswith('is', 7)
2609 True
2610
2611 See also :meth:`endswith` and :meth:`removeprefix`.
2612
2613
2614 .. method:: str.strip(chars=None, /)
2615
2616 Return a copy of the string with the leading and trailing characters removed.
2617 The *chars* argument is a string specifying the set of characters to be removed.
2618 If omitted or ``None``, the *chars* argument defaults to removing whitespace.
2619 The *chars* argument is not a prefix or suffix; rather, all combinations of its
2620 values are stripped.
2621
2622 Whitespace characters are defined by :meth:`str.isspace`.
2623
2624 For example:
2625
2626 .. doctest::
2627
2628 >>> ' spacious '.strip()
2629 'spacious'
2630 >>> 'www.example.com'.strip('cmowz.')
2631 'example'
2632
2633 The outermost leading and trailing *chars* argument values are stripped
2634 from the string. Characters are removed from the leading end until
2635 reaching a string character that is not contained in the set of
2636 characters in *chars*. A similar action takes place on the trailing end.
2637
2638 For example:
2639
2640 .. doctest::
2641
2642 >>> comment_string = '#....... Section 3.2.1 Issue #32 .......'
2643 >>> comment_string.strip('.#! ')
2644 'Section 3.2.1 Issue #32'
2645
2646 See also :meth:`rstrip`.
2647
2648
2649 .. method:: str.swapcase()
2650
2651 Return a copy of the string with uppercase characters converted to lowercase and
2652 vice versa. For example:
2653
2654 .. doctest::
2655
2656 >>> 'Hello World'.swapcase()
2657 'hELLO wORLD'
2658
2659 Note that it is not necessarily true that ``s.swapcase().swapcase() == s``.
2660 For example:
2661
2662 .. doctest::
2663
2664 >>> 'straße'.swapcase().swapcase()
2665 'strasse'
2666
2667 See also :meth:`str.lower` and :meth:`str.upper`.
2668
2669
2670 .. method:: str.title()
2671
2672 Return a titlecased version of the string where words start with an uppercase
2673 character and the remaining characters are lowercase.
2674
2675 For example::
2676
2677 >>> 'Hello world'.title()
2678 'Hello World'
2679
2680 The algorithm uses a simple language-independent definition of a word as
2681 groups of consecutive letters. The definition works in many contexts but
2682 it means that apostrophes in contractions and possessives form word
2683 boundaries, which may not be the desired result::
2684
2685 >>> "they're bill's friends from the UK".title()
2686 "They'Re Bill'S Friends From The Uk"
2687
2688 The :func:`string.capwords` function does not have this problem, as it
2689 splits words on spaces only.
2690
2691 Alternatively, a workaround for apostrophes can be constructed using regular
2692 expressions::
2693
2694 >>> import re
2695 >>> def titlecase(s):
2696 ... return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
2697 ... lambda mo: mo.group(0).capitalize(),
2698 ... s)
2699 ...
2700 >>> titlecase("they're bill's friends.")
2701 "They're Bill's Friends."
2702
2703 See also :meth:`istitle`.
2704
2705
2706 .. method:: str.translate(table, /)
2707
2708 Return a copy of the string in which each character has been mapped through
2709 the given translation table. The table must be an object that implements
2710 indexing via :meth:`~object.__getitem__`, typically a :term:`mapping` or
2711 :term:`sequence`. When indexed by a Unicode ordinal (an integer), the
2712 table object can do any of the following: return a Unicode ordinal or a
2713 string, to map the character to one or more other characters; return
2714 ``None``, to delete the character from the return string; or raise a
2715 :exc:`LookupError` exception, to map the character to itself.
2716
2717 You can use :meth:`str.maketrans` to create a translation map from
2718 character-to-character mappings in different formats.
2719
2720 See also the :mod:`codecs` module for a more flexible approach to custom
2721 character mappings.
2722
2723
2724 .. method:: str.upper()
2725
2726 Return a copy of the string with all the cased characters [4]_ converted to
2727 uppercase. Note that ``s.upper().isupper()`` might be ``False`` if ``s``
2728 contains uncased characters or if the Unicode category of the resulting
2729 character(s) is not "Lu" (Letter, uppercase), but e.g. "Lt" (Letter,
2730 titlecase).
2731
2732 The uppercasing algorithm used is
2733 `described in section 3.13 'Default Case Folding' of the Unicode Standard
2734 <https://www.unicode.org/versions/Unicode15.1.0/ch03.pdf>`__.
2735
2736
2737 .. method:: str.zfill(width, /)
2738
2739 Return a copy of the string left filled with ASCII ``'0'`` digits to
2740 make a string of length *width*. A leading sign prefix (``'+'``/``'-'``)
2741 is handled by inserting the padding *after* the sign character rather
2742 than before. The original string is returned if *width* is less than
2743 or equal to ``len(s)``.
2744
2745 For example:
2746
2747 .. doctest::
2748
2749 >>> "42".zfill(5)
2750 '00042'
2751 >>> "-42".zfill(5)
2752 '-0042'
2753
2754 See also :meth:`rjust`.
2755
2756
2757 .. index::
2758 single: ! formatted string literal
2759 single: formatted string literals
2760 single: ! f-string
2761 single: f-strings
2762 single: fstring
2763 single: interpolated string literal
2764 single: string; formatted literal
2765 single: string; interpolated literal
2766 single: {} (curly brackets); in formatted string literal
2767 single: ! (exclamation mark); in formatted string literal
2768 single: : (colon); in formatted string literal
2769 single: = (equals); for help in debugging using string literals
2770
2771 Formatted String Literals (f-strings)
2772 -------------------------------------
2773
2774 .. versionadded:: 3.6
2775 .. versionchanged:: 3.7
2776 The :keyword:`await` and :keyword:`async for` can be used in expressions
2777 within f-strings.
2778 .. versionchanged:: 3.8
2779 Added the debugging operator (``=``)
2780 .. versionchanged:: 3.12
2781 Many restrictions on expressions within f-strings have been removed.
2782 Notably, nested strings, comments, and backslashes are now permitted.
2783
2784 An :dfn:`f-string` (formally a :dfn:`formatted string literal`) is
2785 a string literal that is prefixed with ``f`` or ``F``.
2786 This type of string literal allows embedding arbitrary Python expressions
2787 within *replacement fields*, which are delimited by curly brackets (``{}``).
2788 These expressions are evaluated at runtime, similarly to :meth:`str.format`,
2789 and are converted into regular :class:`str` objects.
2790 For example:
2791
2792 .. doctest::
2793
2794 >>> who = 'nobody'
2795 >>> nationality = 'Spanish'
2796 >>> f'{who.title()} expects the {nationality} Inquisition!'
2797 'Nobody expects the Spanish Inquisition!'
2798
2799 It is also possible to use a multi line f-string:
2800
2801 .. doctest::
2802
2803 >>> f'''This is a string
2804 ... on two lines'''
2805 'This is a string\non two lines'
2806
2807 A single opening curly bracket, ``'{'``, marks a *replacement field* that
2808 can contain any Python expression:
2809
2810 .. doctest::
2811
2812 >>> nationality = 'Spanish'
2813 >>> f'The {nationality} Inquisition!'
2814 'The Spanish Inquisition!'
2815
2816 To include a literal ``{`` or ``}``, use a double bracket:
2817
2818 .. doctest::
2819
2820 >>> x = 42
2821 >>> f'{{x}} is {x}'
2822 '{x} is 42'
2823
2824 Functions can also be used, and :ref:`format specifiers <formatstrings>`:
2825
2826 .. doctest::
2827
2828 >>> from math import sqrt
2829 >>> f'√2 \N{ALMOST EQUAL TO} {sqrt(2):.5f}'
2830 '√2 ≈ 1.41421'
2831
2832 Any non-string expression is converted using :func:`str`, by default:
2833
2834 .. doctest::
2835
2836 >>> from fractions import Fraction
2837 >>> f'{Fraction(1, 3)}'
2838 '1/3'
2839
2840 To use an explicit conversion, use the ``!`` (exclamation mark) operator,
2841 followed by any of the valid formats, which are:
2842
2843 ========== ==============
2844 Conversion Meaning
2845 ========== ==============
2846 ``!a`` :func:`ascii`
2847 ``!r`` :func:`repr`
2848 ``!s`` :func:`str`
2849 ========== ==============
2850
2851 For example:
2852
2853 .. doctest::
2854
2855 >>> from fractions import Fraction
2856 >>> f'{Fraction(1, 3)!s}'
2857 '1/3'
2858 >>> f'{Fraction(1, 3)!r}'
2859 'Fraction(1, 3)'
2860 >>> question = '¿Dónde está el Presidente?'
2861 >>> print(f'{question!a}')
2862 '\xbfD\xf3nde est\xe1 el Presidente?'
2863
2864 While debugging it may be helpful to see both the expression and its value,
2865 by using the equals sign (``=``) after the expression.
2866 This preserves spaces within the brackets, and can be used with a converter.
2867 By default, the debugging operator uses the :func:`repr` (``!r``) conversion.
2868 For example:
2869
2870 .. doctest::
2871
2872 >>> from fractions import Fraction
2873 >>> calculation = Fraction(1, 3)
2874 >>> f'{calculation=}'
2875 'calculation=Fraction(1, 3)'
2876 >>> f'{calculation = }'
2877 'calculation = Fraction(1, 3)'
2878 >>> f'{calculation = !s}'
2879 'calculation = 1/3'
2880
2881 Once the output has been evaluated, it can be formatted using a
2882 :ref:`format specifier <formatstrings>` following a colon (``':'``).
2883 After the expression has been evaluated, and possibly converted to a string,
2884 the :meth:`!__format__` method of the result is called with the format specifier,
2885 or the empty string if no format specifier is given.
2886 The formatted result is then used as the final value for the replacement field.
2887 For example:
2888
2889 .. doctest::
2890
2891 >>> from fractions import Fraction
2892 >>> f'{Fraction(1, 7):.6f}'
2893 '0.142857'
2894 >>> f'{Fraction(1, 7):_^+10}'
2895 '___+1/7___'
2896
2897
2898 .. _old-string-formatting:
2899
2900 ``printf``-style String Formatting
2901 ----------------------------------
2902
2903 .. index::
2904 single: formatting, string (%)
2905 single: interpolation, string (%)
2906 single: string; formatting, printf
2907 single: string; interpolation, printf
2908 single: printf-style formatting
2909 single: sprintf-style formatting
2910 single: % (percent); printf-style formatting
2911
2912 .. note::
2913
2914 The formatting operations described here exhibit a variety of quirks that
2915 lead to a number of common errors (such as failing to display tuples and
2916 dictionaries correctly). Using the newer :ref:`formatted string literals
2917 <f-strings>`, the :meth:`str.format` interface, or :ref:`template strings
2918 <template-strings>` may help avoid these errors. Each of these
2919 alternatives provides their own trade-offs and benefits of simplicity,
2920 flexibility, and/or extensibility.
2921
2922 String objects have one unique built-in operation: the ``%`` operator (modulo).
2923 This is also known as the string *formatting* or *interpolation* operator.
2924 Given ``format % values`` (where *format* is a string), ``%`` conversion
2925 specifications in *format* are replaced with zero or more elements of *values*.
2926 The effect is similar to using the :c:func:`sprintf` function in the C language.
2927 For example:
2928
2929 .. doctest::
2930
2931 >>> print('%s has %d quote types.' % ('Python', 2))
2932 Python has 2 quote types.
2933
2934 If *format* requires a single argument, *values* may be a single non-tuple
2935 object. [5]_ Otherwise, *values* must be a tuple with exactly the number of
2936 items specified by the format string, or a single mapping object (for example, a
2937 dictionary).
2938
2939 .. index::
2940 single: () (parentheses); in printf-style formatting
2941 single: * (asterisk); in printf-style formatting
2942 single: . (dot); in printf-style formatting
2943
2944 A conversion specifier contains two or more characters and has the following
2945 components, which must occur in this order:
2946
2947 #. The ``'%'`` character, which marks the start of the specifier.
2948
2949 #. Mapping key (optional), consisting of a parenthesised sequence of characters
2950 (for example, ``(somename)``).
2951
2952 #. Conversion flags (optional), which affect the result of some conversion
2953 types.
2954
2955 #. Minimum field width (optional). If specified as an ``'*'`` (asterisk), the
2956 actual width is read from the next element of the tuple in *values*, and the
2957 object to convert comes after the minimum field width and optional precision.
2958
2959 #. Precision (optional), given as a ``'.'`` (dot) followed by the precision. If
2960 specified as ``'*'`` (an asterisk), the actual precision is read from the next
2961 element of the tuple in *values*, and the value to convert comes after the
2962 precision.
2963
2964 #. Length modifier (optional).
2965
2966 #. Conversion type.
2967
2968 When the right argument is a dictionary (or other mapping type), then the
2969 formats in the string *must* include a parenthesised mapping key into that
2970 dictionary inserted immediately after the ``'%'`` character. The mapping key
2971 selects the value to be formatted from the mapping. For example:
2972
2973 >>> print('%(language)s has %(number)03d quote types.' %
2974 ... {'language': "Python", "number": 2})
2975 Python has 002 quote types.
2976
2977 In this case no ``*`` specifiers may occur in a format (since they require a
2978 sequential parameter list).
2979
2980 The conversion flag characters are:
2981
2982 .. index::
2983 single: # (hash); in printf-style formatting
2984 single: - (minus); in printf-style formatting
2985 single: + (plus); in printf-style formatting
2986 single: space; in printf-style formatting
2987
2988 +---------+---------------------------------------------------------------------+
2989 | Flag | Meaning |
2990 +=========+=====================================================================+
2991 | ``'#'`` | The value conversion will use the "alternate form" (where defined |
2992 | | below). |
2993 +---------+---------------------------------------------------------------------+
2994 | ``'0'`` | The conversion will be zero padded for numeric values. |
2995 +---------+---------------------------------------------------------------------+
2996 | ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` |
2997 | | conversion if both are given). |
2998 +---------+---------------------------------------------------------------------+
2999 | ``' '`` | (a space) A blank should be left before a positive number (or empty |
3000 | | string) produced by a signed conversion. |
3001 +---------+---------------------------------------------------------------------+
3002 | ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion |
3003 | | (overrides a "space" flag). |
3004 +---------+---------------------------------------------------------------------+
3005
3006 A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it
3007 is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``.
3008
3009 The conversion types are:
3010
3011 +------------+-----------------------------------------------------+-------+
3012 | Conversion | Meaning | Notes |
3013 +============+=====================================================+=======+
3014 | ``'d'`` | Signed integer decimal. | |
3015 +------------+-----------------------------------------------------+-------+
3016 | ``'i'`` | Signed integer decimal. | |
3017 +------------+-----------------------------------------------------+-------+
3018 | ``'o'`` | Signed octal value. | \(1) |
3019 +------------+-----------------------------------------------------+-------+
3020 | ``'u'`` | Obsolete type -- it is identical to ``'d'``. | \(6) |
3021 +------------+-----------------------------------------------------+-------+
3022 | ``'x'`` | Signed hexadecimal (lowercase). | \(2) |
3023 +------------+-----------------------------------------------------+-------+
3024 | ``'X'`` | Signed hexadecimal (uppercase). | \(2) |
3025 +------------+-----------------------------------------------------+-------+
3026 | ``'e'`` | Floating-point exponential format (lowercase). | \(3) |
3027 +------------+-----------------------------------------------------+-------+
3028 | ``'E'`` | Floating-point exponential format (uppercase). | \(3) |
3029 +------------+-----------------------------------------------------+-------+
3030 | ``'f'`` | Floating-point decimal format. | \(3) |
3031 +------------+-----------------------------------------------------+-------+
3032 | ``'F'`` | Floating-point decimal format. | \(3) |
3033 +------------+-----------------------------------------------------+-------+
3034 | ``'g'`` | Floating-point format. Uses lowercase exponential | \(4) |
3035 | | format if exponent is less than -4 or not less than | |
3036 | | precision, decimal format otherwise. | |
3037 +------------+-----------------------------------------------------+-------+
3038 | ``'G'`` | Floating-point format. Uses uppercase exponential | \(4) |
3039 | | format if exponent is less than -4 or not less than | |
3040 | | precision, decimal format otherwise. | |
3041 +------------+-----------------------------------------------------+-------+
3042 | ``'c'`` | Single character (accepts integer or single | |
3043 | | character string). | |
3044 +------------+-----------------------------------------------------+-------+
3045 | ``'r'`` | String (converts any Python object using | \(5) |
3046 | | :func:`repr`). | |
3047 +------------+-----------------------------------------------------+-------+
3048 | ``'s'`` | String (converts any Python object using | \(5) |
3049 | | :func:`str`). | |
3050 +------------+-----------------------------------------------------+-------+
3051 | ``'a'`` | String (converts any Python object using | \(5) |
3052 | | :func:`ascii`). | |
3053 +------------+-----------------------------------------------------+-------+
3054 | ``'%'`` | No argument is converted, results in a ``'%'`` | |
3055 | | character in the result. | |
3056 +------------+-----------------------------------------------------+-------+
3057
3058 For floating-point formats, the result should be correctly rounded to a given
3059 precision ``p`` of digits after the decimal point. The rounding mode matches
3060 that of the :func:`round` builtin.
3061
3062 Notes:
3063
3064 (1)
3065 The alternate form causes a leading octal specifier (``'0o'``) to be
3066 inserted before the first digit.
3067
3068 (2)
3069 The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether
3070 the ``'x'`` or ``'X'`` format was used) to be inserted before the first digit.
3071
3072 (3)
3073 The alternate form causes the result to always contain a decimal point, even if
3074 no digits follow it.
3075
3076 The precision determines the number of digits after the decimal point and
3077 defaults to 6.
3078
3079 (4)
3080 The alternate form causes the result to always contain a decimal point, and
3081 trailing zeroes are not removed as they would otherwise be.
3082
3083 The precision determines the number of significant digits before and after the
3084 decimal point and defaults to 6.
3085
3086 (5)
3087 If precision is ``N``, the output is truncated to ``N`` characters.
3088
3089 (6)
3090 See :pep:`237`.
3091
3092 Since Python strings have an explicit length, ``%s`` conversions do not assume
3093 that ``'\0'`` is the end of the string.
3094
3095 .. XXX Examples?
3096
3097 .. versionchanged:: 3.1
3098 ``%f`` conversions for numbers whose absolute value is over 1e50 are no
3099 longer replaced by ``%g`` conversions.
3100
3101
3102 .. index::
3103 single: buffer protocol; binary sequence types
3104
3105 .. _binaryseq:
3106
3107 Binary Sequence Types --- :class:`bytes`, :class:`bytearray`, :class:`memoryview`
3108 =================================================================================
3109
3110 .. index::
3111 pair: object; bytes
3112 pair: object; bytearray
3113 pair: object; memoryview
3114 pair: module; array
3115
3116 The core built-in types for manipulating binary data are :class:`bytes` and
3117 :class:`bytearray`. They are supported by :class:`memoryview` which uses
3118 the :ref:`buffer protocol <bufferobjects>` to access the memory of other
3119 binary objects without needing to make a copy.
3120
3121 The :mod:`array` module supports efficient storage of basic data types like
3122 32-bit integers and IEEE754 double-precision floating values.
3123
3124 .. _typebytes:
3125
3126 Bytes Objects
3127 -------------
3128
3129 .. index:: pair: object; bytes
3130
3131 Bytes objects are immutable sequences of single bytes. Since many major
3132 binary protocols are based on the ASCII text encoding, bytes objects offer
3133 several methods that are only valid when working with ASCII compatible
3134 data and are closely related to string objects in a variety of other ways.
3135
3136 .. class:: bytes(source=b'')
3137 bytes(source, encoding, errors='strict')
3138
3139 Firstly, the syntax for bytes literals is largely the same as that for string
3140 literals, except that a ``b`` prefix is added:
3141
3142 * Single quotes: ``b'still allows embedded "double" quotes'``
3143 * Double quotes: ``b"still allows embedded 'single' quotes"``
3144 * Triple quoted: ``b'''3 single quotes'''``, ``b"""3 double quotes"""``
3145
3146 Only ASCII characters are permitted in bytes literals (regardless of the
3147 declared source code encoding). Any binary values over 127 must be entered
3148 into bytes literals using the appropriate escape sequence.
3149
3150 As with string literals, bytes literals may also use a ``r`` prefix to disable
3151 processing of escape sequences. See :ref:`strings` for more about the various
3152 forms of bytes literal, including supported escape sequences.
3153
3154 While bytes literals and representations are based on ASCII text, bytes
3155 objects actually behave like immutable sequences of integers, with each
3156 value in the sequence restricted such that ``0 <= x < 256`` (attempts to
3157 violate this restriction will trigger :exc:`ValueError`). This is done
3158 deliberately to emphasise that while many binary formats include ASCII based
3159 elements and can be usefully manipulated with some text-oriented algorithms,
3160 this is not generally the case for arbitrary binary data (blindly applying
3161 text processing algorithms to binary data formats that are not ASCII
3162 compatible will usually lead to data corruption).
3163
3164 In addition to the literal forms, bytes objects can be created in a number of
3165 other ways:
3166
3167 * A zero-filled bytes object of a specified length: ``bytes(10)``
3168 * From an iterable of integers: ``bytes(range(20))``
3169 * Copying existing binary data via the buffer protocol: ``bytes(obj)``
3170
3171 Also see the :ref:`bytes <func-bytes>` built-in.
3172
3173 Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal
3174 numbers are a commonly used format for describing binary data. Accordingly,
3175 the bytes type has an additional class method to read data in that format:
3176
3177 .. classmethod:: fromhex(string, /)
3178
3179 This :class:`bytes` class method returns a bytes object, decoding the
3180 given string object. The string must contain two hexadecimal digits per
3181 byte, with ASCII whitespace being ignored.
3182
3183 >>> bytes.fromhex('2Ef0 F1f2 ')
3184 b'.\xf0\xf1\xf2'
3185
3186 .. versionchanged:: 3.7
3187 :meth:`bytes.fromhex` now skips all ASCII whitespace in the string,
3188 not just spaces.
3189
3190 A reverse conversion function exists to transform a bytes object into its
3191 hexadecimal representation.
3192
3193 .. method:: hex(*, bytes_per_sep=1)
3194 hex(sep, bytes_per_sep=1)
3195
3196 Return a string object containing two hexadecimal digits for each
3197 byte in the instance.
3198
3199 >>> b'\xf0\xf1\xf2'.hex()
3200 'f0f1f2'
3201
3202 If you want to make the hex string easier to read, you can specify a
3203 single character separator *sep* parameter to include in the output.
3204 By default, this separator will be included between each byte.
3205 A second optional *bytes_per_sep* parameter controls the spacing.
3206 Positive values calculate the separator position from the right,
3207 negative values from the left.
3208
3209 >>> value = b'\xf0\xf1\xf2'
3210 >>> value.hex('-')
3211 'f0-f1-f2'
3212 >>> value.hex('_', 2)
3213 'f0_f1f2'
3214 >>> b'UUDDLRLRAB'.hex(' ', -4)
3215 '55554444 4c524c52 4142'
3216
3217 .. versionadded:: 3.5
3218
3219 .. versionchanged:: 3.8
3220 :meth:`bytes.hex` now supports optional *sep* and *bytes_per_sep*
3221 parameters to insert separators between bytes in the hex output.
3222
3223 Since bytes objects are sequences of integers (akin to a tuple), for a bytes
3224 object *b*, ``b[0]`` will be an integer, while ``b[0:1]`` will be a bytes
3225 object of length 1. (This contrasts with text strings, where both indexing
3226 and slicing will produce a string of length 1)
3227
3228 The representation of bytes objects uses the literal format (``b'...'``)
3229 since it is often more useful than e.g. ``bytes([46, 46, 46])``. You can
3230 always convert a bytes object into a list of integers using ``list(b)``.
3231
3232
3233 .. _typebytearray:
3234
3235 Bytearray Objects
3236 -----------------
3237
3238 .. index:: pair: object; bytearray
3239
3240 :class:`bytearray` objects are a mutable counterpart to :class:`bytes`
3241 objects.
3242
3243 .. class:: bytearray(source=b'')
3244 bytearray(source, encoding, errors='strict')
3245
3246 There is no dedicated literal syntax for bytearray objects, instead
3247 they are always created by calling the constructor:
3248
3249 * Creating an empty instance: ``bytearray()``
3250 * Creating a zero-filled instance with a given length: ``bytearray(10)``
3251 * From an iterable of integers: ``bytearray(range(20))``
3252 * Copying existing binary data via the buffer protocol: ``bytearray(b'Hi!')``
3253
3254 As bytearray objects are mutable, they support the
3255 :ref:`mutable <typesseq-mutable>` sequence operations in addition to the
3256 common bytes and bytearray operations described in :ref:`bytes-methods`.
3257
3258 Also see the :ref:`bytearray <func-bytearray>` built-in.
3259
3260 Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal
3261 numbers are a commonly used format for describing binary data. Accordingly,
3262 the bytearray type has an additional class method to read data in that format:
3263
3264 .. classmethod:: fromhex(string, /)
3265
3266 This :class:`bytearray` class method returns bytearray object, decoding
3267 the given string object. The string must contain two hexadecimal digits
3268 per byte, with ASCII whitespace being ignored.
3269
3270 >>> bytearray.fromhex('2Ef0 F1f2 ')
3271 bytearray(b'.\xf0\xf1\xf2')
3272
3273 .. versionchanged:: 3.7
3274 :meth:`bytearray.fromhex` now skips all ASCII whitespace in the string,
3275 not just spaces.
3276
3277 A reverse conversion function exists to transform a bytearray object into its
3278 hexadecimal representation.
3279
3280 .. method:: hex(*, bytes_per_sep=1)
3281 hex(sep, bytes_per_sep=1)
3282
3283 Return a string object containing two hexadecimal digits for each
3284 byte in the instance.
3285
3286 >>> bytearray(b'\xf0\xf1\xf2').hex()
3287 'f0f1f2'
3288
3289 .. versionadded:: 3.5
3290
3291 .. versionchanged:: 3.8
3292 Similar to :meth:`bytes.hex`, :meth:`bytearray.hex` now supports
3293 optional *sep* and *bytes_per_sep* parameters to insert separators
3294 between bytes in the hex output.
3295
3296 Since bytearray objects are sequences of integers (akin to a list), for a
3297 bytearray object *b*, ``b[0]`` will be an integer, while ``b[0:1]`` will be
3298 a bytearray object of length 1. (This contrasts with text strings, where
3299 both indexing and slicing will produce a string of length 1)
3300
3301 The representation of bytearray objects uses the bytes literal format
3302 (``bytearray(b'...')``) since it is often more useful than e.g.
3303 ``bytearray([46, 46, 46])``. You can always convert a bytearray object into
3304 a list of integers using ``list(b)``.
3305
3306
3307 .. _bytes-methods:
3308
3309 Bytes and Bytearray Operations
3310 ------------------------------
3311
3312 .. index:: pair: bytes; methods
3313 pair: bytearray; methods
3314
3315 Both bytes and bytearray objects support the :ref:`common <typesseq-common>`
3316 sequence operations. They interoperate not just with operands of the same
3317 type, but with any :term:`bytes-like object`. Due to this flexibility, they can be
3318 freely mixed in operations without causing errors. However, the return type
3319 of the result may depend on the order of operands.
3320
3321 .. note::
3322
3323 The methods on bytes and bytearray objects don't accept strings as their
3324 arguments, just as the methods on strings don't accept bytes as their
3325 arguments. For example, you have to write::
3326
3327 a = "abc"
3328 b = a.replace("a", "f")
3329
3330 and::
3331
3332 a = b"abc"
3333 b = a.replace(b"a", b"f")
3334
3335 Some bytes and bytearray operations assume the use of ASCII compatible
3336 binary formats, and hence should be avoided when working with arbitrary
3337 binary data. These restrictions are covered below.
3338
3339 .. note::
3340 Using these ASCII based operations to manipulate binary data that is not
3341 stored in an ASCII based format may lead to data corruption.
3342
3343 The following methods on bytes and bytearray objects can be used with
3344 arbitrary binary data.
3345
3346 .. method:: bytes.count(sub[, start[, end]])
3347 bytearray.count(sub[, start[, end]])
3348
3349 Return the number of non-overlapping occurrences of subsequence *sub* in
3350 the range [*start*, *end*]. Optional arguments *start* and *end* are
3351 interpreted as in slice notation.
3352
3353 The subsequence to search for may be any :term:`bytes-like object` or an
3354 integer in the range 0 to 255.
3355
3356 If *sub* is empty, returns the number of empty slices between characters
3357 which is the length of the bytes object plus one.
3358
3359 .. versionchanged:: 3.3
3360 Also accept an integer in the range 0 to 255 as the subsequence.
3361
3362
3363 .. method:: bytes.removeprefix(prefix, /)
3364 bytearray.removeprefix(prefix, /)
3365
3366 If the binary data starts with the *prefix* string, return
3367 ``bytes[len(prefix):]``. Otherwise, return a copy of the original
3368 binary data::
3369
3370 >>> b'TestHook'.removeprefix(b'Test')
3371 b'Hook'
3372 >>> b'BaseTestCase'.removeprefix(b'Test')
3373 b'BaseTestCase'
3374
3375 The *prefix* may be any :term:`bytes-like object`.
3376
3377 .. note::
3378
3379 The bytearray version of this method does *not* operate in place -
3380 it always produces a new object, even if no changes were made.
3381
3382 .. versionadded:: 3.9
3383
3384
3385 .. method:: bytes.removesuffix(suffix, /)
3386 bytearray.removesuffix(suffix, /)
3387
3388 If the binary data ends with the *suffix* string and that *suffix* is
3389 not empty, return ``bytes[:-len(suffix)]``. Otherwise, return a copy of
3390 the original binary data::
3391
3392 >>> b'MiscTests'.removesuffix(b'Tests')
3393 b'Misc'
3394 >>> b'TmpDirMixin'.removesuffix(b'Tests')
3395 b'TmpDirMixin'
3396
3397 The *suffix* may be any :term:`bytes-like object`.
3398
3399 .. note::
3400
3401 The bytearray version of this method does *not* operate in place -
3402 it always produces a new object, even if no changes were made.
3403
3404 .. versionadded:: 3.9
3405
3406
3407 .. method:: bytes.decode(encoding="utf-8", errors="strict")
3408 bytearray.decode(encoding="utf-8", errors="strict")
3409
3410 Return the bytes decoded to a :class:`str`.
3411
3412 *encoding* defaults to ``'utf-8'``;
3413 see :ref:`standard-encodings` for possible values.
3414
3415 *errors* controls how decoding errors are handled.
3416 If ``'strict'`` (the default), a :exc:`UnicodeError` exception is raised.
3417 Other possible values are ``'ignore'``, ``'replace'``,
3418 and any other name registered via :func:`codecs.register_error`.
3419 See :ref:`error-handlers` for details.
3420
3421 For performance reasons, the value of *errors* is not checked for validity
3422 unless a decoding error actually occurs,
3423 :ref:`devmode` is enabled or a :ref:`debug build <debug-build>` is used.
3424
3425 .. note::
3426
3427 Passing the *encoding* argument to :class:`str` allows decoding any
3428 :term:`bytes-like object` directly, without needing to make a temporary
3429 :class:`!bytes` or :class:`!bytearray` object.
3430
3431 .. versionchanged:: 3.1
3432 Added support for keyword arguments.
3433
3434 .. versionchanged:: 3.9
3435 The value of the *errors* argument is now checked in :ref:`devmode` and
3436 in :ref:`debug mode <debug-build>`.
3437
3438
3439 .. method:: bytes.endswith(suffix[, start[, end]])
3440 bytearray.endswith(suffix[, start[, end]])
3441
3442 Return ``True`` if the binary data ends with the specified *suffix*,
3443 otherwise return ``False``. *suffix* can also be a tuple of suffixes to
3444 look for. With optional *start*, test beginning at that position. With
3445 optional *end*, stop comparing at that position.
3446
3447 The suffix(es) to search for may be any :term:`bytes-like object`.
3448
3449
3450 .. method:: bytes.find(sub[, start[, end]])
3451 bytearray.find(sub[, start[, end]])
3452
3453 Return the lowest index in the data where the subsequence *sub* is found,
3454 such that *sub* is contained in the slice ``s[start:end]``. Optional
3455 arguments *start* and *end* are interpreted as in slice notation. Return
3456 ``-1`` if *sub* is not found.
3457
3458 The subsequence to search for may be any :term:`bytes-like object` or an
3459 integer in the range 0 to 255.
3460
3461 .. note::
3462
3463 The :meth:`~bytes.find` method should be used only if you need to know the
3464 position of *sub*. To check if *sub* is a substring or not, use the
3465 :keyword:`in` operator::
3466
3467 >>> b'Py' in b'Python'
3468 True
3469
3470 .. versionchanged:: 3.3
3471 Also accept an integer in the range 0 to 255 as the subsequence.
3472
3473
3474 .. method:: bytes.index(sub[, start[, end]])
3475 bytearray.index(sub[, start[, end]])
3476
3477 Like :meth:`~bytes.find`, but raise :exc:`ValueError` when the
3478 subsequence is not found.
3479
3480 The subsequence to search for may be any :term:`bytes-like object` or an
3481 integer in the range 0 to 255.
3482
3483 .. versionchanged:: 3.3
3484 Also accept an integer in the range 0 to 255 as the subsequence.
3485
3486
3487 .. method:: bytes.join(iterable, /)
3488 bytearray.join(iterable, /)
3489
3490 Return a bytes or bytearray object which is the concatenation of the
3491 binary data sequences in *iterable*. A :exc:`TypeError` will be raised
3492 if there are any values in *iterable* that are not :term:`bytes-like
3493 objects <bytes-like object>`, including :class:`str` objects. The
3494 separator between elements is the contents of the bytes or
3495 bytearray object providing this method.
3496
3497
3498 .. staticmethod:: bytes.maketrans(from, to, /)
3499 bytearray.maketrans(from, to, /)
3500
3501 This static method returns a translation table usable for
3502 :meth:`bytes.translate` that will map each character in *from* into the
3503 character at the same position in *to*; *from* and *to* must both be
3504 :term:`bytes-like objects <bytes-like object>` and have the same length.
3505
3506 .. versionadded:: 3.1
3507
3508
3509 .. method:: bytes.partition(sep, /)
3510 bytearray.partition(sep, /)
3511
3512 Split the sequence at the first occurrence of *sep*, and return a 3-tuple
3513 containing the part before the separator, the separator itself or its
3514 bytearray copy, and the part after the separator.
3515 If the separator is not found, return a 3-tuple
3516 containing a copy of the original sequence, followed by two empty bytes or
3517 bytearray objects.
3518
3519 The separator to search for may be any :term:`bytes-like object`.
3520
3521
3522 .. method:: bytes.replace(old, new, count=-1, /)
3523 bytearray.replace(old, new, count=-1, /)
3524
3525 Return a copy of the sequence with all occurrences of subsequence *old*
3526 replaced by *new*. If the optional argument *count* is given, only the
3527 first *count* occurrences are replaced.
3528
3529 The subsequence to search for and its replacement may be any
3530 :term:`bytes-like object`.
3531
3532 .. note::
3533
3534 The bytearray version of this method does *not* operate in place - it
3535 always produces a new object, even if no changes were made.
3536
3537
3538 .. method:: bytes.rfind(sub[, start[, end]])
3539 bytearray.rfind(sub[, start[, end]])
3540
3541 Return the highest index in the sequence where the subsequence *sub* is
3542 found, such that *sub* is contained within ``s[start:end]``. Optional
3543 arguments *start* and *end* are interpreted as in slice notation. Return
3544 ``-1`` on failure.
3545
3546 The subsequence to search for may be any :term:`bytes-like object` or an
3547 integer in the range 0 to 255.
3548
3549 .. versionchanged:: 3.3
3550 Also accept an integer in the range 0 to 255 as the subsequence.
3551
3552
3553 .. method:: bytes.rindex(sub[, start[, end]])
3554 bytearray.rindex(sub[, start[, end]])
3555
3556 Like :meth:`~bytes.rfind` but raises :exc:`ValueError` when the
3557 subsequence *sub* is not found.
3558
3559 The subsequence to search for may be any :term:`bytes-like object` or an
3560 integer in the range 0 to 255.
3561
3562 .. versionchanged:: 3.3
3563 Also accept an integer in the range 0 to 255 as the subsequence.
3564
3565
3566 .. method:: bytes.rpartition(sep, /)
3567 bytearray.rpartition(sep, /)
3568
3569 Split the sequence at the last occurrence of *sep*, and return a 3-tuple
3570 containing the part before the separator, the separator itself or its
3571 bytearray copy, and the part after the separator.
3572 If the separator is not found, return a 3-tuple
3573 containing two empty bytes or bytearray objects, followed by a copy of the
3574 original sequence.
3575
3576 The separator to search for may be any :term:`bytes-like object`.
3577
3578
3579 .. method:: bytes.startswith(prefix[, start[, end]])
3580 bytearray.startswith(prefix[, start[, end]])
3581
3582 Return ``True`` if the binary data starts with the specified *prefix*,
3583 otherwise return ``False``. *prefix* can also be a tuple of prefixes to
3584 look for. With optional *start*, test beginning at that position. With
3585 optional *end*, stop comparing at that position.
3586
3587 The prefix(es) to search for may be any :term:`bytes-like object`.
3588
3589
3590 .. method:: bytes.translate(table, /, delete=b'')
3591 bytearray.translate(table, /, delete=b'')
3592
3593 Return a copy of the bytes or bytearray object where all bytes occurring in
3594 the optional argument *delete* are removed, and the remaining bytes have
3595 been mapped through the given translation table, which must be a bytes
3596 object of length 256.
3597
3598 You can use the :func:`bytes.maketrans` method to create a translation
3599 table.
3600
3601 Set the *table* argument to ``None`` for translations that only delete
3602 characters::
3603
3604 >>> b'read this short text'.translate(None, b'aeiou')
3605 b'rd ths shrt txt'
3606
3607 .. versionchanged:: 3.6
3608 *delete* is now supported as a keyword argument.
3609
3610
3611 The following methods on bytes and bytearray objects have default behaviours
3612 that assume the use of ASCII compatible binary formats, but can still be used
3613 with arbitrary binary data by passing appropriate arguments. Note that all of
3614 the bytearray methods in this section do *not* operate in place, and instead
3615 produce new objects.
3616
3617 .. method:: bytes.center(width, fillbyte=b' ', /)
3618 bytearray.center(width, fillbyte=b' ', /)
3619
3620 Return a copy of the object centered in a sequence of length *width*.
3621 Padding is done using the specified *fillbyte* (default is an ASCII
3622 space). For :class:`bytes` objects, the original sequence is returned if
3623 *width* is less than or equal to ``len(s)``.
3624
3625 .. note::
3626
3627 The bytearray version of this method does *not* operate in place -
3628 it always produces a new object, even if no changes were made.
3629
3630
3631 .. method:: bytes.ljust(width, fillbyte=b' ', /)
3632 bytearray.ljust(width, fillbyte=b' ', /)
3633
3634 Return a copy of the object left justified in a sequence of length *width*.
3635 Padding is done using the specified *fillbyte* (default is an ASCII
3636 space). For :class:`bytes` objects, the original sequence is returned if
3637 *width* is less than or equal to ``len(s)``.
3638
3639 .. note::
3640
3641 The bytearray version of this method does *not* operate in place -
3642 it always produces a new object, even if no changes were made.
3643
3644
3645 .. method:: bytes.lstrip(bytes=None, /)
3646 bytearray.lstrip(bytes=None, /)
3647
3648 Return a copy of the sequence with specified leading bytes removed. The
3649 *bytes* argument is a binary sequence specifying the set of byte values to
3650 be removed. If omitted or ``None``, the *bytes* argument defaults
3651 to removing ASCII whitespace. The *bytes* argument is not a prefix;
3652 rather, all combinations of its values are stripped::
3653
3654 >>> b' spacious '.lstrip()
3655 b'spacious '
3656 >>> b'www.example.com'.lstrip(b'cmowz.')
3657 b'example.com'
3658
3659 The binary sequence of byte values to remove may be any
3660 :term:`bytes-like object`. See :meth:`~bytes.removeprefix` for a method
3661 that will remove a single prefix string rather than all of a set of
3662 characters. For example::
3663
3664 >>> b'Arthur: three!'.lstrip(b'Arthur: ')
3665 b'ee!'
3666 >>> b'Arthur: three!'.removeprefix(b'Arthur: ')
3667 b'three!'
3668
3669 .. note::
3670
3671 The bytearray version of this method does *not* operate in place -
3672 it always produces a new object, even if no changes were made.
3673
3674
3675 .. method:: bytes.rjust(width, fillbyte=b' ', /)
3676 bytearray.rjust(width, fillbyte=b' ', /)
3677
3678 Return a copy of the object right justified in a sequence of length *width*.
3679 Padding is done using the specified *fillbyte* (default is an ASCII
3680 space). For :class:`bytes` objects, the original sequence is returned if
3681 *width* is less than or equal to ``len(s)``.
3682
3683 .. note::
3684
3685 The bytearray version of this method does *not* operate in place -
3686 it always produces a new object, even if no changes were made.
3687
3688
3689 .. method:: bytes.rsplit(sep=None, maxsplit=-1)
3690 bytearray.rsplit(sep=None, maxsplit=-1)
3691
3692 Split the binary sequence into subsequences of the same type, using *sep*
3693 as the delimiter string. If *maxsplit* is given, at most *maxsplit* splits
3694 are done, the *rightmost* ones. If *sep* is not specified or ``None``,
3695 any subsequence consisting solely of ASCII whitespace is a separator.
3696 Except for splitting from the right, :meth:`rsplit` behaves like
3697 :meth:`split` which is described in detail below.
3698
3699
3700 .. method:: bytes.rstrip(bytes=None, /)
3701 bytearray.rstrip(bytes=None, /)
3702
3703 Return a copy of the sequence with specified trailing bytes removed. The
3704 *bytes* argument is a binary sequence specifying the set of byte values to
3705 be removed. If omitted or ``None``, the *bytes* argument defaults to
3706 removing ASCII whitespace. The *bytes* argument is not a suffix; rather,
3707 all combinations of its values are stripped::
3708
3709 >>> b' spacious '.rstrip()
3710 b' spacious'
3711 >>> b'mississippi'.rstrip(b'ipz')
3712 b'mississ'
3713
3714 The binary sequence of byte values to remove may be any
3715 :term:`bytes-like object`. See :meth:`~bytes.removesuffix` for a method
3716 that will remove a single suffix string rather than all of a set of
3717 characters. For example::
3718
3719 >>> b'Monty Python'.rstrip(b' Python')
3720 b'M'
3721 >>> b'Monty Python'.removesuffix(b' Python')
3722 b'Monty'
3723
3724 .. note::
3725
3726 The bytearray version of this method does *not* operate in place -
3727 it always produces a new object, even if no changes were made.
3728
3729
3730 .. method:: bytes.split(sep=None, maxsplit=-1)
3731 bytearray.split(sep=None, maxsplit=-1)
3732
3733 Split the binary sequence into subsequences of the same type, using *sep*
3734 as the delimiter string. If *maxsplit* is given and non-negative, at most
3735 *maxsplit* splits are done (thus, the list will have at most ``maxsplit+1``
3736 elements). If *maxsplit* is not specified or is ``-1``, then there is no
3737 limit on the number of splits (all possible splits are made).
3738
3739 If *sep* is given, consecutive delimiters are not grouped together and are
3740 deemed to delimit empty subsequences (for example, ``b'1,,2'.split(b',')``
3741 returns ``[b'1', b'', b'2']``). The *sep* argument may consist of a
3742 multibyte sequence as a single delimiter. Splitting an empty sequence with
3743 a specified separator returns ``[b'']`` or ``[bytearray(b'')]`` depending
3744 on the type of object being split. The *sep* argument may be any
3745 :term:`bytes-like object`.
3746
3747 For example::
3748
3749 >>> b'1,2,3'.split(b',')
3750 [b'1', b'2', b'3']
3751 >>> b'1,2,3'.split(b',', maxsplit=1)
3752 [b'1', b'2,3']
3753 >>> b'1,2,,3,'.split(b',')
3754 [b'1', b'2', b'', b'3', b'']
3755 >>> b'1<>2<>3<4'.split(b'<>')
3756 [b'1', b'2', b'3<4']
3757
3758 If *sep* is not specified or is ``None``, a different splitting algorithm
3759 is applied: runs of consecutive ASCII whitespace are regarded as a single
3760 separator, and the result will contain no empty strings at the start or
3761 end if the sequence has leading or trailing whitespace. Consequently,
3762 splitting an empty sequence or a sequence consisting solely of ASCII
3763 whitespace without a specified separator returns ``[]``.
3764
3765 For example::
3766
3767
3768 >>> b'1 2 3'.split()
3769 [b'1', b'2', b'3']
3770 >>> b'1 2 3'.split(maxsplit=1)
3771 [b'1', b'2 3']
3772 >>> b' 1 2 3 '.split()
3773 [b'1', b'2', b'3']
3774
3775
3776 .. method:: bytes.strip(bytes=None, /)
3777 bytearray.strip(bytes=None, /)
3778
3779 Return a copy of the sequence with specified leading and trailing bytes
3780 removed. The *bytes* argument is a binary sequence specifying the set of
3781 byte values to be removed. If omitted or ``None``, the *bytes*
3782 argument defaults to removing ASCII whitespace. The *bytes* argument is
3783 not a prefix or suffix; rather, all combinations of its values are
3784 stripped::
3785
3786 >>> b' spacious '.strip()
3787 b'spacious'
3788 >>> b'www.example.com'.strip(b'cmowz.')
3789 b'example'
3790
3791 The binary sequence of byte values to remove may be any
3792 :term:`bytes-like object`.
3793
3794 .. note::
3795
3796 The bytearray version of this method does *not* operate in place -
3797 it always produces a new object, even if no changes were made.
3798
3799
3800 The following methods on bytes and bytearray objects assume the use of ASCII
3801 compatible binary formats and should not be applied to arbitrary binary data.
3802 Note that all of the bytearray methods in this section do *not* operate in
3803 place, and instead produce new objects.
3804
3805 .. method:: bytes.capitalize()
3806 bytearray.capitalize()
3807
3808 Return a copy of the sequence with each byte interpreted as an ASCII
3809 character, and the first byte capitalized and the rest lowercased.
3810 Non-ASCII byte values are passed through unchanged.
3811
3812 .. note::
3813
3814 The bytearray version of this method does *not* operate in place - it
3815 always produces a new object, even if no changes were made.
3816
3817
3818 .. method:: bytes.expandtabs(tabsize=8)
3819 bytearray.expandtabs(tabsize=8)
3820
3821 Return a copy of the sequence where all ASCII tab characters are replaced
3822 by one or more ASCII spaces, depending on the current column and the given
3823 tab size. Tab positions occur every *tabsize* bytes (default is 8,
3824 giving tab positions at columns 0, 8, 16 and so on). To expand the
3825 sequence, the current column is set to zero and the sequence is examined
3826 byte by byte. If the byte is an ASCII tab character (``b'\t'``), one or
3827 more space characters are inserted in the result until the current column
3828 is equal to the next tab position. (The tab character itself is not
3829 copied.) If the current byte is an ASCII newline (``b'\n'``) or
3830 carriage return (``b'\r'``), it is copied and the current column is reset
3831 to zero. Any other byte value is copied unchanged and the current column
3832 is incremented by one regardless of how the byte value is represented when
3833 printed::
3834
3835 >>> b'01\t012\t0123\t01234'.expandtabs()
3836 b'01 012 0123 01234'
3837 >>> b'01\t012\t0123\t01234'.expandtabs(4)
3838 b'01 012 0123 01234'
3839
3840 .. note::
3841
3842 The bytearray version of this method does *not* operate in place - it
3843 always produces a new object, even if no changes were made.
3844
3845
3846 .. method:: bytes.isalnum()
3847 bytearray.isalnum()
3848
3849 Return ``True`` if all bytes in the sequence are alphabetical ASCII characters
3850 or ASCII decimal digits and the sequence is not empty, ``False`` otherwise.
3851 Alphabetic ASCII characters are those byte values in the sequence
3852 ``b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'``. ASCII decimal
3853 digits are those byte values in the sequence ``b'0123456789'``.
3854
3855 For example::
3856
3857 >>> b'ABCabc1'.isalnum()
3858 True
3859 >>> b'ABC abc1'.isalnum()
3860 False
3861
3862
3863 .. method:: bytes.isalpha()
3864 bytearray.isalpha()
3865
3866 Return ``True`` if all bytes in the sequence are alphabetic ASCII characters
3867 and the sequence is not empty, ``False`` otherwise. Alphabetic ASCII
3868 characters are those byte values in the sequence
3869 ``b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'``.
3870
3871 For example::
3872
3873 >>> b'ABCabc'.isalpha()
3874 True
3875 >>> b'ABCabc1'.isalpha()
3876 False
3877
3878
3879 .. method:: bytes.isascii()
3880 bytearray.isascii()
3881
3882 Return ``True`` if the sequence is empty or all bytes in the sequence are ASCII,
3883 ``False`` otherwise.
3884 ASCII bytes are in the range 0-0x7F.
3885
3886 .. versionadded:: 3.7
3887
3888
3889 .. method:: bytes.isdigit()
3890 bytearray.isdigit()
3891
3892 Return ``True`` if all bytes in the sequence are ASCII decimal digits
3893 and the sequence is not empty, ``False`` otherwise. ASCII decimal digits are
3894 those byte values in the sequence ``b'0123456789'``.
3895
3896 For example::
3897
3898 >>> b'1234'.isdigit()
3899 True
3900 >>> b'1.23'.isdigit()
3901 False
3902
3903
3904 .. method:: bytes.islower()
3905 bytearray.islower()
3906
3907 Return ``True`` if there is at least one lowercase ASCII character
3908 in the sequence and no uppercase ASCII characters, ``False`` otherwise.
3909
3910 For example::
3911
3912 >>> b'hello world'.islower()
3913 True
3914 >>> b'Hello world'.islower()
3915 False
3916
3917 Lowercase ASCII characters are those byte values in the sequence
3918 ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters
3919 are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``.
3920
3921
3922 .. method:: bytes.isspace()
3923 bytearray.isspace()
3924
3925 Return ``True`` if all bytes in the sequence are ASCII whitespace and the
3926 sequence is not empty, ``False`` otherwise. ASCII whitespace characters are
3927 those byte values in the sequence ``b' \t\n\r\x0b\f'`` (space, tab, newline,
3928 carriage return, vertical tab, form feed).
3929
3930
3931 .. method:: bytes.istitle()
3932 bytearray.istitle()
3933
3934 Return ``True`` if the sequence is ASCII titlecase and the sequence is not
3935 empty, ``False`` otherwise. See :meth:`bytes.title` for more details on the
3936 definition of "titlecase".
3937
3938 For example::
3939
3940 >>> b'Hello World'.istitle()
3941 True
3942 >>> b'Hello world'.istitle()
3943 False
3944
3945
3946 .. method:: bytes.isupper()
3947 bytearray.isupper()
3948
3949 Return ``True`` if there is at least one uppercase alphabetic ASCII character
3950 in the sequence and no lowercase ASCII characters, ``False`` otherwise.
3951
3952 For example::
3953
3954 >>> b'HELLO WORLD'.isupper()
3955 True
3956 >>> b'Hello world'.isupper()
3957 False
3958
3959 Lowercase ASCII characters are those byte values in the sequence
3960 ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters
3961 are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``.
3962
3963
3964 .. method:: bytes.lower()
3965 bytearray.lower()
3966
3967 Return a copy of the sequence with all the uppercase ASCII characters
3968 converted to their corresponding lowercase counterpart.
3969
3970 For example::
3971
3972 >>> b'Hello World'.lower()
3973 b'hello world'
3974
3975 Lowercase ASCII characters are those byte values in the sequence
3976 ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters
3977 are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``.
3978
3979 .. note::
3980
3981 The bytearray version of this method does *not* operate in place - it
3982 always produces a new object, even if no changes were made.
3983
3984
3985 .. index::
3986 single: universal newlines; bytes.splitlines method
3987 single: universal newlines; bytearray.splitlines method
3988
3989 .. method:: bytes.splitlines(keepends=False)
3990 bytearray.splitlines(keepends=False)
3991
3992 Return a list of the lines in the binary sequence, breaking at ASCII
3993 line boundaries. This method uses the :term:`universal newlines` approach
3994 to splitting lines. Line breaks are not included in the resulting list
3995 unless *keepends* is given and true.
3996
3997 For example::
3998
3999 >>> b'ab c\n\nde fg\rkl\r\n'.splitlines()
4000 [b'ab c', b'', b'de fg', b'kl']
4001 >>> b'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
4002 [b'ab c\n', b'\n', b'de fg\r', b'kl\r\n']
4003
4004 Unlike :meth:`~bytes.split` when a delimiter string *sep* is given, this
4005 method returns an empty list for the empty string, and a terminal line
4006 break does not result in an extra line::
4007
4008 >>> b"".split(b'\n'), b"Two lines\n".split(b'\n')
4009 ([b''], [b'Two lines', b''])
4010 >>> b"".splitlines(), b"One line\n".splitlines()
4011 ([], [b'One line'])
4012
4013
4014 .. method:: bytes.swapcase()
4015 bytearray.swapcase()
4016
4017 Return a copy of the sequence with all the lowercase ASCII characters
4018 converted to their corresponding uppercase counterpart and vice-versa.
4019
4020 For example::
4021
4022 >>> b'Hello World'.swapcase()
4023 b'hELLO wORLD'
4024
4025 Lowercase ASCII characters are those byte values in the sequence
4026 ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters
4027 are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``.
4028
4029 Unlike :func:`str.swapcase`, it is always the case that
4030 ``bin.swapcase().swapcase() == bin`` for the binary versions. Case
4031 conversions are symmetrical in ASCII, even though that is not generally
4032 true for arbitrary Unicode code points.
4033
4034 .. note::
4035
4036 The bytearray version of this method does *not* operate in place - it
4037 always produces a new object, even if no changes were made.
4038
4039
4040 .. method:: bytes.title()
4041 bytearray.title()
4042
4043 Return a titlecased version of the binary sequence where words start with
4044 an uppercase ASCII character and the remaining characters are lowercase.
4045 Uncased byte values are left unmodified.
4046
4047 For example::
4048
4049 >>> b'Hello world'.title()
4050 b'Hello World'
4051
4052 Lowercase ASCII characters are those byte values in the sequence
4053 ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters
4054 are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``.
4055 All other byte values are uncased.
4056
4057 The algorithm uses a simple language-independent definition of a word as
4058 groups of consecutive letters. The definition works in many contexts but
4059 it means that apostrophes in contractions and possessives form word
4060 boundaries, which may not be the desired result::
4061
4062 >>> b"they're bill's friends from the UK".title()
4063 b"They'Re Bill'S Friends From The Uk"
4064
4065 A workaround for apostrophes can be constructed using regular expressions::
4066
4067 >>> import re
4068 >>> def titlecase(s):
4069 ... return re.sub(rb"[A-Za-z]+('[A-Za-z]+)?",
4070 ... lambda mo: mo.group(0)[0:1].upper() +
4071 ... mo.group(0)[1:].lower(),
4072 ... s)
4073 ...
4074 >>> titlecase(b"they're bill's friends.")
4075 b"They're Bill's Friends."
4076
4077 .. note::
4078
4079 The bytearray version of this method does *not* operate in place - it
4080 always produces a new object, even if no changes were made.
4081
4082
4083 .. method:: bytes.upper()
4084 bytearray.upper()
4085
4086 Return a copy of the sequence with all the lowercase ASCII characters
4087 converted to their corresponding uppercase counterpart.
4088
4089 For example::
4090
4091 >>> b'Hello World'.upper()
4092 b'HELLO WORLD'
4093
4094 Lowercase ASCII characters are those byte values in the sequence
4095 ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters
4096 are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``.
4097
4098 .. note::
4099
4100 The bytearray version of this method does *not* operate in place - it
4101 always produces a new object, even if no changes were made.
4102
4103
4104 .. method:: bytes.zfill(width, /)
4105 bytearray.zfill(width, /)
4106
4107 Return a copy of the sequence left filled with ASCII ``b'0'`` digits to
4108 make a sequence of length *width*. A leading sign prefix (``b'+'``/
4109 ``b'-'``) is handled by inserting the padding *after* the sign character
4110 rather than before. For :class:`bytes` objects, the original sequence is
4111 returned if *width* is less than or equal to ``len(seq)``.
4112
4113 For example::
4114
4115 >>> b"42".zfill(5)
4116 b'00042'
4117 >>> b"-42".zfill(5)
4118 b'-0042'
4119
4120 .. note::
4121
4122 The bytearray version of this method does *not* operate in place - it
4123 always produces a new object, even if no changes were made.
4124
4125
4126 .. _bytes-formatting:
4127
4128 ``printf``-style Bytes Formatting
4129 ----------------------------------
4130
4131 .. index::
4132 single: formatting; bytes (%)
4133 single: formatting; bytearray (%)
4134 single: interpolation; bytes (%)
4135 single: interpolation; bytearray (%)
4136 single: bytes; formatting
4137 single: bytearray; formatting
4138 single: bytes; interpolation
4139 single: bytearray; interpolation
4140 single: printf-style formatting
4141 single: sprintf-style formatting
4142 single: % (percent); printf-style formatting
4143
4144 .. note::
4145
4146 The formatting operations described here exhibit a variety of quirks that
4147 lead to a number of common errors (such as failing to display tuples and
4148 dictionaries correctly). If the value being printed may be a tuple or
4149 dictionary, wrap it in a tuple.
4150
4151 Bytes objects (``bytes``/``bytearray``) have one unique built-in operation:
4152 the ``%`` operator (modulo).
4153 This is also known as the bytes *formatting* or *interpolation* operator.
4154 Given ``format % values`` (where *format* is a bytes object), ``%`` conversion
4155 specifications in *format* are replaced with zero or more elements of *values*.
4156 The effect is similar to using the :c:func:`sprintf` in the C language.
4157
4158 If *format* requires a single argument, *values* may be a single non-tuple
4159 object. [5]_ Otherwise, *values* must be a tuple with exactly the number of
4160 items specified by the format bytes object, or a single mapping object (for
4161 example, a dictionary).
4162
4163 .. index::
4164 single: () (parentheses); in printf-style formatting
4165 single: * (asterisk); in printf-style formatting
4166 single: . (dot); in printf-style formatting
4167
4168 A conversion specifier contains two or more characters and has the following
4169 components, which must occur in this order:
4170
4171 #. The ``'%'`` character, which marks the start of the specifier.
4172
4173 #. Mapping key (optional), consisting of a parenthesised sequence of characters
4174 (for example, ``(somename)``).
4175
4176 #. Conversion flags (optional), which affect the result of some conversion
4177 types.
4178
4179 #. Minimum field width (optional). If specified as an ``'*'`` (asterisk), the
4180 actual width is read from the next element of the tuple in *values*, and the
4181 object to convert comes after the minimum field width and optional precision.
4182
4183 #. Precision (optional), given as a ``'.'`` (dot) followed by the precision. If
4184 specified as ``'*'`` (an asterisk), the actual precision is read from the next
4185 element of the tuple in *values*, and the value to convert comes after the
4186 precision.
4187
4188 #. Length modifier (optional).
4189
4190 #. Conversion type.
4191
4192 When the right argument is a dictionary (or other mapping type), then the
4193 formats in the bytes object *must* include a parenthesised mapping key into that
4194 dictionary inserted immediately after the ``'%'`` character. The mapping key
4195 selects the value to be formatted from the mapping. For example:
4196
4197 >>> print(b'%(language)s has %(number)03d quote types.' %
4198 ... {b'language': b"Python", b"number": 2})
4199 b'Python has 002 quote types.'
4200
4201 In this case no ``*`` specifiers may occur in a format (since they require a
4202 sequential parameter list).
4203
4204 The conversion flag characters are:
4205
4206 .. index::
4207 single: # (hash); in printf-style formatting
4208 single: - (minus); in printf-style formatting
4209 single: + (plus); in printf-style formatting
4210 single: space; in printf-style formatting
4211
4212 +---------+---------------------------------------------------------------------+
4213 | Flag | Meaning |
4214 +=========+=====================================================================+
4215 | ``'#'`` | The value conversion will use the "alternate form" (where defined |
4216 | | below). |
4217 +---------+---------------------------------------------------------------------+
4218 | ``'0'`` | The conversion will be zero padded for numeric values. |
4219 +---------+---------------------------------------------------------------------+
4220 | ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` |
4221 | | conversion if both are given). |
4222 +---------+---------------------------------------------------------------------+
4223 | ``' '`` | (a space) A blank should be left before a positive number (or empty |
4224 | | string) produced by a signed conversion. |
4225 +---------+---------------------------------------------------------------------+
4226 | ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion |
4227 | | (overrides a "space" flag). |
4228 +---------+---------------------------------------------------------------------+
4229
4230 A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it
4231 is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``.
4232
4233 The conversion types are:
4234
4235 +------------+-----------------------------------------------------+-------+
4236 | Conversion | Meaning | Notes |
4237 +============+=====================================================+=======+
4238 | ``'d'`` | Signed integer decimal. | |
4239 +------------+-----------------------------------------------------+-------+
4240 | ``'i'`` | Signed integer decimal. | |
4241 +------------+-----------------------------------------------------+-------+
4242 | ``'o'`` | Signed octal value. | \(1) |
4243 +------------+-----------------------------------------------------+-------+
4244 | ``'u'`` | Obsolete type -- it is identical to ``'d'``. | \(8) |
4245 +------------+-----------------------------------------------------+-------+
4246 | ``'x'`` | Signed hexadecimal (lowercase). | \(2) |
4247 +------------+-----------------------------------------------------+-------+
4248 | ``'X'`` | Signed hexadecimal (uppercase). | \(2) |
4249 +------------+-----------------------------------------------------+-------+
4250 | ``'e'`` | Floating-point exponential format (lowercase). | \(3) |
4251 +------------+-----------------------------------------------------+-------+
4252 | ``'E'`` | Floating-point exponential format (uppercase). | \(3) |
4253 +------------+-----------------------------------------------------+-------+
4254 | ``'f'`` | Floating-point decimal format. | \(3) |
4255 +------------+-----------------------------------------------------+-------+
4256 | ``'F'`` | Floating-point decimal format. | \(3) |
4257 +------------+-----------------------------------------------------+-------+
4258 | ``'g'`` | Floating-point format. Uses lowercase exponential | \(4) |
4259 | | format if exponent is less than -4 or not less than | |
4260 | | precision, decimal format otherwise. | |
4261 +------------+-----------------------------------------------------+-------+
4262 | ``'G'`` | Floating-point format. Uses uppercase exponential | \(4) |
4263 | | format if exponent is less than -4 or not less than | |
4264 | | precision, decimal format otherwise. | |
4265 +------------+-----------------------------------------------------+-------+
4266 | ``'c'`` | Single byte (accepts integer or single | |
4267 | | byte objects). | |
4268 +------------+-----------------------------------------------------+-------+
4269 | ``'b'`` | Bytes (any object that follows the | \(5) |
4270 | | :ref:`buffer protocol <bufferobjects>` or has | |
4271 | | :meth:`~object.__bytes__`). | |
4272 +------------+-----------------------------------------------------+-------+
4273 | ``'s'`` | ``'s'`` is an alias for ``'b'`` and should only | \(6) |
4274 | | be used for Python2/3 code bases. | |
4275 +------------+-----------------------------------------------------+-------+
4276 | ``'a'`` | Bytes (converts any Python object using | \(5) |
4277 | | ``repr(obj).encode('ascii', 'backslashreplace')``). | |
4278 +------------+-----------------------------------------------------+-------+
4279 | ``'r'`` | ``'r'`` is an alias for ``'a'`` and should only | \(7) |
4280 | | be used for Python2/3 code bases. | |
4281 +------------+-----------------------------------------------------+-------+
4282 | ``'%'`` | No argument is converted, results in a ``'%'`` | |
4283 | | character in the result. | |
4284 +------------+-----------------------------------------------------+-------+
4285
4286 Notes:
4287
4288 (1)
4289 The alternate form causes a leading octal specifier (``'0o'``) to be
4290 inserted before the first digit.
4291
4292 (2)
4293 The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether
4294 the ``'x'`` or ``'X'`` format was used) to be inserted before the first digit.
4295
4296 (3)
4297 The alternate form causes the result to always contain a decimal point, even if
4298 no digits follow it.
4299
4300 The precision determines the number of digits after the decimal point and
4301 defaults to 6.
4302
4303 (4)
4304 The alternate form causes the result to always contain a decimal point, and
4305 trailing zeroes are not removed as they would otherwise be.
4306
4307 The precision determines the number of significant digits before and after the
4308 decimal point and defaults to 6.
4309
4310 (5)
4311 If precision is ``N``, the output is truncated to ``N`` characters.
4312
4313 (6)
4314 ``b'%s'`` is deprecated, but will not be removed during the 3.x series.
4315
4316 (7)
4317 ``b'%r'`` is deprecated, but will not be removed during the 3.x series.
4318
4319 (8)
4320 See :pep:`237`.
4321
4322 .. note::
4323
4324 The bytearray version of this method does *not* operate in place - it
4325 always produces a new object, even if no changes were made.
4326
4327 .. seealso::
4328
4329 :pep:`461` - Adding % formatting to bytes and bytearray
4330
4331 .. versionadded:: 3.5
4332
4333 .. _typememoryview:
4334
4335 Memory Views
4336 ------------
4337
4338 :class:`memoryview` objects allow Python code to access the internal data
4339 of an object that supports the :ref:`buffer protocol <bufferobjects>` without
4340 copying.
4341
4342 .. class:: memoryview(object)
4343
4344 Create a :class:`memoryview` that references *object*. *object* must
4345 support the buffer protocol. Built-in objects that support the buffer
4346 protocol include :class:`bytes` and :class:`bytearray`.
4347
4348 A :class:`memoryview` has the notion of an *element*, which is the
4349 atomic memory unit handled by the originating *object*. For many simple
4350 types such as :class:`bytes` and :class:`bytearray`, an element is a single
4351 byte, but other types such as :class:`array.array` may have bigger elements.
4352
4353 ``len(view)`` is equal to the length of :class:`~memoryview.tolist`, which
4354 is the nested list representation of the view. If ``view.ndim = 1``,
4355 this is equal to the number of elements in the view.
4356
4357 .. versionchanged:: 3.12
4358 If ``view.ndim == 0``, ``len(view)`` now raises :exc:`TypeError` instead of returning 1.
4359
4360 The :class:`~memoryview.itemsize` attribute will give you the number of
4361 bytes in a single element.
4362
4363 A :class:`memoryview` supports slicing and indexing to expose its data.
4364 One-dimensional slicing will result in a subview::
4365
4366 >>> v = memoryview(b'abcefg')
4367 >>> v[1]
4368 98
4369 >>> v[-1]
4370 103
4371 >>> v[1:4]
4372 <memory at 0x7f3ddc9f4350>
4373 >>> bytes(v[1:4])
4374 b'bce'
4375
4376 If :class:`~memoryview.format` is one of the native format specifiers
4377 from the :mod:`struct` module, indexing with an integer or a tuple of
4378 integers is also supported and returns a single *element* with
4379 the correct type. One-dimensional memoryviews can be indexed
4380 with an integer or a one-integer tuple. Multi-dimensional memoryviews
4381 can be indexed with tuples of exactly *ndim* integers where *ndim* is
4382 the number of dimensions. Zero-dimensional memoryviews can be indexed
4383 with the empty tuple.
4384
4385 Here is an example with a non-byte format::
4386
4387 >>> import array
4388 >>> a = array.array('l', [-11111111, 22222222, -33333333, 44444444])
4389 >>> m = memoryview(a)
4390 >>> m[0]
4391 -11111111
4392 >>> m[-1]
4393 44444444
4394 >>> m[::2].tolist()
4395 [-11111111, -33333333]
4396
4397 If the underlying object is writable, the memoryview supports
4398 one-dimensional slice assignment. Resizing is not allowed::
4399
4400 >>> data = bytearray(b'abcefg')
4401 >>> v = memoryview(data)
4402 >>> v.readonly
4403 False
4404 >>> v[0] = ord(b'z')
4405 >>> data
4406 bytearray(b'zbcefg')
4407 >>> v[1:4] = b'123'
4408 >>> data
4409 bytearray(b'z123fg')
4410 >>> v[2:3] = b'spam'
4411 Traceback (most recent call last):
4412 File "<stdin>", line 1, in <module>
4413 ValueError: memoryview assignment: lvalue and rvalue have different structures
4414 >>> v[2:6] = b'spam'
4415 >>> data
4416 bytearray(b'z1spam')
4417
4418 One-dimensional memoryviews of :term:`hashable` (read-only) types with formats
4419 'B', 'b' or 'c' are also hashable. The hash is defined as
4420 ``hash(m) == hash(m.tobytes())``::
4421
4422 >>> v = memoryview(b'abcefg')
4423 >>> hash(v) == hash(b'abcefg')
4424 True
4425 >>> hash(v[2:4]) == hash(b'ce')
4426 True
4427 >>> hash(v[::-2]) == hash(b'abcefg'[::-2])
4428 True
4429
4430 .. versionchanged:: 3.3
4431 One-dimensional memoryviews can now be sliced.
4432 One-dimensional memoryviews with formats 'B', 'b' or 'c' are now :term:`hashable`.
4433
4434 .. versionchanged:: 3.4
4435 memoryview is now registered automatically with
4436 :class:`collections.abc.Sequence`
4437
4438 .. versionchanged:: 3.5
4439 memoryviews can now be indexed with tuple of integers.
4440
4441 :class:`memoryview` has several methods:
4442
4443 .. method:: __eq__(exporter)
4444
4445 A memoryview and a :pep:`3118` exporter are equal if their shapes are
4446 equivalent and if all corresponding values are equal when the operands'
4447 respective format codes are interpreted using :mod:`struct` syntax.
4448
4449 For the subset of :mod:`struct` format strings currently supported by
4450 :meth:`tolist`, ``v`` and ``w`` are equal if ``v.tolist() == w.tolist()``::
4451
4452 >>> import array
4453 >>> a = array.array('I', [1, 2, 3, 4, 5])
4454 >>> b = array.array('d', [1.0, 2.0, 3.0, 4.0, 5.0])
4455 >>> c = array.array('b', [5, 3, 1])
4456 >>> x = memoryview(a)
4457 >>> y = memoryview(b)
4458 >>> x == a == y == b
4459 True
4460 >>> x.tolist() == a.tolist() == y.tolist() == b.tolist()
4461 True
4462 >>> z = y[::-2]
4463 >>> z == c
4464 True
4465 >>> z.tolist() == c.tolist()
4466 True
4467
4468 If either format string is not supported by the :mod:`struct` module,
4469 then the objects will always compare as unequal (even if the format
4470 strings and buffer contents are identical)::
4471
4472 >>> from ctypes import BigEndianStructure, c_long
4473 >>> class BEPoint(BigEndianStructure):
4474 ... _fields_ = [("x", c_long), ("y", c_long)]
4475 ...
4476 >>> point = BEPoint(100, 200)
4477 >>> a = memoryview(point)
4478 >>> b = memoryview(point)
4479 >>> a == point
4480 False
4481 >>> a == b
4482 False
4483
4484 Note that, as with floating-point numbers, ``v is w`` does *not* imply
4485 ``v == w`` for memoryview objects.
4486
4487 .. versionchanged:: 3.3
4488 Previous versions compared the raw memory disregarding the item format
4489 and the logical array structure.
4490
4491 .. method:: tobytes(order='C')
4492
4493 Return the data in the buffer as a bytestring. This is equivalent to
4494 calling the :class:`bytes` constructor on the memoryview. ::
4495
4496 >>> m = memoryview(b"abc")
4497 >>> m.tobytes()
4498 b'abc'
4499 >>> bytes(m)
4500 b'abc'
4501
4502 For non-contiguous arrays the result is equal to the flattened list
4503 representation with all elements converted to bytes. :meth:`tobytes`
4504 supports all format strings, including those that are not in
4505 :mod:`struct` module syntax.
4506
4507 .. versionadded:: 3.8
4508 *order* can be {'C', 'F', 'A'}. When *order* is 'C' or 'F', the data
4509 of the original array is converted to C or Fortran order. For contiguous
4510 views, 'A' returns an exact copy of the physical memory. In particular,
4511 in-memory Fortran order is preserved. For non-contiguous views, the
4512 data is converted to C first. *order=None* is the same as *order='C'*.
4513
4514 .. method:: hex(*, bytes_per_sep=1)
4515 hex(sep, bytes_per_sep=1)
4516
4517 Return a string object containing two hexadecimal digits for each
4518 byte in the buffer. ::
4519
4520 >>> m = memoryview(b"abc")
4521 >>> m.hex()
4522 '616263'
4523
4524 .. versionadded:: 3.5
4525
4526 .. versionchanged:: 3.8
4527 Similar to :meth:`bytes.hex`, :meth:`memoryview.hex` now supports
4528 optional *sep* and *bytes_per_sep* parameters to insert separators
4529 between bytes in the hex output.
4530
4531 .. method:: tolist()
4532
4533 Return the data in the buffer as a list of elements. ::
4534
4535 >>> memoryview(b'abc').tolist()
4536 [97, 98, 99]
4537 >>> import array
4538 >>> a = array.array('d', [1.1, 2.2, 3.3])
4539 >>> m = memoryview(a)
4540 >>> m.tolist()
4541 [1.1, 2.2, 3.3]
4542
4543 .. versionchanged:: 3.3
4544 :meth:`tolist` now supports all single character native formats in
4545 :mod:`struct` module syntax as well as multi-dimensional
4546 representations.
4547
4548 .. method:: toreadonly()
4549
4550 Return a readonly version of the memoryview object. The original
4551 memoryview object is unchanged. ::
4552
4553 >>> m = memoryview(bytearray(b'abc'))
4554 >>> mm = m.toreadonly()
4555 >>> mm.tolist()
4556 [97, 98, 99]
4557 >>> mm[0] = 42
4558 Traceback (most recent call last):
4559 File "<stdin>", line 1, in <module>
4560 TypeError: cannot modify read-only memory
4561 >>> m[0] = 43
4562 >>> mm.tolist()
4563 [43, 98, 99]
4564
4565 .. versionadded:: 3.8
4566
4567 .. method:: release()
4568
4569 Release the underlying buffer exposed by the memoryview object. Many
4570 objects take special actions when a view is held on them (for example,
4571 a :class:`bytearray` would temporarily forbid resizing); therefore,
4572 calling release() is handy to remove these restrictions (and free any
4573 dangling resources) as soon as possible.
4574
4575 After this method has been called, any further operation on the view
4576 raises a :class:`ValueError` (except :meth:`release` itself which can
4577 be called multiple times)::
4578
4579 >>> m = memoryview(b'abc')
4580 >>> m.release()
4581 >>> m[0]
4582 Traceback (most recent call last):
4583 File "<stdin>", line 1, in <module>
4584 ValueError: operation forbidden on released memoryview object
4585
4586 The context management protocol can be used for a similar effect,
4587 using the ``with`` statement::
4588
4589 >>> with memoryview(b'abc') as m:
4590 ... m[0]
4591 ...
4592 97
4593 >>> m[0]
4594 Traceback (most recent call last):
4595 File "<stdin>", line 1, in <module>
4596 ValueError: operation forbidden on released memoryview object
4597
4598 .. versionadded:: 3.2
4599
4600 .. method:: cast(format, /)
4601 cast(format, shape, /)
4602
4603 Cast a memoryview to a new format or shape. *shape* defaults to
4604 ``[byte_length//new_itemsize]``, which means that the result view
4605 will be one-dimensional. The return value is a new memoryview, but
4606 the buffer itself is not copied. Supported casts are 1D -> C-:term:`contiguous`
4607 and C-contiguous -> 1D.
4608
4609 The destination format is restricted to a single element native format in
4610 :mod:`struct` syntax. One of the formats must be a byte format
4611 ('B', 'b' or 'c'). The byte length of the result must be the same
4612 as the original length.
4613 Note that all byte lengths may depend on the operating system.
4614
4615 Cast 1D/long to 1D/unsigned bytes::
4616
4617 >>> import array
4618 >>> a = array.array('l', [1,2,3])
4619 >>> x = memoryview(a)
4620 >>> x.format
4621 'l'
4622 >>> x.itemsize
4623 8
4624 >>> len(x)
4625 3
4626 >>> x.nbytes
4627 24
4628 >>> y = x.cast('B')
4629 >>> y.format
4630 'B'
4631 >>> y.itemsize
4632 1
4633 >>> len(y)
4634 24
4635 >>> y.nbytes
4636 24
4637
4638 Cast 1D/unsigned bytes to 1D/char::
4639
4640 >>> b = bytearray(b'zyz')
4641 >>> x = memoryview(b)
4642 >>> x[0] = b'a'
4643 Traceback (most recent call last):
4644 ...
4645 TypeError: memoryview: invalid type for format 'B'
4646 >>> y = x.cast('c')
4647 >>> y[0] = b'a'
4648 >>> b
4649 bytearray(b'ayz')
4650
4651 Cast 1D/bytes to 3D/ints to 1D/signed char::
4652
4653 >>> import struct
4654 >>> buf = struct.pack("i"*12, *list(range(12)))
4655 >>> x = memoryview(buf)
4656 >>> y = x.cast('i', shape=[2,2,3])
4657 >>> y.tolist()
4658 [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]
4659 >>> y.format
4660 'i'
4661 >>> y.itemsize
4662 4
4663 >>> len(y)
4664 2
4665 >>> y.nbytes
4666 48
4667 >>> z = y.cast('b')
4668 >>> z.format
4669 'b'
4670 >>> z.itemsize
4671 1
4672 >>> len(z)
4673 48
4674 >>> z.nbytes
4675 48
4676
4677 Cast 1D/unsigned long to 2D/unsigned long::
4678
4679 >>> buf = struct.pack("L"*6, *list(range(6)))
4680 >>> x = memoryview(buf)
4681 >>> y = x.cast('L', shape=[2,3])
4682 >>> len(y)
4683 2
4684 >>> y.nbytes
4685 48
4686 >>> y.tolist()
4687 [[0, 1, 2], [3, 4, 5]]
4688
4689 .. versionadded:: 3.3
4690
4691 .. versionchanged:: 3.5
4692 The source format is no longer restricted when casting to a byte view.
4693
4694 There are also several readonly attributes available:
4695
4696 .. attribute:: obj
4697
4698 The underlying object of the memoryview::
4699
4700 >>> b = bytearray(b'xyz')
4701 >>> m = memoryview(b)
4702 >>> m.obj is b
4703 True
4704
4705 .. versionadded:: 3.3
4706
4707 .. attribute:: nbytes
4708
4709 ``nbytes == product(shape) * itemsize == len(m.tobytes())``. This is
4710 the amount of space in bytes that the array would use in a contiguous
4711 representation. It is not necessarily equal to ``len(m)``::
4712
4713 >>> import array
4714 >>> a = array.array('i', [1,2,3,4,5])
4715 >>> m = memoryview(a)
4716 >>> len(m)
4717 5
4718 >>> m.nbytes
4719 20
4720 >>> y = m[::2]
4721 >>> len(y)
4722 3
4723 >>> y.nbytes
4724 12
4725 >>> len(y.tobytes())
4726 12
4727
4728 Multi-dimensional arrays::
4729
4730 >>> import struct
4731 >>> buf = struct.pack("d"*12, *[1.5*x for x in range(12)])
4732 >>> x = memoryview(buf)
4733 >>> y = x.cast('d', shape=[3,4])
4734 >>> y.tolist()
4735 [[0.0, 1.5, 3.0, 4.5], [6.0, 7.5, 9.0, 10.5], [12.0, 13.5, 15.0, 16.5]]
4736 >>> len(y)
4737 3
4738 >>> y.nbytes
4739 96
4740
4741 .. versionadded:: 3.3
4742
4743 .. attribute:: readonly
4744
4745 A bool indicating whether the memory is read only.
4746
4747 .. attribute:: format
4748
4749 A string containing the format (in :mod:`struct` module style) for each
4750 element in the view. A memoryview can be created from exporters with
4751 arbitrary format strings, but some methods (e.g. :meth:`tolist`) are
4752 restricted to native single element formats.
4753
4754 .. versionchanged:: 3.3
4755 format ``'B'`` is now handled according to the struct module syntax.
4756 This means that ``memoryview(b'abc')[0] == b'abc'[0] == 97``.
4757
4758 .. attribute:: itemsize
4759
4760 The size in bytes of each element of the memoryview::
4761
4762 >>> import array, struct
4763 >>> m = memoryview(array.array('H', [32000, 32001, 32002]))
4764 >>> m.itemsize
4765 2
4766 >>> m[0]
4767 32000
4768 >>> struct.calcsize('H') == m.itemsize
4769 True
4770
4771 .. attribute:: ndim
4772
4773 An integer indicating how many dimensions of a multi-dimensional array the
4774 memory represents.
4775
4776 .. attribute:: shape
4777
4778 A tuple of integers the length of :attr:`ndim` giving the shape of the
4779 memory as an N-dimensional array.
4780
4781 .. versionchanged:: 3.3
4782 An empty tuple instead of ``None`` when ndim = 0.
4783
4784 .. attribute:: strides
4785
4786 A tuple of integers the length of :attr:`ndim` giving the size in bytes to
4787 access each element for each dimension of the array.
4788
4789 .. versionchanged:: 3.3
4790 An empty tuple instead of ``None`` when ndim = 0.
4791
4792 .. attribute:: suboffsets
4793
4794 Used internally for PIL-style arrays. The value is informational only.
4795
4796 .. attribute:: c_contiguous
4797
4798 A bool indicating whether the memory is C-:term:`contiguous`.
4799
4800 .. versionadded:: 3.3
4801
4802 .. attribute:: f_contiguous
4803
4804 A bool indicating whether the memory is Fortran :term:`contiguous`.
4805
4806 .. versionadded:: 3.3
4807
4808 .. attribute:: contiguous
4809
4810 A bool indicating whether the memory is :term:`contiguous`.
4811
4812 .. versionadded:: 3.3
4813
4814
4815 .. _types-set:
4816
4817 Set Types --- :class:`set`, :class:`frozenset`
4818 ==============================================
4819
4820 .. index:: pair: object; set
4821
4822 A :dfn:`set` object is an unordered collection of distinct :term:`hashable` objects.
4823 Common uses include membership testing, removing duplicates from a sequence, and
4824 computing mathematical operations such as intersection, union, difference, and
4825 symmetric difference.
4826 (For other containers see the built-in :class:`dict`, :class:`list`,
4827 and :class:`tuple` classes, and the :mod:`collections` module.)
4828
4829 Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in
4830 set``. Being an unordered collection, sets do not record element position or
4831 order of insertion. Accordingly, sets do not support indexing, slicing, or
4832 other sequence-like behavior.
4833
4834 There are currently two built-in set types, :class:`set` and :class:`frozenset`.
4835 The :class:`set` type is mutable --- the contents can be changed using methods
4836 like :meth:`~set.add` and :meth:`~set.remove`. Since it is mutable, it has no
4837 hash value and cannot be used as either a dictionary key or as an element of
4838 another set. The :class:`frozenset` type is immutable and :term:`hashable` ---
4839 its contents cannot be altered after it is created; it can therefore be used as
4840 a dictionary key or as an element of another set.
4841
4842 Non-empty sets (not frozensets) can be created by placing a comma-separated list
4843 of elements within braces, for example: ``{'jack', 'sjoerd'}``, in addition to the
4844 :class:`set` constructor.
4845
4846 The constructors for both classes work the same:
4847
4848 .. class:: set(iterable=(), /)
4849 frozenset(iterable=(), /)
4850
4851 Return a new set or frozenset object whose elements are taken from
4852 *iterable*. The elements of a set must be :term:`hashable`. To
4853 represent sets of sets, the inner sets must be :class:`frozenset`
4854 objects. If *iterable* is not specified, a new empty set is
4855 returned.
4856
4857 Sets can be created by several means:
4858
4859 * Use a comma-separated list of elements within braces: ``{'jack', 'sjoerd'}``
4860 * Use a set comprehension: ``{c for c in 'abracadabra' if c not in 'abc'}``
4861 * Use the type constructor: ``set()``, ``set('foobar')``, ``set(['a', 'b', 'foo'])``
4862
4863 Instances of :class:`set` and :class:`frozenset` provide the following
4864 operations:
4865
4866 .. describe:: len(s)
4867
4868 Return the number of elements in set *s* (cardinality of *s*).
4869
4870 .. describe:: x in s
4871
4872 Test *x* for membership in *s*.
4873
4874 .. describe:: x not in s
4875
4876 Test *x* for non-membership in *s*.
4877
4878 .. method:: frozenset.isdisjoint(other, /)
4879 set.isdisjoint(other, /)
4880
4881 Return ``True`` if the set has no elements in common with *other*. Sets are
4882 disjoint if and only if their intersection is the empty set.
4883
4884 .. method:: frozenset.issubset(other, /)
4885 set.issubset(other, /)
4886 .. describe:: set <= other
4887
4888 Test whether every element in the set is in *other*.
4889
4890 .. describe:: set < other
4891
4892 Test whether the set is a proper subset of *other*, that is,
4893 ``set <= other and set != other``.
4894
4895 .. method:: frozenset.issuperset(other, /)
4896 set.issuperset(other, /)
4897 .. describe:: set >= other
4898
4899 Test whether every element in *other* is in the set.
4900
4901 .. describe:: set > other
4902
4903 Test whether the set is a proper superset of *other*, that is, ``set >=
4904 other and set != other``.
4905
4906 .. method:: frozenset.union(*others)
4907 set.union(*others)
4908 .. describe:: set | other | ...
4909
4910 Return a new set with elements from the set and all others.
4911
4912 .. method:: frozenset.intersection(*others)
4913 set.intersection(*others)
4914 .. describe:: set & other & ...
4915
4916 Return a new set with elements common to the set and all others.
4917
4918 .. method:: frozenset.difference(*others)
4919 set.difference(*others)
4920 .. describe:: set - other - ...
4921
4922 Return a new set with elements in the set that are not in the others.
4923
4924 .. method:: frozenset.symmetric_difference(other, /)
4925 set.symmetric_difference(other, /)
4926 .. describe:: set ^ other
4927
4928 Return a new set with elements in either the set or *other* but not both.
4929
4930 .. method:: frozenset.copy()
4931 set.copy()
4932
4933 Return a shallow copy of the set.
4934
4935
4936 Note, the non-operator versions of :meth:`~frozenset.union`,
4937 :meth:`~frozenset.intersection`, :meth:`~frozenset.difference`, :meth:`~frozenset.symmetric_difference`, :meth:`~frozenset.issubset`, and
4938 :meth:`~frozenset.issuperset` methods will accept any iterable as an argument. In
4939 contrast, their operator based counterparts require their arguments to be
4940 sets. This precludes error-prone constructions like ``set('abc') & 'cbs'``
4941 in favor of the more readable ``set('abc').intersection('cbs')``.
4942
4943 Both :class:`set` and :class:`frozenset` support set to set comparisons. Two
4944 sets are equal if and only if every element of each set is contained in the
4945 other (each is a subset of the other). A set is less than another set if and
4946 only if the first set is a proper subset of the second set (is a subset, but
4947 is not equal). A set is greater than another set if and only if the first set
4948 is a proper superset of the second set (is a superset, but is not equal).
4949
4950 Instances of :class:`set` are compared to instances of :class:`frozenset`
4951 based on their members. For example, ``set('abc') == frozenset('abc')``
4952 returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``.
4953
4954 The subset and equality comparisons do not generalize to a total ordering
4955 function. For example, any two nonempty disjoint sets are not equal and are not
4956 subsets of each other, so *all* of the following return ``False``: ``a<b``,
4957 ``a==b``, or ``a>b``.
4958
4959 Since sets only define partial ordering (subset relationships), the output of
4960 the :meth:`list.sort` method is undefined for lists of sets.
4961
4962 Set elements, like dictionary keys, must be :term:`hashable`.
4963
4964 Binary operations that mix :class:`set` instances with :class:`frozenset`
4965 return the type of the first operand. For example: ``frozenset('ab') |
4966 set('bc')`` returns an instance of :class:`frozenset`.
4967
4968 The following table lists operations available for :class:`set` that do not
4969 apply to immutable instances of :class:`frozenset`:
4970
4971 .. method:: set.update(*others)
4972 .. describe:: set |= other | ...
4973
4974 Update the set, adding elements from all others.
4975
4976 .. method:: set.intersection_update(*others)
4977 .. describe:: set &= other & ...
4978
4979 Update the set, keeping only elements found in it and all others.
4980
4981 .. method:: set.difference_update(*others)
4982 .. describe:: set -= other | ...
4983
4984 Update the set, removing elements found in others.
4985
4986 .. method:: set.symmetric_difference_update(other, /)
4987 .. describe:: set ^= other
4988
4989 Update the set, keeping only elements found in either set, but not in both.
4990
4991 .. method:: set.add(elem, /)
4992
4993 Add element *elem* to the set.
4994
4995 .. method:: set.remove(elem, /)
4996
4997 Remove element *elem* from the set. Raises :exc:`KeyError` if *elem* is
4998 not contained in the set.
4999
5000 .. method:: set.discard(elem, /)
5001
5002 Remove element *elem* from the set if it is present.
5003
5004 .. method:: set.pop()
5005
5006 Remove and return an arbitrary element from the set. Raises
5007 :exc:`KeyError` if the set is empty.
5008
5009 .. method:: set.clear()
5010
5011 Remove all elements from the set.
5012
5013
5014 Note, the non-operator versions of the :meth:`~set.update`,
5015 :meth:`~set.intersection_update`, :meth:`~set.difference_update`, and
5016 :meth:`~set.symmetric_difference_update` methods will accept any iterable as an
5017 argument.
5018
5019 Note, the *elem* argument to the :meth:`~object.__contains__`,
5020 :meth:`~set.remove`, and
5021 :meth:`~set.discard` methods may be a set. To support searching for an equivalent
5022 frozenset, a temporary one is created from *elem*.
5023
5024 Sets and frozensets are :ref:`generic <generics>` over the type of their elements.
5025
5026 .. _typesmapping:
5027
5028 Mapping Types --- :class:`dict`
5029 ===============================
5030
5031 .. index::
5032 pair: object; mapping
5033 pair: object; dictionary
5034 triple: operations on; mapping; types
5035 triple: operations on; dictionary; type
5036 pair: statement; del
5037 pair: built-in function; len
5038
5039 A :term:`mapping` object maps :term:`hashable` values to arbitrary objects.
5040 Mappings are mutable objects. There is currently only one standard mapping
5041 type, the :dfn:`dictionary`. (For other containers see the built-in
5042 :class:`list`, :class:`set`, and :class:`tuple` classes, and the
5043 :mod:`collections` module.)
5044
5045 A dictionary's keys are *almost* arbitrary values. Values that are not
5046 :term:`hashable`, that is, values containing lists, dictionaries or other
5047 mutable types (that are compared by value rather than by object identity) may
5048 not be used as keys.
5049 Values that compare equal (such as ``1``, ``1.0``, and ``True``)
5050 can be used interchangeably to index the same dictionary entry.
5051
5052 .. class:: dict(**kwargs)
5053 dict(mapping, /, **kwargs)
5054 dict(iterable, /, **kwargs)
5055
5056 Return a new dictionary initialized from an optional positional argument
5057 and a possibly empty set of keyword arguments.
5058
5059 Dictionaries can be created by several means:
5060
5061 * Use a comma-separated list of ``key: value`` pairs within braces:
5062 ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098: 'jack', 4127: 'sjoerd'}``
5063 * Use a dict comprehension: ``{}``, ``{x: x ** 2 for x in range(10)}``
5064 * Use the type constructor: ``dict()``,
5065 ``dict([('foo', 100), ('bar', 200)])``, ``dict(foo=100, bar=200)``
5066
5067 If no positional argument is given, an empty dictionary is created.
5068 If a positional argument is given and it defines a ``keys()`` method, a
5069 dictionary is created by calling :meth:`~object.__getitem__` on the argument with
5070 each returned key from the method. Otherwise, the positional argument must be an
5071 :term:`iterable` object. Each item in the iterable must itself be an iterable
5072 with exactly two elements. The first element of each item becomes a key in the
5073 new dictionary, and the second element the corresponding value. If a key occurs
5074 more than once, the last value for that key becomes the corresponding value in
5075 the new dictionary.
5076
5077 If keyword arguments are given, the keyword arguments and their values are
5078 added to the dictionary created from the positional argument. If a key
5079 being added is already present, the value from the keyword argument
5080 replaces the value from the positional argument.
5081
5082 Dictionaries compare equal if and only if they have the same ``(key,
5083 value)`` pairs (regardless of ordering). Order comparisons ('<', '<=', '>=', '>') raise
5084 :exc:`TypeError`. To illustrate dictionary creation and equality,
5085 the following examples all return a dictionary equal to
5086 ``{"one": 1, "two": 2, "three": 3}``::
5087
5088 >>> a = dict(one=1, two=2, three=3)
5089 >>> b = {'one': 1, 'two': 2, 'three': 3}
5090 >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
5091 >>> d = dict([('two', 2), ('one', 1), ('three', 3)])
5092 >>> e = dict({'three': 3, 'one': 1, 'two': 2})
5093 >>> f = dict({'one': 1, 'three': 3}, two=2)
5094 >>> a == b == c == d == e == f
5095 True
5096
5097 Providing keyword arguments as in the first example only works for keys that
5098 are valid Python identifiers. Otherwise, any valid keys can be used.
5099
5100 Dictionaries preserve insertion order. Note that updating a key does not
5101 affect the order. Keys added after deletion are inserted at the end. ::
5102
5103 >>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
5104 >>> d
5105 {'one': 1, 'two': 2, 'three': 3, 'four': 4}
5106 >>> list(d)
5107 ['one', 'two', 'three', 'four']
5108 >>> list(d.values())
5109 [1, 2, 3, 4]
5110 >>> d["one"] = 42
5111 >>> d
5112 {'one': 42, 'two': 2, 'three': 3, 'four': 4}
5113 >>> del d["two"]
5114 >>> d["two"] = None
5115 >>> d
5116 {'one': 42, 'three': 3, 'four': 4, 'two': None}
5117
5118 .. versionchanged:: 3.7
5119 Dictionary order is guaranteed to be insertion order. This behavior was
5120 an implementation detail of CPython from 3.6.
5121
5122 Dictionaries are :ref:`generic <generics>` over two types, signifying
5123 (respectively) the types of the dictionary's keys and values.
5124
5125 These are the operations that dictionaries support (and therefore, custom
5126 mapping types should support too):
5127
5128 .. describe:: list(d)
5129
5130 Return a list of all the keys used in the dictionary *d*.
5131
5132 .. describe:: len(d)
5133
5134 Return the number of items in the dictionary *d*.
5135
5136 .. describe:: d[key]
5137
5138 Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key* is
5139 not in the map.
5140
5141 .. index:: __missing__()
5142
5143 If a subclass of dict defines a method :meth:`~object.__missing__` and *key*
5144 is not present, the ``d[key]`` operation calls that method with the key *key*
5145 as argument. The ``d[key]`` operation then returns or raises whatever is
5146 returned or raised by the ``__missing__(key)`` call.
5147 No other operations or methods invoke :meth:`~object.__missing__`. If
5148 :meth:`~object.__missing__` is not defined, :exc:`KeyError` is raised.
5149 :meth:`~object.__missing__` must be a method; it cannot be an instance variable::
5150
5151 >>> class Counter(dict):
5152 ... def __missing__(self, key):
5153 ... return 0
5154 ...
5155 >>> c = Counter()
5156 >>> c['red']
5157 0
5158 >>> c['red'] += 1
5159 >>> c['red']
5160 1
5161
5162 The example above shows part of the implementation of
5163 :class:`collections.Counter`.
5164 A different :meth:`!__missing__` method is used
5165 by :class:`collections.defaultdict`.
5166
5167 .. describe:: d[key] = value
5168
5169 Set ``d[key]`` to *value*.
5170
5171 .. describe:: del d[key]
5172
5173 Remove ``d[key]`` from *d*. Raises a :exc:`KeyError` if *key* is not in the
5174 map.
5175
5176 .. describe:: key in d
5177
5178 Return ``True`` if *d* has a key *key*, else ``False``.
5179
5180 .. describe:: key not in d
5181
5182 Equivalent to ``not key in d``.
5183
5184 .. describe:: iter(d)
5185
5186 Return an iterator over the keys of the dictionary. This is a shortcut
5187 for ``iter(d.keys())``.
5188
5189 .. method:: clear()
5190
5191 Remove all items from the dictionary.
5192
5193 .. method:: copy()
5194
5195 Return a shallow copy of the dictionary.
5196
5197 .. classmethod:: fromkeys(iterable, value=None, /)
5198
5199 Create a new dictionary with keys from *iterable* and values set to *value*.
5200
5201 :meth:`fromkeys` is a class method that returns a new dictionary. *value*
5202 defaults to ``None``. All of the values refer to just a single instance,
5203 so it generally doesn't make sense for *value* to be a mutable object
5204 such as an empty list. To get distinct values, use a :ref:`dict
5205 comprehension <dict>` instead.
5206
5207 .. method:: get(key, default=None, /)
5208
5209 Return the value for *key* if *key* is in the dictionary, else *default*.
5210 If *default* is not given, it defaults to ``None``, so that this method
5211 never raises a :exc:`KeyError`.
5212
5213 .. method:: items()
5214
5215 Return a new view of the dictionary's items (``(key, value)`` pairs).
5216 See the :ref:`documentation of view objects <dict-views>`.
5217
5218 .. method:: keys()
5219
5220 Return a new view of the dictionary's keys. See the :ref:`documentation
5221 of view objects <dict-views>`.
5222
5223 .. method:: pop(key, /)
5224 pop(key, default, /)
5225
5226 If *key* is in the dictionary, remove it and return its value, else return
5227 *default*. If *default* is not given and *key* is not in the dictionary,
5228 a :exc:`KeyError` is raised.
5229
5230 .. method:: popitem()
5231
5232 Remove and return a ``(key, value)`` pair from the dictionary.
5233 Pairs are returned in :abbr:`LIFO (last-in, first-out)` order.
5234
5235 :meth:`popitem` is useful to destructively iterate over a dictionary, as
5236 often used in set algorithms. If the dictionary is empty, calling
5237 :meth:`popitem` raises a :exc:`KeyError`.
5238
5239 .. versionchanged:: 3.7
5240 LIFO order is now guaranteed. In prior versions, :meth:`popitem` would
5241 return an arbitrary key/value pair.
5242
5243 .. describe:: reversed(d)
5244
5245 Return a reverse iterator over the keys of the dictionary. This is a
5246 shortcut for ``reversed(d.keys())``.
5247
5248 .. versionadded:: 3.8
5249
5250 .. method:: setdefault(key, default=None, /)
5251
5252 If *key* is in the dictionary, return its value. If not, insert *key*
5253 with a value of *default* and return *default*. *default* defaults to
5254 ``None``.
5255
5256 .. method:: update(**kwargs)
5257 update(mapping, /, **kwargs)
5258 update(iterable, /, **kwargs)
5259
5260 Update the dictionary with the key/value pairs from *mapping* or *iterable* and *kwargs*, overwriting
5261 existing keys. Return ``None``.
5262
5263 :meth:`update` accepts either another object with a ``keys()`` method (in
5264 which case :meth:`~object.__getitem__` is called with every key returned from
5265 the method) or an iterable of key/value pairs (as tuples or other iterables
5266 of length two). If keyword arguments are specified, the dictionary is then
5267 updated with those key/value pairs: ``d.update(red=1, blue=2)``.
5268
5269 .. method:: values()
5270
5271 Return a new view of the dictionary's values. See the
5272 :ref:`documentation of view objects <dict-views>`.
5273
5274 An equality comparison between one ``dict.values()`` view and another
5275 will always return ``False``. This also applies when comparing
5276 ``dict.values()`` to itself::
5277
5278 >>> d = {'a': 1}
5279 >>> d.values() == d.values()
5280 False
5281
5282 .. describe:: d | other
5283
5284 Create a new dictionary with the merged keys and values of *d* and
5285 *other*, which must both be dictionaries. The values of *other* take
5286 priority when *d* and *other* share keys.
5287
5288 .. versionadded:: 3.9
5289
5290 .. describe:: d |= other
5291
5292 Update the dictionary *d* with keys and values from *other*, which may be
5293 either a :term:`mapping` or an :term:`iterable` of key/value pairs. The
5294 values of *other* take priority when *d* and *other* share keys.
5295
5296 .. versionadded:: 3.9
5297
5298 Dictionaries and dictionary views are reversible. ::
5299
5300 >>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
5301 >>> d
5302 {'one': 1, 'two': 2, 'three': 3, 'four': 4}
5303 >>> list(reversed(d))
5304 ['four', 'three', 'two', 'one']
5305 >>> list(reversed(d.values()))
5306 [4, 3, 2, 1]
5307 >>> list(reversed(d.items()))
5308 [('four', 4), ('three', 3), ('two', 2), ('one', 1)]
5309
5310 .. versionchanged:: 3.8
5311 Dictionaries are now reversible.
5312
5313
5314 .. seealso::
5315 :class:`types.MappingProxyType` can be used to create a read-only view
5316 of a :class:`dict`.
5317
5318
5319 .. _dict-views:
5320
5321 Dictionary view objects
5322 -----------------------
5323
5324 The objects returned by :meth:`dict.keys`, :meth:`dict.values` and
5325 :meth:`dict.items` are *view objects*. They provide a dynamic view on the
5326 dictionary's entries, which means that when the dictionary changes, the view
5327 reflects these changes.
5328
5329 Dictionary views can be iterated over to yield their respective data, and
5330 support membership tests:
5331
5332 .. describe:: len(dictview)
5333
5334 Return the number of entries in the dictionary.
5335
5336 .. describe:: iter(dictview)
5337
5338 Return an iterator over the keys, values or items (represented as tuples of
5339 ``(key, value)``) in the dictionary.
5340
5341 Keys and values are iterated over in insertion order.
5342 This allows the creation of ``(value, key)`` pairs
5343 using :func:`zip`: ``pairs = zip(d.values(), d.keys())``. Another way to
5344 create the same list is ``pairs = [(v, k) for (k, v) in d.items()]``.
5345
5346 Iterating views while adding or deleting entries in the dictionary may raise
5347 a :exc:`RuntimeError` or fail to iterate over all entries.
5348
5349 .. versionchanged:: 3.7
5350 Dictionary order is guaranteed to be insertion order.
5351
5352 .. describe:: x in dictview
5353
5354 Return ``True`` if *x* is in the underlying dictionary's keys, values or
5355 items (in the latter case, *x* should be a ``(key, value)`` tuple).
5356
5357 .. describe:: reversed(dictview)
5358
5359 Return a reverse iterator over the keys, values or items of the dictionary.
5360 The view will be iterated in reverse order of the insertion.
5361
5362 .. versionchanged:: 3.8
5363 Dictionary views are now reversible.
5364
5365 .. describe:: dictview.mapping
5366
5367 Return a :class:`types.MappingProxyType` that wraps the original
5368 dictionary to which the view refers.
5369
5370 .. versionadded:: 3.10
5371
5372 Keys views are set-like since their entries are unique and :term:`hashable`.
5373 Items views also have set-like operations since the (key, value) pairs
5374 are unique and the keys are hashable.
5375 If all values in an items view are hashable as well,
5376 then the items view can interoperate with other sets.
5377 (Values views are not treated as set-like
5378 since the entries are generally not unique.) For set-like views, all of the
5379 operations defined for the abstract base class :class:`collections.abc.Set` are
5380 available (for example, ``==``, ``<``, or ``^``). While using set operators,
5381 set-like views accept any iterable as the other operand,
5382 unlike sets which only accept sets as the input.
5383
5384 An example of dictionary view usage::
5385
5386 >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
5387 >>> keys = dishes.keys()
5388 >>> values = dishes.values()
5389
5390 >>> # iteration
5391 >>> n = 0
5392 >>> for val in values:
5393 ... n += val
5394 ...
5395 >>> print(n)
5396 504
5397
5398 >>> # keys and values are iterated over in the same order (insertion order)
5399 >>> list(keys)
5400 ['eggs', 'sausage', 'bacon', 'spam']
5401 >>> list(values)
5402 [2, 1, 1, 500]
5403
5404 >>> # view objects are dynamic and reflect dict changes
5405 >>> del dishes['eggs']
5406 >>> del dishes['sausage']
5407 >>> list(keys)
5408 ['bacon', 'spam']
5409
5410 >>> # set operations
5411 >>> keys & {'eggs', 'bacon', 'salad'}
5412 {'bacon'}
5413 >>> keys ^ {'sausage', 'juice'} == {'juice', 'sausage', 'bacon', 'spam'}
5414 True
5415 >>> keys | ['juice', 'juice', 'juice'] == {'bacon', 'spam', 'juice'}
5416 True
5417
5418 >>> # get back a read-only proxy for the original dictionary
5419 >>> values.mapping
5420 mappingproxy({'bacon': 1, 'spam': 500})
5421 >>> values.mapping['spam']
5422 500
5423
5424
5425 .. _typecontextmanager:
5426
5427 Context Manager Types
5428 =====================
5429
5430 .. index::
5431 single: context manager
5432 single: context management protocol
5433 single: protocol; context management
5434
5435 Python's :keyword:`with` statement supports the concept of a runtime context
5436 defined by a context manager. This is implemented using a pair of methods
5437 that allow user-defined classes to define a runtime context that is entered
5438 before the statement body is executed and exited when the statement ends:
5439
5440
5441 .. method:: contextmanager.__enter__()
5442
5443 Enter the runtime context and return either this object or another object
5444 related to the runtime context. The value returned by this method is bound to
5445 the identifier in the :keyword:`!as` clause of :keyword:`with` statements using
5446 this context manager.
5447
5448 An example of a context manager that returns itself is a :term:`file object`.
5449 File objects return themselves from __enter__() to allow :func:`open` to be
5450 used as the context expression in a :keyword:`with` statement.
5451
5452 An example of a context manager that returns a related object is the one
5453 returned by :func:`decimal.localcontext`. These managers set the active
5454 decimal context to a copy of the original decimal context and then return the
5455 copy. This allows changes to be made to the current decimal context in the body
5456 of the :keyword:`with` statement without affecting code outside the
5457 :keyword:`!with` statement.
5458
5459
5460 .. method:: contextmanager.__exit__(exc_type, exc_val, exc_tb)
5461
5462 Exit the runtime context and return a Boolean flag indicating if any exception
5463 that occurred should be suppressed. If an exception occurred while executing the
5464 body of the :keyword:`with` statement, the arguments contain the exception type,
5465 value and traceback information. Otherwise, all three arguments are ``None``.
5466
5467 Returning a true value from this method will cause the :keyword:`with` statement
5468 to suppress the exception and continue execution with the statement immediately
5469 following the :keyword:`!with` statement. Otherwise the exception continues
5470 propagating after this method has finished executing.
5471
5472 If this method raises an exception while handling an earlier exception from the
5473 :keyword:`with` block, the new exception is raised, and the original exception
5474 is stored in its :attr:`~BaseException.__context__` attribute.
5475
5476 The exception passed in should never be reraised explicitly - instead, this
5477 method should return a false value to indicate that the method completed
5478 successfully and does not want to suppress the raised exception. This allows
5479 context management code to easily detect whether or not an :meth:`~object.__exit__`
5480 method has actually failed.
5481
5482 Python defines several context managers to support easy thread synchronisation,
5483 prompt closure of files or other objects, and simpler manipulation of the active
5484 decimal arithmetic context. The specific types are not treated specially beyond
5485 their implementation of the context management protocol. See the
5486 :mod:`contextlib` module for some examples.
5487
5488 Python's :term:`generator`\s and the :class:`contextlib.contextmanager` decorator
5489 provide a convenient way to implement these protocols. If a generator function is
5490 decorated with the :class:`contextlib.contextmanager` decorator, it will return a
5491 context manager implementing the necessary :meth:`~contextmanager.__enter__` and
5492 :meth:`~contextmanager.__exit__` methods, rather than the iterator produced by an
5493 undecorated generator function.
5494
5495 Note that there is no specific slot for any of these methods in the type
5496 structure for Python objects in the Python/C API. Extension types wanting to
5497 define these methods must provide them as a normal Python accessible method.
5498 Compared to the overhead of setting up the runtime context, the overhead of a
5499 single class dictionary lookup is negligible.
5500
5501
5502 Type Annotation Types --- :ref:`Generic Alias <types-genericalias>`, :ref:`Union <types-union>`
5503 ===============================================================================================
5504
5505 .. index::
5506 single: annotation; type annotation; type hint
5507
5508 The core built-in types for :term:`type annotations <annotation>` are
5509 :ref:`Generic Alias <types-genericalias>` and :ref:`Union <types-union>`.
5510
5511
5512 .. _types-genericalias:
5513
5514 Generic Alias Type
5515 ------------------
5516
5517 .. index::
5518 pair: object; GenericAlias
5519 pair: Generic; Alias
5520
5521 ``GenericAlias`` objects are generally created by
5522 :ref:`subscripting <subscriptions>` a class. They are most often used with
5523 :ref:`container classes <sequence-types>`, such as :class:`list` or
5524 :class:`dict`. For example, ``list[int]`` is a ``GenericAlias`` object created
5525 by subscripting the ``list`` class with the argument :class:`int`.
5526 ``GenericAlias`` objects are intended primarily for use with
5527 :term:`type annotations <annotation>`.
5528
5529 .. note::
5530
5531 It is generally only possible to subscript a class if the class implements
5532 the special method :meth:`~object.__class_getitem__`.
5533
5534 A ``GenericAlias`` object acts as a proxy for a :term:`generic type`,
5535 implementing *parameterized generics*.
5536
5537 For a container class, the
5538 argument(s) supplied to a :ref:`subscription <subscriptions>` of the class may
5539 indicate the type(s) of the elements an object contains. For example,
5540 ``set[bytes]`` can be used in type annotations to signify a :class:`set` in
5541 which all the elements are of type :class:`bytes`.
5542
5543 For a class which defines :meth:`~object.__class_getitem__` but is not a
5544 container, the argument(s) supplied to a subscription of the class will often
5545 indicate the return type(s) of one or more methods defined on an object. For
5546 example, :mod:`regular expressions <re>` can be used on both the :class:`str` data
5547 type and the :class:`bytes` data type:
5548
5549 * If ``x = re.search('foo', 'foo')``, ``x`` will be a
5550 :ref:`re.Match <match-objects>` object where the return values of
5551 ``x.group(0)`` and ``x[0]`` will both be of type :class:`str`. We can
5552 represent this kind of object in type annotations with the ``GenericAlias``
5553 ``re.Match[str]``.
5554
5555 * If ``y = re.search(b'bar', b'bar')``, (note the ``b`` for :class:`bytes`),
5556 ``y`` will also be an instance of ``re.Match``, but the return
5557 values of ``y.group(0)`` and ``y[0]`` will both be of type
5558 :class:`bytes`. In type annotations, we would represent this
5559 variety of :ref:`re.Match <match-objects>` objects with ``re.Match[bytes]``.
5560
5561 ``GenericAlias`` objects are instances of the class
5562 :class:`types.GenericAlias`, which can also be used to create ``GenericAlias``
5563 objects directly. Specializations of user-defined :ref:`generic classes <generic-classes>`
5564 may not be instances of :class:`types.GenericAlias`, but they provide similar functionality.
5565
5566 .. describe:: T[X, Y, ...]
5567
5568 Creates a ``GenericAlias`` representing a type ``T`` parameterized by types
5569 *X*, *Y*, and more depending on the ``T`` used.
5570 For example, a function expecting a :class:`list` containing
5571 :class:`float` elements::
5572
5573 def average(values: list[float]) -> float:
5574 return sum(values) / len(values)
5575
5576 Another example for :term:`mapping` objects, using a :class:`dict`, which
5577 is a generic type expecting two type parameters representing the key type
5578 and the value type. In this example, the function expects a ``dict`` with
5579 keys of type :class:`str` and values of type :class:`int`::
5580
5581 def send_post_request(url: str, body: dict[str, int]) -> None:
5582 ...
5583
5584 The builtin functions :func:`isinstance` and :func:`issubclass` do not accept
5585 ``GenericAlias`` types for their second argument::
5586
5587 >>> isinstance([1, 2], list[str])
5588 Traceback (most recent call last):
5589 File "<stdin>", line 1, in <module>
5590 TypeError: isinstance() argument 2 cannot be a parameterized generic
5591
5592 The Python runtime does not enforce :term:`type annotations <annotation>`.
5593 This extends to generic types and their type parameters. When creating
5594 a container object from a ``GenericAlias``, the elements in the container are not checked
5595 against their type. For example, the following code is discouraged, but will
5596 run without errors::
5597
5598 >>> t = list[str]
5599 >>> t([1, 2, 3])
5600 [1, 2, 3]
5601
5602 Furthermore, parameterized generics erase type parameters during object
5603 creation::
5604
5605 >>> t = list[str]
5606 >>> type(t)
5607 <class 'types.GenericAlias'>
5608
5609 >>> l = t()
5610 >>> type(l)
5611 <class 'list'>
5612
5613
5614 Instances of ``GenericAlias`` are not classes at runtime, even though they behave like classes (they can be instantiated and subclassed)::
5615
5616 >>> import inspect
5617 >>> inspect.isclass(list[int])
5618 False
5619
5620 This is true for :ref:`user-defined generics <user-defined-generics>` also.
5621
5622 Calling :func:`repr` or :func:`str` on a generic shows the parameterized type::
5623
5624 >>> repr(list[int])
5625 'list[int]'
5626
5627 >>> str(list[int])
5628 'list[int]'
5629
5630 The :meth:`~object.__getitem__` method of generic containers will raise an
5631 exception to disallow mistakes like ``dict[str][str]``::
5632
5633 >>> dict[str][str]
5634 Traceback (most recent call last):
5635 ...
5636 TypeError: dict[str] is not a generic class
5637
5638 However, such expressions are valid when :ref:`type variables <generics>` are
5639 used. The index must have as many elements as there are type variable items
5640 in the ``GenericAlias`` object's :attr:`~genericalias.__args__`. ::
5641
5642 >>> from typing import TypeVar
5643 >>> Y = TypeVar('Y')
5644 >>> dict[str, Y][int]
5645 dict[str, int]
5646
5647
5648 Standard Generic Classes
5649 ^^^^^^^^^^^^^^^^^^^^^^^^
5650
5651 The following standard library classes support parameterized generics. This
5652 list is non-exhaustive.
5653
5654 * :class:`tuple`
5655 * :class:`list`
5656 * :class:`dict`
5657 * :class:`set`
5658 * :class:`frozenset`
5659 * :class:`type`
5660 * :class:`asyncio.Future`
5661 * :class:`asyncio.Task`
5662 * :class:`collections.deque`
5663 * :class:`collections.defaultdict`
5664 * :class:`collections.OrderedDict`
5665 * :class:`collections.Counter`
5666 * :class:`collections.ChainMap`
5667 * :class:`collections.abc.Awaitable`
5668 * :class:`collections.abc.Coroutine`
5669 * :class:`collections.abc.AsyncIterable`
5670 * :class:`collections.abc.AsyncIterator`
5671 * :class:`collections.abc.AsyncGenerator`
5672 * :class:`collections.abc.Iterable`
5673 * :class:`collections.abc.Iterator`
5674 * :class:`collections.abc.Generator`
5675 * :class:`collections.abc.Reversible`
5676 * :class:`collections.abc.Container`
5677 * :class:`collections.abc.Collection`
5678 * :class:`collections.abc.Callable`
5679 * :class:`collections.abc.Set`
5680 * :class:`collections.abc.MutableSet`
5681 * :class:`collections.abc.Mapping`
5682 * :class:`collections.abc.MutableMapping`
5683 * :class:`collections.abc.Sequence`
5684 * :class:`collections.abc.MutableSequence`
5685 * :class:`collections.abc.ByteString`
5686 * :class:`collections.abc.MappingView`
5687 * :class:`collections.abc.KeysView`
5688 * :class:`collections.abc.ItemsView`
5689 * :class:`collections.abc.ValuesView`
5690 * :class:`contextlib.AbstractContextManager`
5691 * :class:`contextlib.AbstractAsyncContextManager`
5692 * :class:`dataclasses.Field`
5693 * :class:`functools.cached_property`
5694 * :class:`functools.partialmethod`
5695 * :class:`os.PathLike`
5696 * :class:`queue.LifoQueue`
5697 * :class:`queue.Queue`
5698 * :class:`queue.PriorityQueue`
5699 * :class:`queue.SimpleQueue`
5700 * :ref:`re.Pattern <re-objects>`
5701 * :ref:`re.Match <match-objects>`
5702 * :class:`shelve.BsdDbShelf`
5703 * :class:`shelve.DbfilenameShelf`
5704 * :class:`shelve.Shelf`
5705 * :class:`types.MappingProxyType`
5706 * :class:`weakref.WeakKeyDictionary`
5707 * :class:`weakref.WeakMethod`
5708 * :class:`weakref.WeakSet`
5709 * :class:`weakref.WeakValueDictionary`
5710
5711
5712
5713 Special Attributes of ``GenericAlias`` objects
5714 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
5715
5716 All parameterized generics implement special read-only attributes.
5717
5718 .. attribute:: genericalias.__origin__
5719
5720 This attribute points at the non-parameterized generic class::
5721
5722 >>> list[int].__origin__
5723 <class 'list'>
5724
5725
5726 .. attribute:: genericalias.__args__
5727
5728 This attribute is a :class:`tuple` (possibly of length 1) of generic
5729 types passed to the original :meth:`~object.__class_getitem__` of the
5730 generic class::
5731
5732 >>> dict[str, list[int]].__args__
5733 (<class 'str'>, list[int])
5734
5735
5736 .. attribute:: genericalias.__parameters__
5737
5738 This attribute is a lazily computed tuple (possibly empty) of unique type
5739 variables found in ``__args__``::
5740
5741 >>> from typing import TypeVar
5742
5743 >>> T = TypeVar('T')
5744 >>> list[T].__parameters__
5745 (~T,)
5746
5747
5748 .. note::
5749 A ``GenericAlias`` object with :class:`typing.ParamSpec` parameters may not
5750 have correct ``__parameters__`` after substitution because
5751 :class:`typing.ParamSpec` is intended primarily for static type checking.
5752
5753
5754 .. attribute:: genericalias.__unpacked__
5755
5756 A boolean that is true if the alias has been unpacked using the
5757 ``*`` operator (see :data:`~typing.TypeVarTuple`).
5758
5759 .. versionadded:: 3.11
5760
5761
5762 .. seealso::
5763
5764 :pep:`484` - Type Hints
5765 Introducing Python's framework for type annotations.
5766
5767 :pep:`585` - Type Hinting Generics In Standard Collections
5768 Introducing the ability to natively parameterize standard-library
5769 classes, provided they implement the special class method
5770 :meth:`~object.__class_getitem__`.
5771
5772 :ref:`Generics`, :ref:`user-defined generics <user-defined-generics>` and :class:`typing.Generic`
5773 Documentation on how to implement generic classes that can be
5774 parameterized at runtime and understood by static type-checkers.
5775
5776 .. versionadded:: 3.9
5777
5778
5779 .. _types-union:
5780
5781 Union Type
5782 ----------
5783
5784 .. index::
5785 pair: object; Union
5786 pair: union; type
5787
5788 A union object holds the value of the ``|`` (bitwise or) operation on
5789 multiple :ref:`type objects <bltin-type-objects>`. These types are intended
5790 primarily for :term:`type annotations <annotation>`. The union type expression
5791 enables cleaner type hinting syntax compared to :data:`typing.Union`.
5792
5793 .. describe:: X | Y | ...
5794
5795 Defines a union object which holds types *X*, *Y*, and so forth. ``X | Y``
5796 means either X or Y. It is equivalent to ``typing.Union[X, Y]``.
5797 For example, the following function expects an argument of type
5798 :class:`int` or :class:`float`::
5799
5800 def square(number: int | float) -> int | float:
5801 return number ** 2
5802
5803 .. note::
5804
5805 The ``|`` operand cannot be used at runtime to define unions where one or
5806 more members is a forward reference. For example, ``int | "Foo"``, where
5807 ``"Foo"`` is a reference to a class not yet defined, will fail at
5808 runtime. For unions which include forward references, present the
5809 whole expression as a string, e.g. ``"int | Foo"``.
5810
5811 .. describe:: union_object == other
5812
5813 Union objects can be tested for equality with other union objects. Details:
5814
5815 * Unions of unions are flattened::
5816
5817 (int | str) | float == int | str | float
5818
5819 * Redundant types are removed::
5820
5821 int | str | int == int | str
5822
5823 * When comparing unions, the order is ignored::
5824
5825 int | str == str | int
5826
5827 * It is compatible with :data:`typing.Union`::
5828
5829 int | str == typing.Union[int, str]
5830
5831 * Optional types can be spelled as a union with ``None``::
5832
5833 str | None == typing.Optional[str]
5834
5835 .. describe:: isinstance(obj, union_object)
5836 .. describe:: issubclass(obj, union_object)
5837
5838 Calls to :func:`isinstance` and :func:`issubclass` are also supported with a
5839 union object::
5840
5841 >>> isinstance("", int | str)
5842 True
5843
5844 However, :ref:`parameterized generics <types-genericalias>` in
5845 union objects cannot be checked::
5846
5847 >>> isinstance(1, int | list[int]) # short-circuit evaluation
5848 True
5849 >>> isinstance([1], int | list[int])
5850 Traceback (most recent call last):
5851 ...
5852 TypeError: isinstance() argument 2 cannot be a parameterized generic
5853
5854 The user-exposed type for the union object can be accessed from
5855 :data:`types.UnionType` and used for :func:`isinstance` checks. An object cannot be
5856 instantiated from the type::
5857
5858 >>> import types
5859 >>> isinstance(int | str, types.UnionType)
5860 True
5861 >>> types.UnionType()
5862 Traceback (most recent call last):
5863 File "<stdin>", line 1, in <module>
5864 TypeError: cannot create 'types.UnionType' instances
5865
5866 .. note::
5867 The :meth:`!__or__` method for type objects was added to support the syntax
5868 ``X | Y``. If a metaclass implements :meth:`!__or__`, the Union may
5869 override it:
5870
5871 .. doctest::
5872
5873 >>> class M(type):
5874 ... def __or__(self, other):
5875 ... return "Hello"
5876 ...
5877 >>> class C(metaclass=M):
5878 ... pass
5879 ...
5880 >>> C | int
5881 'Hello'
5882 >>> int | C
5883 int | C
5884
5885 .. seealso::
5886
5887 :pep:`604` -- PEP proposing the ``X | Y`` syntax and the Union type.
5888
5889 .. versionadded:: 3.10
5890
5891
5892 .. _typesother:
5893
5894 Other Built-in Types
5895 ====================
5896
5897 The interpreter supports several other kinds of objects. Most of these support
5898 only one or two operations.
5899
5900
5901 .. _typesmodules:
5902
5903 Modules
5904 -------
5905
5906 The only special operation on a module is attribute access: ``m.name``, where
5907 *m* is a module and *name* accesses a name defined in *m*'s symbol table.
5908 Module attributes can be assigned to. (Note that the :keyword:`import`
5909 statement is not, strictly speaking, an operation on a module object; ``import
5910 foo`` does not require a module object named *foo* to exist, rather it requires
5911 an (external) *definition* for a module named *foo* somewhere.)
5912
5913 A special attribute of every module is :attr:`~object.__dict__`. This is the
5914 dictionary containing the module's symbol table. Modifying this dictionary will
5915 actually change the module's symbol table, but direct assignment to the
5916 :attr:`~object.__dict__` attribute is not possible (you can write
5917 ``m.__dict__['a'] = 1``, which defines ``m.a`` to be ``1``, but you can't write
5918 ``m.__dict__ = {}``). Modifying :attr:`~object.__dict__` directly is
5919 not recommended.
5920
5921 Modules built into the interpreter are written like this: ``<module 'sys'
5922 (built-in)>``. If loaded from a file, they are written as ``<module 'os' from
5923 '/usr/local/lib/pythonX.Y/os.pyc'>``.
5924
5925
5926 .. _typesobjects:
5927
5928 Classes and Class Instances
5929 ---------------------------
5930
5931 See :ref:`objects` and :ref:`class` for these.
5932
5933
5934 .. _typesfunctions:
5935
5936 Functions
5937 ---------
5938
5939 Function objects are created by function definitions. The only operation on a
5940 function object is to call it: ``func(argument-list)``.
5941
5942 There are really two flavors of function objects: built-in functions and
5943 user-defined functions. Both support the same operation (to call the function),
5944 but the implementation is different, hence the different object types.
5945
5946 See :ref:`function` for more information.
5947
5948
5949 .. _typesmethods:
5950
5951 Methods
5952 -------
5953
5954 .. index:: pair: object; method
5955
5956 Methods are functions that are called using the attribute notation.
5957 There are two flavors: :ref:`built-in methods <builtin-methods>`
5958 (such as :meth:`~list.append` on lists)
5959 and :ref:`class instance method <instance-methods>`.
5960 Built-in methods are described with the types that support them.
5961
5962 If you access a method (a function defined in a class namespace) through an
5963 instance, you get a special object: a :dfn:`bound method` (also called
5964 :ref:`instance method <instance-methods>`) object. When called, it will add
5965 the ``self`` argument
5966 to the argument list. Bound methods have two special read-only attributes:
5967 :attr:`m.__self__ <method.__self__>` is the object on which the method
5968 operates, and :attr:`m.__func__ <method.__func__>` is
5969 the function implementing the method. Calling ``m(arg-1, arg-2, ..., arg-n)``
5970 is completely equivalent to calling ``m.__func__(m.__self__, arg-1, arg-2, ...,
5971 arg-n)``.
5972
5973 Like :ref:`function objects <user-defined-funcs>`, bound method objects support
5974 getting arbitrary
5975 attributes. However, since method attributes are actually stored on the
5976 underlying function object (:attr:`method.__func__`), setting method attributes on
5977 bound methods is disallowed. Attempting to set an attribute on a method
5978 results in an :exc:`AttributeError` being raised. In order to set a method
5979 attribute, you need to explicitly set it on the underlying function object:
5980
5981 .. doctest::
5982
5983 >>> class C:
5984 ... def method(self):
5985 ... pass
5986 ...
5987 >>> c = C()
5988 >>> c.method.whoami = 'my name is method' # can't set on the method
5989 Traceback (most recent call last):
5990 File "<stdin>", line 1, in <module>
5991 AttributeError: 'method' object has no attribute 'whoami'
5992 >>> c.method.__func__.whoami = 'my name is method'
5993 >>> c.method.whoami
5994 'my name is method'
5995
5996 See :ref:`instance-methods` for more information.
5997
5998
5999 .. index:: object; code, code object
6000
6001 .. _bltin-code-objects:
6002
6003 Code Objects
6004 ------------
6005
6006 .. index::
6007 pair: built-in function; compile
6008 single: __code__ (function object attribute)
6009
6010 Code objects are used by the implementation to represent "pseudo-compiled"
6011 executable Python code such as a function body. They differ from function
6012 objects because they don't contain a reference to their global execution
6013 environment. Code objects are returned by the built-in :func:`compile` function
6014 and can be extracted from function objects through their
6015 :attr:`~function.__code__` attribute. See also the :mod:`code` module.
6016
6017 Accessing :attr:`~function.__code__` raises an :ref:`auditing event <auditing>`
6018 ``object.__getattr__`` with arguments ``obj`` and ``"__code__"``.
6019
6020 .. index::
6021 pair: built-in function; exec
6022 pair: built-in function; eval
6023
6024 A code object can be executed or evaluated by passing it (instead of a source
6025 string) to the :func:`exec` or :func:`eval` built-in functions.
6026
6027 See :ref:`types` for more information.
6028
6029
6030 .. _bltin-type-objects:
6031
6032 Type Objects
6033 ------------
6034
6035 .. index::
6036 pair: built-in function; type
6037 pair: module; types
6038
6039 Type objects represent the various object types. An object's type is accessed
6040 by the built-in function :func:`type`. There are no special operations on
6041 types. The standard module :mod:`types` defines names for all standard built-in
6042 types.
6043
6044 Types are written like this: ``<class 'int'>``.
6045
6046
6047 .. _bltin-null-object:
6048
6049 The Null Object
6050 ---------------
6051
6052 This object is returned by functions that don't explicitly return a value. It
6053 supports no special operations. There is exactly one null object, named
6054 ``None`` (a built-in name). ``type(None)()`` produces the same singleton.
6055
6056 It is written as ``None``.
6057
6058
6059 .. index:: single: ...; ellipsis literal
6060 .. _bltin-ellipsis-object:
6061
6062 The Ellipsis Object
6063 -------------------
6064
6065 This object is commonly used to indicate that something is omitted.
6066 It supports no special operations. There is exactly one ellipsis object, named
6067 :const:`Ellipsis` (a built-in name). ``type(Ellipsis)()`` produces the
6068 :const:`Ellipsis` singleton.
6069
6070 It is written as ``Ellipsis`` or ``...``.
6071
6072 In typical use, ``...`` as the ``Ellipsis`` object appears in a few different
6073 places, for instance:
6074
6075 - In type annotations, such as :ref:`callable arguments <annotating-callables>`
6076 or :ref:`tuple elements <annotating-tuples>`.
6077
6078 - As the body of a function instead of a :ref:`pass statement <tut-pass>`.
6079
6080 - In third-party libraries, such as `Numpy's slicing and striding
6081 <https://numpy.org/doc/stable/user/basics.indexing.html#slicing-and-striding>`_.
6082
6083 Python also uses three dots in ways that are not ``Ellipsis`` objects, for instance:
6084
6085 - Doctest's :const:`ELLIPSIS <doctest.ELLIPSIS>`, as a pattern for missing content.
6086
6087 - The default Python prompt of the :term:`interactive` shell when partial input is incomplete.
6088
6089 Lastly, the Python documentation often uses three dots in conventional English
6090 usage to mean omitted content, even in code examples that also use them as the
6091 ``Ellipsis``.
6092
6093
6094 .. _bltin-notimplemented-object:
6095
6096 The NotImplemented Object
6097 -------------------------
6098
6099 This object is returned from comparisons and binary operations when they are
6100 asked to operate on types they don't support. See :ref:`comparisons` for more
6101 information. There is exactly one :data:`NotImplemented` object.
6102 :code:`type(NotImplemented)()` produces the singleton instance.
6103
6104 It is written as :code:`NotImplemented`.
6105
6106
6107 .. _typesinternal:
6108
6109 Internal Objects
6110 ----------------
6111
6112 See :ref:`types` for this information. It describes
6113 :ref:`stack frame objects <frame-objects>`,
6114 :ref:`traceback objects <traceback-objects>`, and slice objects.
6115
6116
6117 .. _specialattrs:
6118
6119 Special Attributes
6120 ==================
6121
6122 The implementation adds a few special read-only attributes to several object
6123 types, where they are relevant. Some of these are not reported by the
6124 :func:`dir` built-in function.
6125
6126
6127 .. attribute:: definition.__name__
6128
6129 The name of the class, function, method, descriptor, or
6130 generator instance.
6131
6132
6133 .. attribute:: definition.__qualname__
6134
6135 The :term:`qualified name` of the class, function, method, descriptor,
6136 or generator instance.
6137
6138 .. versionadded:: 3.3
6139
6140
6141 .. attribute:: definition.__module__
6142
6143 The name of the module in which a class or function was defined.
6144
6145
6146 .. attribute:: definition.__doc__
6147
6148 The documentation string of a class or function, or ``None`` if undefined.
6149
6150
6151 .. attribute:: definition.__type_params__
6152
6153 The :ref:`type parameters <type-params>` of generic classes, functions,
6154 and :ref:`type aliases <type-aliases>`. For classes and functions that
6155 are not generic, this will be an empty tuple.
6156
6157 .. versionadded:: 3.12
6158
6159
6160 .. _int_max_str_digits:
6161
6162 Integer string conversion length limitation
6163 ===========================================
6164
6165 CPython has a global limit for converting between :class:`int` and :class:`str`
6166 to mitigate denial of service attacks. This limit *only* applies to decimal or
6167 other non-power-of-two number bases. Hexadecimal, octal, and binary conversions
6168 are unlimited. The limit can be configured.
6169
6170 The :class:`int` type in CPython is an arbitrary length number stored in binary
6171 form (commonly known as a "bignum"). There exists no algorithm that can convert
6172 a string to a binary integer or a binary integer to a string in linear time,
6173 *unless* the base is a power of 2. Even the best known algorithms for base 10
6174 have sub-quadratic complexity. Converting a large value such as ``int('1' *
6175 500_000)`` can take over a second on a fast CPU.
6176
6177 Limiting conversion size offers a practical way to avoid :cve:`2020-10735`.
6178
6179 The limit is applied to the number of digit characters in the input or output
6180 string when a non-linear conversion algorithm would be involved. Underscores
6181 and the sign are not counted towards the limit.
6182
6183 When an operation would exceed the limit, a :exc:`ValueError` is raised:
6184
6185 .. doctest::
6186
6187 >>> import sys
6188 >>> sys.set_int_max_str_digits(4300) # Illustrative, this is the default.
6189 >>> _ = int('2' * 5432)
6190 Traceback (most recent call last):
6191 ...
6192 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
6193 >>> i = int('2' * 4300)
6194 >>> len(str(i))
6195 4300
6196 >>> i_squared = i*i
6197 >>> len(str(i_squared))
6198 Traceback (most recent call last):
6199 ...
6200 ValueError: Exceeds the limit (4300 digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit
6201 >>> len(hex(i_squared))
6202 7144
6203 >>> assert int(hex(i_squared), base=16) == i*i # Hexadecimal is unlimited.
6204
6205 The default limit is 4300 digits as provided in
6206 :data:`sys.int_info.default_max_str_digits <sys.int_info>`.
6207 The lowest limit that can be configured is 640 digits as provided in
6208 :data:`sys.int_info.str_digits_check_threshold <sys.int_info>`.
6209
6210 Verification:
6211
6212 .. doctest::
6213
6214 >>> import sys
6215 >>> assert sys.int_info.default_max_str_digits == 4300, sys.int_info
6216 >>> assert sys.int_info.str_digits_check_threshold == 640, sys.int_info
6217 >>> msg = int('578966293710682886880994035146873798396722250538762761564'
6218 ... '9252925514383915483333812743580549779436104706260696366600'
6219 ... '571186405732').to_bytes(53, 'big')
6220 ...
6221
6222 .. versionadded:: 3.11
6223
6224 Affected APIs
6225 -------------
6226
6227 The limitation only applies to potentially slow conversions between :class:`int`
6228 and :class:`str` or :class:`bytes`:
6229
6230 * ``int(string)`` with default base 10.
6231 * ``int(string, base)`` for all bases that are not a power of 2.
6232 * ``str(integer)``.
6233 * ``repr(integer)``.
6234 * any other string conversion to base 10, for example ``f"{integer}"``,
6235 ``"{}".format(integer)``, or ``b"%d" % integer``.
6236
6237 The limitations do not apply to functions with a linear algorithm:
6238
6239 * ``int(string, base)`` with base 2, 4, 8, 16, or 32.
6240 * :func:`int.from_bytes` and :func:`int.to_bytes`.
6241 * :func:`hex`, :func:`oct`, :func:`bin`.
6242 * :ref:`formatspec` for hex, octal, and binary numbers.
6243 * :class:`str` to :class:`float`.
6244 * :class:`str` to :class:`decimal.Decimal`.
6245
6246 Configuring the limit
6247 ---------------------
6248
6249 Before Python starts up you can use an environment variable or an interpreter
6250 command line flag to configure the limit:
6251
6252 * :envvar:`PYTHONINTMAXSTRDIGITS`, e.g.
6253 ``PYTHONINTMAXSTRDIGITS=640 python3`` to set the limit to 640 or
6254 ``PYTHONINTMAXSTRDIGITS=0 python3`` to disable the limitation.
6255 * :option:`-X int_max_str_digits <-X>`, e.g.
6256 ``python3 -X int_max_str_digits=640``
6257 * :data:`sys.flags.int_max_str_digits` contains the value of
6258 :envvar:`PYTHONINTMAXSTRDIGITS` or :option:`-X int_max_str_digits <-X>`.
6259 If both the env var and the ``-X`` option are set, the ``-X`` option takes
6260 precedence. A value of *-1* indicates that both were unset, thus a value of
6261 :data:`sys.int_info.default_max_str_digits` was used during initialization.
6262
6263 From code, you can inspect the current limit and set a new one using these
6264 :mod:`sys` APIs:
6265
6266 * :func:`sys.get_int_max_str_digits` and :func:`sys.set_int_max_str_digits` are
6267 a getter and setter for the interpreter-wide limit. Subinterpreters have
6268 their own limit.
6269
6270 Information about the default and minimum can be found in :data:`sys.int_info`:
6271
6272 * :data:`sys.int_info.default_max_str_digits <sys.int_info>` is the compiled-in
6273 default limit.
6274 * :data:`sys.int_info.str_digits_check_threshold <sys.int_info>` is the lowest
6275 accepted value for the limit (other than 0 which disables it).
6276
6277 .. versionadded:: 3.11
6278
6279 .. caution::
6280
6281 Setting a low limit *can* lead to problems. While rare, code exists that
6282 contains integer constants in decimal in their source that exceed the
6283 minimum threshold. A consequence of setting the limit is that Python source
6284 code containing decimal integer literals longer than the limit will
6285 encounter an error during parsing, usually at startup time or import time or
6286 even at installation time - anytime an up to date ``.pyc`` does not already
6287 exist for the code. A workaround for source that contains such large
6288 constants is to convert them to ``0x`` hexadecimal form as it has no limit.
6289
6290 Test your application thoroughly if you use a low limit. Ensure your tests
6291 run with the limit set early via the environment or flag so that it applies
6292 during startup and even during any installation step that may invoke Python
6293 to precompile ``.py`` sources to ``.pyc`` files.
6294
6295 Recommended configuration
6296 -------------------------
6297
6298 The default :data:`sys.int_info.default_max_str_digits` is expected to be
6299 reasonable for most applications. If your application requires a different
6300 limit, set it from your main entry point using Python version agnostic code as
6301 these APIs were added in security patch releases in versions before 3.12.
6302
6303 Example::
6304
6305 >>> import sys
6306 >>> if hasattr(sys, "set_int_max_str_digits"):
6307 ... upper_bound = 68000
6308 ... lower_bound = 4004
6309 ... current_limit = sys.get_int_max_str_digits()
6310 ... if current_limit == 0 or current_limit > upper_bound:
6311 ... sys.set_int_max_str_digits(upper_bound)
6312 ... elif current_limit < lower_bound:
6313 ... sys.set_int_max_str_digits(lower_bound)
6314
6315 If you need to disable it entirely, set it to ``0``.
6316
6317
6318 .. rubric:: Footnotes
6319
6320 .. [1] Additional information on these special methods may be found in the Python
6321 Reference Manual (:ref:`customization`).
6322
6323 .. [2] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and
6324 similarly for tuples.
6325
6326 .. [3] They must have since the parser can't tell the type of the operands.
6327
6328 .. [4] Cased characters are those with general category property being one of
6329 "Lu" (Letter, uppercase), "Ll" (Letter, lowercase), or "Lt" (Letter, titlecase).
6330
6331 .. [5] To format only a tuple you should therefore provide a singleton tuple whose only
6332 element is the tuple to be formatted.