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