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