Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 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 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 13 | .. index:: pair: built-in; types |
| 14 | |
Antoine Pitrou | e231e39 | 2009-12-19 18:22:15 +0000 | [diff] [blame] | 15 | The principal built-in types are numerics, sequences, mappings, classes, |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 16 | instances and exceptions. |
| 17 | |
Georg Brandl | 388349a | 2011-10-08 18:32:40 +0200 | [diff] [blame] | 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 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 22 | Some operations are supported by several object types; in particular, |
Windson yang | 1aeba74 | 2018-09-14 12:50:18 +0800 | [diff] [blame] | 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. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 27 | |
| 28 | |
| 29 | .. _truth: |
| 30 | |
| 31 | Truth Value Testing |
| 32 | =================== |
| 33 | |
| 34 | .. index:: |
| 35 | statement: if |
| 36 | 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 |
Peter Thomassen | caa1280 | 2017-07-29 21:18:13 +0200 | [diff] [blame] | 42 | :keyword:`while` condition or as operand of the Boolean operations below. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 43 | |
| 44 | .. index:: single: true |
| 45 | |
Peter Thomassen | caa1280 | 2017-07-29 21:18:13 +0200 | [diff] [blame] | 46 | By default, an object is considered true unless its class defines either a |
| 47 | :meth:`__bool__` method that returns ``False`` or a :meth:`__len__` method that |
| 48 | returns zero, when called with the object. [1]_ Here are most of the built-in |
| 49 | objects considered false: |
| 50 | |
| 51 | .. index:: |
| 52 | single: None (Built-in object) |
| 53 | single: False (Built-in object) |
| 54 | |
| 55 | * constants defined to be false: ``None`` and ``False``. |
| 56 | |
| 57 | * zero of any numeric type: ``0``, ``0.0``, ``0j``, ``Decimal(0)``, |
| 58 | ``Fraction(0, 1)`` |
| 59 | |
| 60 | * empty sequences and collections: ``''``, ``()``, ``[]``, ``{}``, ``set()``, |
| 61 | ``range(0)`` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 62 | |
| 63 | .. index:: |
| 64 | operator: or |
| 65 | operator: and |
| 66 | single: False |
| 67 | single: True |
| 68 | |
| 69 | Operations and built-in functions that have a Boolean result always return ``0`` |
| 70 | or ``False`` for false and ``1`` or ``True`` for true, unless otherwise stated. |
| 71 | (Important exception: the Boolean operations ``or`` and ``and`` always return |
| 72 | one of their operands.) |
| 73 | |
| 74 | |
| 75 | .. _boolean: |
| 76 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 77 | Boolean Operations --- :keyword:`!and`, :keyword:`!or`, :keyword:`!not` |
| 78 | ======================================================================= |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 79 | |
| 80 | .. index:: pair: Boolean; operations |
| 81 | |
| 82 | These are the Boolean operations, ordered by ascending priority: |
| 83 | |
| 84 | +-------------+---------------------------------+-------+ |
| 85 | | Operation | Result | Notes | |
| 86 | +=============+=================================+=======+ |
| 87 | | ``x or y`` | if *x* is false, then *y*, else | \(1) | |
| 88 | | | *x* | | |
| 89 | +-------------+---------------------------------+-------+ |
| 90 | | ``x and y`` | if *x* is false, then *x*, else | \(2) | |
| 91 | | | *y* | | |
| 92 | +-------------+---------------------------------+-------+ |
| 93 | | ``not x`` | if *x* is false, then ``True``, | \(3) | |
| 94 | | | else ``False`` | | |
| 95 | +-------------+---------------------------------+-------+ |
| 96 | |
| 97 | .. index:: |
| 98 | operator: and |
| 99 | operator: or |
| 100 | operator: not |
| 101 | |
| 102 | Notes: |
| 103 | |
| 104 | (1) |
| 105 | This is a short-circuit operator, so it only evaluates the second |
Mariatta | 8eb531d | 2017-03-03 13:16:29 -0800 | [diff] [blame] | 106 | argument if the first one is false. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 107 | |
| 108 | (2) |
| 109 | This is a short-circuit operator, so it only evaluates the second |
Mariatta | 8eb531d | 2017-03-03 13:16:29 -0800 | [diff] [blame] | 110 | argument if the first one is true. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 111 | |
| 112 | (3) |
| 113 | ``not`` has a lower priority than non-Boolean operators, so ``not a == b`` is |
| 114 | interpreted as ``not (a == b)``, and ``a == not b`` is a syntax error. |
| 115 | |
| 116 | |
| 117 | .. _stdcomparisons: |
| 118 | |
| 119 | Comparisons |
| 120 | =========== |
| 121 | |
Alexandre Vassalotti | 6d3dfc3 | 2009-07-29 19:54:39 +0000 | [diff] [blame] | 122 | .. index:: |
| 123 | pair: chaining; comparisons |
| 124 | pair: operator; comparison |
| 125 | operator: == |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 126 | operator: < (less) |
Alexandre Vassalotti | 6d3dfc3 | 2009-07-29 19:54:39 +0000 | [diff] [blame] | 127 | operator: <= |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 128 | operator: > (greater) |
Alexandre Vassalotti | 6d3dfc3 | 2009-07-29 19:54:39 +0000 | [diff] [blame] | 129 | operator: >= |
| 130 | operator: != |
| 131 | operator: is |
| 132 | operator: is not |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 133 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 134 | There are eight comparison operations in Python. They all have the same |
| 135 | priority (which is higher than that of the Boolean operations). Comparisons can |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 136 | be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and |
| 137 | y <= z``, except that *y* is evaluated only once (but in both cases *z* is not |
| 138 | evaluated at all when ``x < y`` is found to be false). |
| 139 | |
| 140 | This table summarizes the comparison operations: |
| 141 | |
Georg Brandl | fd85516 | 2008-01-07 09:13:03 +0000 | [diff] [blame] | 142 | +------------+-------------------------+ |
| 143 | | Operation | Meaning | |
| 144 | +============+=========================+ |
| 145 | | ``<`` | strictly less than | |
| 146 | +------------+-------------------------+ |
| 147 | | ``<=`` | less than or equal | |
| 148 | +------------+-------------------------+ |
| 149 | | ``>`` | strictly greater than | |
| 150 | +------------+-------------------------+ |
| 151 | | ``>=`` | greater than or equal | |
| 152 | +------------+-------------------------+ |
| 153 | | ``==`` | equal | |
| 154 | +------------+-------------------------+ |
| 155 | | ``!=`` | not equal | |
| 156 | +------------+-------------------------+ |
| 157 | | ``is`` | object identity | |
| 158 | +------------+-------------------------+ |
| 159 | | ``is not`` | negated object identity | |
| 160 | +------------+-------------------------+ |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 161 | |
| 162 | .. index:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 163 | pair: object; numeric |
| 164 | pair: objects; comparing |
| 165 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 166 | Objects of different types, except different numeric types, never compare equal. |
Windson yang | 1aeba74 | 2018-09-14 12:50:18 +0800 | [diff] [blame] | 167 | The ``==`` operator is always defined but for some object types (for example, |
| 168 | class objects) is equivalent to :keyword:`is`. The ``<``, ``<=``, ``>`` and ``>=`` |
| 169 | operators are only defined where they make sense; for example, they raise a |
| 170 | :exc:`TypeError` exception when one of the arguments is a complex number. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 171 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 172 | .. index:: |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 173 | single: __eq__() (instance method) |
| 174 | single: __ne__() (instance method) |
| 175 | single: __lt__() (instance method) |
| 176 | single: __le__() (instance method) |
| 177 | single: __gt__() (instance method) |
| 178 | single: __ge__() (instance method) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 179 | |
Georg Brandl | 05f5ab7 | 2008-09-24 09:11:47 +0000 | [diff] [blame] | 180 | Non-identical instances of a class normally compare as non-equal unless the |
| 181 | class defines the :meth:`__eq__` method. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 182 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 183 | Instances of a class cannot be ordered with respect to other instances of the |
| 184 | same class, or other types of object, unless the class defines enough of the |
Georg Brandl | 05f5ab7 | 2008-09-24 09:11:47 +0000 | [diff] [blame] | 185 | methods :meth:`__lt__`, :meth:`__le__`, :meth:`__gt__`, and :meth:`__ge__` (in |
| 186 | general, :meth:`__lt__` and :meth:`__eq__` are sufficient, if you want the |
| 187 | conventional meanings of the comparison operators). |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 188 | |
| 189 | The behavior of the :keyword:`is` and :keyword:`is not` operators cannot be |
| 190 | customized; also they can be applied to any two objects and never raise an |
| 191 | exception. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 192 | |
| 193 | .. index:: |
| 194 | operator: in |
| 195 | operator: not in |
| 196 | |
Georg Brandl | 375aec2 | 2011-01-15 17:03:02 +0000 | [diff] [blame] | 197 | Two more operations with the same syntactic priority, :keyword:`in` and |
wim glenn | 08bcf64 | 2018-09-11 12:44:52 -0500 | [diff] [blame] | 198 | :keyword:`not in`, are supported by types that are :term:`iterable` or |
| 199 | implement the :meth:`__contains__` method. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 200 | |
| 201 | .. _typesnumeric: |
| 202 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 203 | Numeric Types --- :class:`int`, :class:`float`, :class:`complex` |
| 204 | ================================================================ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 205 | |
| 206 | .. index:: |
| 207 | object: numeric |
| 208 | object: Boolean |
| 209 | object: integer |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 210 | object: floating point |
| 211 | object: complex number |
| 212 | pair: C; language |
| 213 | |
Mark Summerfield | bbfd71d | 2008-07-01 15:50:04 +0000 | [diff] [blame] | 214 | There are three distinct numeric types: :dfn:`integers`, :dfn:`floating |
| 215 | point numbers`, and :dfn:`complex numbers`. In addition, Booleans are a |
| 216 | subtype of integers. Integers have unlimited precision. Floating point |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 217 | numbers are usually implemented using :c:type:`double` in C; information |
Mark Dickinson | 74f5902 | 2010-08-04 18:42:43 +0000 | [diff] [blame] | 218 | about the precision and internal representation of floating point |
| 219 | numbers for the machine on which your program is running is available |
| 220 | in :data:`sys.float_info`. Complex numbers have a real and imaginary |
| 221 | part, which are each a floating point number. To extract these parts |
| 222 | from a complex number *z*, use ``z.real`` and ``z.imag``. (The standard |
Andre Delfino | 7804e8c | 2018-12-24 04:03:40 -0300 | [diff] [blame] | 223 | library includes the additional numeric types :mod:`fractions.Fraction`, for |
| 224 | rationals, and :mod:`decimal.Decimal`, for floating-point numbers with |
Mark Dickinson | 74f5902 | 2010-08-04 18:42:43 +0000 | [diff] [blame] | 225 | user-definable precision.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 226 | |
| 227 | .. index:: |
| 228 | pair: numeric; literals |
| 229 | pair: integer; literals |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 230 | pair: floating point; literals |
| 231 | pair: complex number; literals |
| 232 | pair: hexadecimal; literals |
| 233 | pair: octal; literals |
Neal Norwitz | 1d2aef5 | 2007-10-02 07:26:14 +0000 | [diff] [blame] | 234 | pair: binary; literals |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 235 | |
| 236 | Numbers are created by numeric literals or as the result of built-in functions |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 237 | and operators. Unadorned integer literals (including hex, octal and binary |
| 238 | numbers) yield integers. Numeric literals containing a decimal point or an |
| 239 | exponent sign yield floating point numbers. Appending ``'j'`` or ``'J'`` to a |
| 240 | numeric literal yields an imaginary number (a complex number with a zero real |
| 241 | part) which you can add to an integer or float to get a complex number with real |
| 242 | and imaginary parts. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 243 | |
| 244 | .. index:: |
| 245 | single: arithmetic |
| 246 | builtin: int |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 247 | builtin: float |
| 248 | builtin: complex |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 249 | single: operator; + (plus) |
| 250 | single: + (plus); unary operator |
| 251 | single: + (plus); binary operator |
| 252 | single: operator; - (minus) |
| 253 | single: - (minus); unary operator |
| 254 | single: - (minus); binary operator |
| 255 | operator: * (asterisk) |
| 256 | operator: / (slash) |
Alexandre Vassalotti | 6d3dfc3 | 2009-07-29 19:54:39 +0000 | [diff] [blame] | 257 | operator: // |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 258 | operator: % (percent) |
Alexandre Vassalotti | 6d3dfc3 | 2009-07-29 19:54:39 +0000 | [diff] [blame] | 259 | operator: ** |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 260 | |
| 261 | Python fully supports mixed arithmetic: when a binary arithmetic operator has |
| 262 | operands of different numeric types, the operand with the "narrower" type is |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 263 | widened to that of the other, where integer is narrower than floating point, |
| 264 | which is narrower than complex. Comparisons between numbers of mixed type use |
Ezio Melotti | 0656a56 | 2011-08-15 14:27:19 +0300 | [diff] [blame] | 265 | the same rule. [2]_ The constructors :func:`int`, :func:`float`, and |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 266 | :func:`complex` can be used to produce numbers of a specific type. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 267 | |
| 268 | All numeric types (except complex) support the following operations, sorted by |
Georg Brandl | e4196d3 | 2014-10-31 09:41:46 +0100 | [diff] [blame] | 269 | ascending priority (all numeric operations have a higher priority than |
| 270 | comparison operations): |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 271 | |
Raymond Hettinger | c706dbf | 2011-03-22 17:33:17 -0700 | [diff] [blame] | 272 | +---------------------+---------------------------------+---------+--------------------+ |
| 273 | | Operation | Result | Notes | Full documentation | |
| 274 | +=====================+=================================+=========+====================+ |
| 275 | | ``x + y`` | sum of *x* and *y* | | | |
| 276 | +---------------------+---------------------------------+---------+--------------------+ |
| 277 | | ``x - y`` | difference of *x* and *y* | | | |
| 278 | +---------------------+---------------------------------+---------+--------------------+ |
| 279 | | ``x * y`` | product of *x* and *y* | | | |
| 280 | +---------------------+---------------------------------+---------+--------------------+ |
| 281 | | ``x / y`` | quotient of *x* and *y* | | | |
| 282 | +---------------------+---------------------------------+---------+--------------------+ |
| 283 | | ``x // y`` | floored quotient of *x* and | \(1) | | |
| 284 | | | *y* | | | |
| 285 | +---------------------+---------------------------------+---------+--------------------+ |
| 286 | | ``x % y`` | remainder of ``x / y`` | \(2) | | |
| 287 | +---------------------+---------------------------------+---------+--------------------+ |
| 288 | | ``-x`` | *x* negated | | | |
| 289 | +---------------------+---------------------------------+---------+--------------------+ |
| 290 | | ``+x`` | *x* unchanged | | | |
| 291 | +---------------------+---------------------------------+---------+--------------------+ |
| 292 | | ``abs(x)`` | absolute value or magnitude of | | :func:`abs` | |
| 293 | | | *x* | | | |
| 294 | +---------------------+---------------------------------+---------+--------------------+ |
| 295 | | ``int(x)`` | *x* converted to integer | \(3)\(6)| :func:`int` | |
| 296 | +---------------------+---------------------------------+---------+--------------------+ |
| 297 | | ``float(x)`` | *x* converted to floating point | \(4)\(6)| :func:`float` | |
| 298 | +---------------------+---------------------------------+---------+--------------------+ |
| 299 | | ``complex(re, im)`` | a complex number with real part | \(6) | :func:`complex` | |
| 300 | | | *re*, imaginary part *im*. | | | |
| 301 | | | *im* defaults to zero. | | | |
| 302 | +---------------------+---------------------------------+---------+--------------------+ |
| 303 | | ``c.conjugate()`` | conjugate of the complex number | | | |
| 304 | | | *c* | | | |
| 305 | +---------------------+---------------------------------+---------+--------------------+ |
| 306 | | ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | \(2) | :func:`divmod` | |
| 307 | +---------------------+---------------------------------+---------+--------------------+ |
| 308 | | ``pow(x, y)`` | *x* to the power *y* | \(5) | :func:`pow` | |
| 309 | +---------------------+---------------------------------+---------+--------------------+ |
| 310 | | ``x ** y`` | *x* to the power *y* | \(5) | | |
| 311 | +---------------------+---------------------------------+---------+--------------------+ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 312 | |
| 313 | .. index:: |
| 314 | triple: operations on; numeric; types |
| 315 | single: conjugate() (complex number method) |
| 316 | |
| 317 | Notes: |
| 318 | |
| 319 | (1) |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 320 | Also referred to as integer division. The resultant value is a whole |
| 321 | integer, though the result's type is not necessarily int. The result is |
| 322 | always rounded towards minus infinity: ``1//2`` is ``0``, ``(-1)//2`` is |
| 323 | ``-1``, ``1//(-2)`` is ``-1``, and ``(-1)//(-2)`` is ``0``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 324 | |
| 325 | (2) |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 326 | Not for complex numbers. Instead convert to floats using :func:`abs` if |
| 327 | appropriate. |
| 328 | |
| 329 | (3) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 330 | .. index:: |
| 331 | module: math |
| 332 | single: floor() (in module math) |
| 333 | single: ceil() (in module math) |
Benjamin Peterson | 28d88b4 | 2009-01-09 03:03:23 +0000 | [diff] [blame] | 334 | single: trunc() (in module math) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 335 | pair: numeric; conversions |
| 336 | pair: C; language |
| 337 | |
Georg Brandl | ba956ae | 2007-11-29 17:24:34 +0000 | [diff] [blame] | 338 | Conversion from floating point to integer may round or truncate |
Serhiy Storchaka | 0d196ed | 2013-10-09 14:02:31 +0300 | [diff] [blame] | 339 | as in C; see functions :func:`math.floor` and :func:`math.ceil` for |
| 340 | well-defined conversions. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 341 | |
Georg Brandl | 74f3669 | 2008-01-06 17:39:49 +0000 | [diff] [blame] | 342 | (4) |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 343 | float also accepts the strings "nan" and "inf" with an optional prefix "+" |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 344 | or "-" for Not a Number (NaN) and positive or negative infinity. |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 345 | |
Georg Brandl | 74f3669 | 2008-01-06 17:39:49 +0000 | [diff] [blame] | 346 | (5) |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 347 | Python defines ``pow(0, 0)`` and ``0 ** 0`` to be ``1``, as is common for |
| 348 | programming languages. |
| 349 | |
Raymond Hettinger | c706dbf | 2011-03-22 17:33:17 -0700 | [diff] [blame] | 350 | (6) |
| 351 | The numeric literals accepted include the digits ``0`` to ``9`` or any |
| 352 | Unicode equivalent (code points with the ``Nd`` property). |
| 353 | |
Benjamin Peterson | 3aca40d | 2019-05-08 20:59:35 -0700 | [diff] [blame] | 354 | See http://www.unicode.org/Public/12.1.0/ucd/extracted/DerivedNumericType.txt |
Raymond Hettinger | c706dbf | 2011-03-22 17:33:17 -0700 | [diff] [blame] | 355 | for a complete list of code points with the ``Nd`` property. |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 356 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 357 | |
Benjamin Peterson | 10116d4 | 2011-05-01 17:38:17 -0500 | [diff] [blame] | 358 | All :class:`numbers.Real` types (:class:`int` and :class:`float`) also include |
| 359 | the following operations: |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 360 | |
Martin Panter | 129fe04 | 2016-05-08 12:22:37 +0000 | [diff] [blame] | 361 | +--------------------+---------------------------------------------+ |
| 362 | | Operation | Result | |
| 363 | +====================+=============================================+ |
| 364 | | :func:`math.trunc(\| *x* truncated to :class:`~numbers.Integral` | |
| 365 | | x) <math.trunc>` | | |
| 366 | +--------------------+---------------------------------------------+ |
| 367 | | :func:`round(x[, | *x* rounded to *n* digits, | |
| 368 | | n]) <round>` | rounding half to even. If *n* is | |
| 369 | | | omitted, it defaults to 0. | |
| 370 | +--------------------+---------------------------------------------+ |
| 371 | | :func:`math.floor(\| the greatest :class:`~numbers.Integral` | |
| 372 | | x) <math.floor>` | <= *x* | |
| 373 | +--------------------+---------------------------------------------+ |
| 374 | | :func:`math.ceil(x)| the least :class:`~numbers.Integral` >= *x* | |
| 375 | | <math.ceil>` | | |
| 376 | +--------------------+---------------------------------------------+ |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 377 | |
Mark Summerfield | bbfd71d | 2008-07-01 15:50:04 +0000 | [diff] [blame] | 378 | For additional numeric operations see the :mod:`math` and :mod:`cmath` |
| 379 | modules. |
| 380 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 381 | .. XXXJH exceptions: overflow (when? what operations?) zerodivision |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 382 | |
| 383 | |
| 384 | .. _bitstring-ops: |
| 385 | |
Benjamin Peterson | e9fca25 | 2012-01-25 16:29:03 -0500 | [diff] [blame] | 386 | Bitwise Operations on Integer Types |
Sanyam Khurana | b4bc5ca | 2018-07-28 10:45:50 +0530 | [diff] [blame] | 387 | ----------------------------------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 388 | |
Alexandre Vassalotti | 6d3dfc3 | 2009-07-29 19:54:39 +0000 | [diff] [blame] | 389 | .. index:: |
| 390 | triple: operations on; integer; types |
Benjamin Peterson | e9fca25 | 2012-01-25 16:29:03 -0500 | [diff] [blame] | 391 | pair: bitwise; operations |
Alexandre Vassalotti | 6d3dfc3 | 2009-07-29 19:54:39 +0000 | [diff] [blame] | 392 | pair: shifting; operations |
| 393 | pair: masking; operations |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 394 | operator: | (vertical bar) |
| 395 | operator: ^ (caret) |
| 396 | operator: & (ampersand) |
Alexandre Vassalotti | 6d3dfc3 | 2009-07-29 19:54:39 +0000 | [diff] [blame] | 397 | operator: << |
| 398 | operator: >> |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 399 | operator: ~ (tilde) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 400 | |
Sanyam Khurana | b4bc5ca | 2018-07-28 10:45:50 +0530 | [diff] [blame] | 401 | Bitwise operations only make sense for integers. The result of bitwise |
| 402 | operations is calculated as though carried out in two's complement with an |
| 403 | infinite number of sign bits. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 404 | |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 405 | The priorities of the binary bitwise operations are all lower than the numeric |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 406 | operations and higher than the comparisons; the unary operation ``~`` has the |
| 407 | same priority as the other unary numeric operations (``+`` and ``-``). |
| 408 | |
Georg Brandl | e4196d3 | 2014-10-31 09:41:46 +0100 | [diff] [blame] | 409 | This table lists the bitwise operations sorted in ascending priority: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 410 | |
| 411 | +------------+--------------------------------+----------+ |
| 412 | | Operation | Result | Notes | |
| 413 | +============+================================+==========+ |
Andrés Delfino | 2e5d2ea | 2018-08-25 11:08:20 -0300 | [diff] [blame] | 414 | | ``x | y`` | bitwise :dfn:`or` of *x* and | \(4) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 415 | | | *y* | | |
| 416 | +------------+--------------------------------+----------+ |
Andrés Delfino | 2e5d2ea | 2018-08-25 11:08:20 -0300 | [diff] [blame] | 417 | | ``x ^ y`` | bitwise :dfn:`exclusive or` of | \(4) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 418 | | | *x* and *y* | | |
| 419 | +------------+--------------------------------+----------+ |
Andrés Delfino | 2e5d2ea | 2018-08-25 11:08:20 -0300 | [diff] [blame] | 420 | | ``x & y`` | bitwise :dfn:`and` of *x* and | \(4) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 421 | | | *y* | | |
| 422 | +------------+--------------------------------+----------+ |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 423 | | ``x << n`` | *x* shifted left by *n* bits | (1)(2) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 424 | +------------+--------------------------------+----------+ |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 425 | | ``x >> n`` | *x* shifted right by *n* bits | (1)(3) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 426 | +------------+--------------------------------+----------+ |
| 427 | | ``~x`` | the bits of *x* inverted | | |
| 428 | +------------+--------------------------------+----------+ |
| 429 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 430 | Notes: |
| 431 | |
| 432 | (1) |
| 433 | Negative shift counts are illegal and cause a :exc:`ValueError` to be raised. |
| 434 | |
| 435 | (2) |
| 436 | A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)`` |
| 437 | without overflow check. |
| 438 | |
| 439 | (3) |
| 440 | A right shift by *n* bits is equivalent to division by ``pow(2, n)`` without |
| 441 | overflow check. |
| 442 | |
Sanyam Khurana | b4bc5ca | 2018-07-28 10:45:50 +0530 | [diff] [blame] | 443 | (4) |
| 444 | Performing these calculations with at least one extra sign extension bit in |
| 445 | a finite two's complement representation (a working bit-width of |
Andre Delfino | 55f41e4 | 2018-12-05 16:45:30 -0300 | [diff] [blame] | 446 | ``1 + max(x.bit_length(), y.bit_length())`` or more) is sufficient to get the |
Sanyam Khurana | b4bc5ca | 2018-07-28 10:45:50 +0530 | [diff] [blame] | 447 | same result as if there were an infinite number of sign bits. |
| 448 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 449 | |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame] | 450 | Additional Methods on Integer Types |
| 451 | ----------------------------------- |
| 452 | |
Raymond Hettinger | 9b2fd32 | 2011-05-01 18:14:49 -0700 | [diff] [blame] | 453 | The int type implements the :class:`numbers.Integral` :term:`abstract base |
Georg Brandl | e4196d3 | 2014-10-31 09:41:46 +0100 | [diff] [blame] | 454 | class`. In addition, it provides a few more methods: |
Benjamin Peterson | 10116d4 | 2011-05-01 17:38:17 -0500 | [diff] [blame] | 455 | |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame] | 456 | .. method:: int.bit_length() |
| 457 | |
Raymond Hettinger | d3e18b7 | 2008-12-19 09:11:49 +0000 | [diff] [blame] | 458 | Return the number of bits necessary to represent an integer in binary, |
| 459 | excluding the sign and leading zeros:: |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame] | 460 | |
Raymond Hettinger | d3e18b7 | 2008-12-19 09:11:49 +0000 | [diff] [blame] | 461 | >>> n = -37 |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame] | 462 | >>> bin(n) |
Raymond Hettinger | d3e18b7 | 2008-12-19 09:11:49 +0000 | [diff] [blame] | 463 | '-0b100101' |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame] | 464 | >>> n.bit_length() |
| 465 | 6 |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame] | 466 | |
Raymond Hettinger | d3e18b7 | 2008-12-19 09:11:49 +0000 | [diff] [blame] | 467 | More precisely, if ``x`` is nonzero, then ``x.bit_length()`` is the |
| 468 | unique positive integer ``k`` such that ``2**(k-1) <= abs(x) < 2**k``. |
| 469 | Equivalently, when ``abs(x)`` is small enough to have a correctly |
| 470 | rounded logarithm, then ``k = 1 + int(log(abs(x), 2))``. |
| 471 | If ``x`` is zero, then ``x.bit_length()`` returns ``0``. |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame] | 472 | |
| 473 | Equivalent to:: |
| 474 | |
| 475 | def bit_length(self): |
Senthil Kumaran | 0aae6dc | 2010-06-22 02:57:23 +0000 | [diff] [blame] | 476 | s = bin(self) # binary representation: bin(-37) --> '-0b100101' |
Raymond Hettinger | d3e18b7 | 2008-12-19 09:11:49 +0000 | [diff] [blame] | 477 | s = s.lstrip('-0b') # remove leading zeros and minus sign |
| 478 | return len(s) # len('100101') --> 6 |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame] | 479 | |
| 480 | .. versionadded:: 3.1 |
| 481 | |
Georg Brandl | 67b21b7 | 2010-08-17 15:07:14 +0000 | [diff] [blame] | 482 | .. method:: int.to_bytes(length, byteorder, \*, signed=False) |
Alexandre Vassalotti | c36c378 | 2010-01-09 20:35:09 +0000 | [diff] [blame] | 483 | |
| 484 | Return an array of bytes representing an integer. |
| 485 | |
| 486 | >>> (1024).to_bytes(2, byteorder='big') |
| 487 | b'\x04\x00' |
| 488 | >>> (1024).to_bytes(10, byteorder='big') |
| 489 | b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' |
| 490 | >>> (-1024).to_bytes(10, byteorder='big', signed=True) |
| 491 | b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' |
| 492 | >>> x = 1000 |
INADA Naoki | 3e3e9f3 | 2016-10-31 17:41:47 +0900 | [diff] [blame] | 493 | >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') |
Alexandre Vassalotti | c36c378 | 2010-01-09 20:35:09 +0000 | [diff] [blame] | 494 | b'\xe8\x03' |
| 495 | |
| 496 | The integer is represented using *length* bytes. An :exc:`OverflowError` |
| 497 | is raised if the integer is not representable with the given number of |
| 498 | bytes. |
| 499 | |
| 500 | The *byteorder* argument determines the byte order used to represent the |
| 501 | integer. If *byteorder* is ``"big"``, the most significant byte is at the |
| 502 | beginning of the byte array. If *byteorder* is ``"little"``, the most |
| 503 | significant byte is at the end of the byte array. To request the native |
| 504 | byte order of the host system, use :data:`sys.byteorder` as the byte order |
| 505 | value. |
| 506 | |
| 507 | The *signed* argument determines whether two's complement is used to |
| 508 | represent the integer. If *signed* is ``False`` and a negative integer is |
| 509 | given, an :exc:`OverflowError` is raised. The default value for *signed* |
| 510 | is ``False``. |
| 511 | |
| 512 | .. versionadded:: 3.2 |
| 513 | |
Georg Brandl | 67b21b7 | 2010-08-17 15:07:14 +0000 | [diff] [blame] | 514 | .. classmethod:: int.from_bytes(bytes, byteorder, \*, signed=False) |
Alexandre Vassalotti | c36c378 | 2010-01-09 20:35:09 +0000 | [diff] [blame] | 515 | |
| 516 | Return the integer represented by the given array of bytes. |
| 517 | |
| 518 | >>> int.from_bytes(b'\x00\x10', byteorder='big') |
| 519 | 16 |
| 520 | >>> int.from_bytes(b'\x00\x10', byteorder='little') |
| 521 | 4096 |
| 522 | >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) |
| 523 | -1024 |
| 524 | >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) |
| 525 | 64512 |
| 526 | >>> int.from_bytes([255, 0, 0], byteorder='big') |
| 527 | 16711680 |
| 528 | |
Ezio Melotti | c228e96 | 2013-05-04 18:06:34 +0300 | [diff] [blame] | 529 | The argument *bytes* must either be a :term:`bytes-like object` or an |
| 530 | iterable producing bytes. |
Alexandre Vassalotti | c36c378 | 2010-01-09 20:35:09 +0000 | [diff] [blame] | 531 | |
| 532 | The *byteorder* argument determines the byte order used to represent the |
| 533 | integer. If *byteorder* is ``"big"``, the most significant byte is at the |
| 534 | beginning of the byte array. If *byteorder* is ``"little"``, the most |
| 535 | significant byte is at the end of the byte array. To request the native |
| 536 | byte order of the host system, use :data:`sys.byteorder` as the byte order |
| 537 | value. |
| 538 | |
| 539 | The *signed* argument indicates whether two's complement is used to |
| 540 | represent the integer. |
| 541 | |
| 542 | .. versionadded:: 3.2 |
| 543 | |
Lisa Roach | 5ac7043 | 2018-09-13 23:56:23 -0700 | [diff] [blame] | 544 | .. method:: int.as_integer_ratio() |
| 545 | |
| 546 | Return a pair of integers whose ratio is exactly equal to the original |
| 547 | integer and with a positive denominator. The integer ratio of integers |
| 548 | (whole numbers) is always the integer as the numerator and ``1`` as the |
| 549 | denominator. |
| 550 | |
| 551 | .. versionadded:: 3.8 |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame] | 552 | |
Mark Dickinson | 65fe25e | 2008-07-16 11:30:51 +0000 | [diff] [blame] | 553 | Additional Methods on Float |
| 554 | --------------------------- |
| 555 | |
Benjamin Peterson | 10116d4 | 2011-05-01 17:38:17 -0500 | [diff] [blame] | 556 | The float type implements the :class:`numbers.Real` :term:`abstract base |
| 557 | class`. float also has the following additional methods. |
Benjamin Peterson | d7b0328 | 2008-09-13 15:58:53 +0000 | [diff] [blame] | 558 | |
| 559 | .. method:: float.as_integer_ratio() |
| 560 | |
Mark Dickinson | 4a3c7c4 | 2010-11-07 12:48:18 +0000 | [diff] [blame] | 561 | Return a pair of integers whose ratio is exactly equal to the |
| 562 | original float and with a positive denominator. Raises |
| 563 | :exc:`OverflowError` on infinities and a :exc:`ValueError` on |
| 564 | NaNs. |
| 565 | |
| 566 | .. method:: float.is_integer() |
| 567 | |
| 568 | Return ``True`` if the float instance is finite with integral |
| 569 | value, and ``False`` otherwise:: |
| 570 | |
| 571 | >>> (-2.0).is_integer() |
| 572 | True |
| 573 | >>> (3.2).is_integer() |
| 574 | False |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 575 | |
Benjamin Peterson | d7b0328 | 2008-09-13 15:58:53 +0000 | [diff] [blame] | 576 | Two methods support conversion to |
Mark Dickinson | 65fe25e | 2008-07-16 11:30:51 +0000 | [diff] [blame] | 577 | and from hexadecimal strings. Since Python's floats are stored |
| 578 | internally as binary numbers, converting a float to or from a |
| 579 | *decimal* string usually involves a small rounding error. In |
| 580 | contrast, hexadecimal strings allow exact representation and |
| 581 | specification of floating-point numbers. This can be useful when |
| 582 | debugging, and in numerical work. |
| 583 | |
| 584 | |
| 585 | .. method:: float.hex() |
| 586 | |
| 587 | Return a representation of a floating-point number as a hexadecimal |
| 588 | string. For finite floating-point numbers, this representation |
| 589 | will always include a leading ``0x`` and a trailing ``p`` and |
| 590 | exponent. |
| 591 | |
| 592 | |
Georg Brandl | abc3877 | 2009-04-12 15:51:51 +0000 | [diff] [blame] | 593 | .. classmethod:: float.fromhex(s) |
Mark Dickinson | 65fe25e | 2008-07-16 11:30:51 +0000 | [diff] [blame] | 594 | |
| 595 | Class method to return the float represented by a hexadecimal |
| 596 | string *s*. The string *s* may have leading and trailing |
| 597 | whitespace. |
| 598 | |
| 599 | |
| 600 | Note that :meth:`float.hex` is an instance method, while |
| 601 | :meth:`float.fromhex` is a class method. |
| 602 | |
| 603 | A hexadecimal string takes the form:: |
| 604 | |
| 605 | [sign] ['0x'] integer ['.' fraction] ['p' exponent] |
| 606 | |
| 607 | where the optional ``sign`` may by either ``+`` or ``-``, ``integer`` |
| 608 | and ``fraction`` are strings of hexadecimal digits, and ``exponent`` |
| 609 | is a decimal integer with an optional leading sign. Case is not |
| 610 | significant, and there must be at least one hexadecimal digit in |
| 611 | either the integer or the fraction. This syntax is similar to the |
| 612 | syntax specified in section 6.4.4.2 of the C99 standard, and also to |
| 613 | the syntax used in Java 1.5 onwards. In particular, the output of |
| 614 | :meth:`float.hex` is usable as a hexadecimal floating-point literal in |
| 615 | C or Java code, and hexadecimal strings produced by C's ``%a`` format |
| 616 | character or Java's ``Double.toHexString`` are accepted by |
| 617 | :meth:`float.fromhex`. |
| 618 | |
| 619 | |
| 620 | Note that the exponent is written in decimal rather than hexadecimal, |
| 621 | and that it gives the power of 2 by which to multiply the coefficient. |
| 622 | For example, the hexadecimal string ``0x3.a7p10`` represents the |
| 623 | floating-point number ``(3 + 10./16 + 7./16**2) * 2.0**10``, or |
| 624 | ``3740.0``:: |
| 625 | |
| 626 | >>> float.fromhex('0x3.a7p10') |
| 627 | 3740.0 |
| 628 | |
| 629 | |
| 630 | Applying the reverse conversion to ``3740.0`` gives a different |
| 631 | hexadecimal string representing the same number:: |
| 632 | |
| 633 | >>> float.hex(3740.0) |
| 634 | '0x1.d380000000000p+11' |
| 635 | |
| 636 | |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 637 | .. _numeric-hash: |
| 638 | |
| 639 | Hashing of numeric types |
| 640 | ------------------------ |
| 641 | |
| 642 | For numbers ``x`` and ``y``, possibly of different types, it's a requirement |
| 643 | that ``hash(x) == hash(y)`` whenever ``x == y`` (see the :meth:`__hash__` |
| 644 | method documentation for more details). For ease of implementation and |
| 645 | efficiency across a variety of numeric types (including :class:`int`, |
| 646 | :class:`float`, :class:`decimal.Decimal` and :class:`fractions.Fraction`) |
| 647 | Python's hash for numeric types is based on a single mathematical function |
| 648 | that's defined for any rational number, and hence applies to all instances of |
Serhiy Storchaka | 0d196ed | 2013-10-09 14:02:31 +0300 | [diff] [blame] | 649 | :class:`int` and :class:`fractions.Fraction`, and all finite instances of |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 650 | :class:`float` and :class:`decimal.Decimal`. Essentially, this function is |
| 651 | given by reduction modulo ``P`` for a fixed prime ``P``. The value of ``P`` is |
| 652 | made available to Python as the :attr:`modulus` attribute of |
| 653 | :data:`sys.hash_info`. |
| 654 | |
| 655 | .. impl-detail:: |
| 656 | |
| 657 | Currently, the prime used is ``P = 2**31 - 1`` on machines with 32-bit C |
| 658 | longs and ``P = 2**61 - 1`` on machines with 64-bit C longs. |
| 659 | |
| 660 | Here are the rules in detail: |
| 661 | |
Georg Brandl | 226ed7e | 2012-03-24 08:12:41 +0100 | [diff] [blame] | 662 | - If ``x = m / n`` is a nonnegative rational number and ``n`` is not divisible |
| 663 | by ``P``, define ``hash(x)`` as ``m * invmod(n, P) % P``, where ``invmod(n, |
| 664 | P)`` gives the inverse of ``n`` modulo ``P``. |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 665 | |
Georg Brandl | 226ed7e | 2012-03-24 08:12:41 +0100 | [diff] [blame] | 666 | - If ``x = m / n`` is a nonnegative rational number and ``n`` is |
| 667 | divisible by ``P`` (but ``m`` is not) then ``n`` has no inverse |
| 668 | modulo ``P`` and the rule above doesn't apply; in this case define |
| 669 | ``hash(x)`` to be the constant value ``sys.hash_info.inf``. |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 670 | |
Georg Brandl | 226ed7e | 2012-03-24 08:12:41 +0100 | [diff] [blame] | 671 | - If ``x = m / n`` is a negative rational number define ``hash(x)`` |
| 672 | as ``-hash(-x)``. If the resulting hash is ``-1``, replace it with |
| 673 | ``-2``. |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 674 | |
Georg Brandl | 226ed7e | 2012-03-24 08:12:41 +0100 | [diff] [blame] | 675 | - The particular values ``sys.hash_info.inf``, ``-sys.hash_info.inf`` |
| 676 | and ``sys.hash_info.nan`` are used as hash values for positive |
| 677 | infinity, negative infinity, or nans (respectively). (All hashable |
| 678 | nans have the same hash value.) |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 679 | |
Georg Brandl | 226ed7e | 2012-03-24 08:12:41 +0100 | [diff] [blame] | 680 | - For a :class:`complex` number ``z``, the hash values of the real |
| 681 | and imaginary parts are combined by computing ``hash(z.real) + |
| 682 | sys.hash_info.imag * hash(z.imag)``, reduced modulo |
| 683 | ``2**sys.hash_info.width`` so that it lies in |
| 684 | ``range(-2**(sys.hash_info.width - 1), 2**(sys.hash_info.width - |
| 685 | 1))``. Again, if the result is ``-1``, it's replaced with ``-2``. |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 686 | |
| 687 | |
| 688 | To clarify the above rules, here's some example Python code, |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 689 | equivalent to the built-in hash, for computing the hash of a rational |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 690 | number, :class:`float`, or :class:`complex`:: |
| 691 | |
| 692 | |
| 693 | import sys, math |
| 694 | |
| 695 | def hash_fraction(m, n): |
| 696 | """Compute the hash of a rational number m / n. |
| 697 | |
| 698 | Assumes m and n are integers, with n positive. |
| 699 | Equivalent to hash(fractions.Fraction(m, n)). |
| 700 | |
| 701 | """ |
| 702 | P = sys.hash_info.modulus |
| 703 | # Remove common factors of P. (Unnecessary if m and n already coprime.) |
| 704 | while m % P == n % P == 0: |
| 705 | m, n = m // P, n // P |
| 706 | |
| 707 | if n % P == 0: |
Berker Peksag | aa46bd4 | 2016-07-25 04:55:51 +0300 | [diff] [blame] | 708 | hash_value = sys.hash_info.inf |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 709 | else: |
| 710 | # Fermat's Little Theorem: pow(n, P-1, P) is 1, so |
| 711 | # pow(n, P-2, P) gives the inverse of n modulo P. |
Berker Peksag | aa46bd4 | 2016-07-25 04:55:51 +0300 | [diff] [blame] | 712 | hash_value = (abs(m) % P) * pow(n, P - 2, P) % P |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 713 | if m < 0: |
Berker Peksag | aa46bd4 | 2016-07-25 04:55:51 +0300 | [diff] [blame] | 714 | hash_value = -hash_value |
| 715 | if hash_value == -1: |
| 716 | hash_value = -2 |
| 717 | return hash_value |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 718 | |
| 719 | def hash_float(x): |
| 720 | """Compute the hash of a float x.""" |
| 721 | |
| 722 | if math.isnan(x): |
| 723 | return sys.hash_info.nan |
| 724 | elif math.isinf(x): |
| 725 | return sys.hash_info.inf if x > 0 else -sys.hash_info.inf |
| 726 | else: |
| 727 | return hash_fraction(*x.as_integer_ratio()) |
| 728 | |
| 729 | def hash_complex(z): |
| 730 | """Compute the hash of a complex number z.""" |
| 731 | |
Berker Peksag | aa46bd4 | 2016-07-25 04:55:51 +0300 | [diff] [blame] | 732 | hash_value = hash_float(z.real) + sys.hash_info.imag * hash_float(z.imag) |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 733 | # do a signed reduction modulo 2**sys.hash_info.width |
| 734 | M = 2**(sys.hash_info.width - 1) |
Berker Peksag | aa46bd4 | 2016-07-25 04:55:51 +0300 | [diff] [blame] | 735 | hash_value = (hash_value & (M - 1)) - (hash_value & M) |
| 736 | if hash_value == -1: |
| 737 | hash_value = -2 |
| 738 | return hash_value |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 739 | |
Georg Brandl | 6ea420b | 2008-07-16 12:58:29 +0000 | [diff] [blame] | 740 | .. _typeiter: |
| 741 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 742 | Iterator Types |
| 743 | ============== |
| 744 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 745 | .. index:: |
| 746 | single: iterator protocol |
| 747 | single: protocol; iterator |
| 748 | single: sequence; iteration |
| 749 | single: container; iteration over |
| 750 | |
| 751 | Python supports a concept of iteration over containers. This is implemented |
| 752 | using two distinct methods; these are used to allow user-defined classes to |
| 753 | support iteration. Sequences, described below in more detail, always support |
| 754 | the iteration methods. |
| 755 | |
| 756 | One method needs to be defined for container objects to provide iteration |
| 757 | support: |
| 758 | |
Christian Heimes | 790c823 | 2008-01-07 21:14:23 +0000 | [diff] [blame] | 759 | .. XXX duplicated in reference/datamodel! |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 760 | |
Christian Heimes | 790c823 | 2008-01-07 21:14:23 +0000 | [diff] [blame] | 761 | .. method:: container.__iter__() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 762 | |
| 763 | Return an iterator object. The object is required to support the iterator |
| 764 | protocol described below. If a container supports different types of |
| 765 | iteration, additional methods can be provided to specifically request |
| 766 | iterators for those iteration types. (An example of an object supporting |
| 767 | multiple forms of iteration would be a tree structure which supports both |
| 768 | breadth-first and depth-first traversal.) This method corresponds to the |
Antoine Pitrou | 39668f5 | 2013-08-01 21:12:45 +0200 | [diff] [blame] | 769 | :c:member:`~PyTypeObject.tp_iter` slot of the type structure for Python objects in the Python/C |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 770 | API. |
| 771 | |
| 772 | The iterator objects themselves are required to support the following two |
| 773 | methods, which together form the :dfn:`iterator protocol`: |
| 774 | |
| 775 | |
| 776 | .. method:: iterator.__iter__() |
| 777 | |
| 778 | Return the iterator object itself. This is required to allow both containers |
| 779 | and iterators to be used with the :keyword:`for` and :keyword:`in` statements. |
Antoine Pitrou | 39668f5 | 2013-08-01 21:12:45 +0200 | [diff] [blame] | 780 | This method corresponds to the :c:member:`~PyTypeObject.tp_iter` slot of the type structure for |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 781 | Python objects in the Python/C API. |
| 782 | |
| 783 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 784 | .. method:: iterator.__next__() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 785 | |
| 786 | Return the next item from the container. If there are no further items, raise |
| 787 | the :exc:`StopIteration` exception. This method corresponds to the |
Antoine Pitrou | 39668f5 | 2013-08-01 21:12:45 +0200 | [diff] [blame] | 788 | :c:member:`~PyTypeObject.tp_iternext` slot of the type structure for Python objects in the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 789 | Python/C API. |
| 790 | |
| 791 | Python defines several iterator objects to support iteration over general and |
| 792 | specific sequence types, dictionaries, and other more specialized forms. The |
| 793 | specific types are not important beyond their implementation of the iterator |
| 794 | protocol. |
| 795 | |
Ezio Melotti | 7fa8222 | 2012-10-12 13:42:08 +0300 | [diff] [blame] | 796 | Once an iterator's :meth:`~iterator.__next__` method raises |
| 797 | :exc:`StopIteration`, it must continue to do so on subsequent calls. |
| 798 | Implementations that do not obey this property are deemed broken. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 799 | |
Benjamin Peterson | 0289b15 | 2009-06-28 17:22:03 +0000 | [diff] [blame] | 800 | |
| 801 | .. _generator-types: |
| 802 | |
| 803 | Generator Types |
| 804 | --------------- |
| 805 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 806 | Python's :term:`generator`\s provide a convenient way to implement the iterator |
| 807 | protocol. If a container object's :meth:`__iter__` method is implemented as a |
| 808 | generator, it will automatically return an iterator object (technically, a |
Ezio Melotti | 7fa8222 | 2012-10-12 13:42:08 +0300 | [diff] [blame] | 809 | generator object) supplying the :meth:`__iter__` and :meth:`~generator.__next__` |
| 810 | methods. |
Benjamin Peterson | 0289b15 | 2009-06-28 17:22:03 +0000 | [diff] [blame] | 811 | More information about generators can be found in :ref:`the documentation for |
| 812 | the yield expression <yieldexpr>`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 813 | |
| 814 | |
| 815 | .. _typesseq: |
| 816 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 817 | Sequence Types --- :class:`list`, :class:`tuple`, :class:`range` |
| 818 | ================================================================ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 819 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 820 | There are three basic sequence types: lists, tuples, and range objects. |
| 821 | Additional sequence types tailored for processing of |
| 822 | :ref:`binary data <binaryseq>` and :ref:`text strings <textseq>` are |
| 823 | described in dedicated sections. |
Georg Brandl | e17d586 | 2009-01-18 10:40:25 +0000 | [diff] [blame] | 824 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 825 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 826 | .. _typesseq-common: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 827 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 828 | Common Sequence Operations |
| 829 | -------------------------- |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 830 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 831 | .. index:: object: sequence |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 832 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 833 | The operations in the following table are supported by most sequence types, |
| 834 | both mutable and immutable. The :class:`collections.abc.Sequence` ABC is |
| 835 | provided to make it easier to correctly implement these operations on |
| 836 | custom sequence types. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 837 | |
Georg Brandl | e4196d3 | 2014-10-31 09:41:46 +0100 | [diff] [blame] | 838 | This table lists the sequence operations sorted in ascending priority. In the |
| 839 | table, *s* and *t* are sequences of the same type, *n*, *i*, *j* and *k* are |
| 840 | integers and *x* is an arbitrary object that meets any type and value |
| 841 | restrictions imposed by *s*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 842 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 843 | The ``in`` and ``not in`` operations have the same priorities as the |
| 844 | comparison operations. The ``+`` (concatenation) and ``*`` (repetition) |
Serhiy Storchaka | d97b7dc | 2017-05-16 23:18:09 +0300 | [diff] [blame] | 845 | operations have the same priority as the corresponding numeric operations. [3]_ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 846 | |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 847 | .. index:: |
| 848 | triple: operations on; sequence; types |
| 849 | builtin: len |
| 850 | builtin: min |
| 851 | builtin: max |
| 852 | pair: concatenation; operation |
| 853 | pair: repetition; operation |
| 854 | pair: subscript; operation |
| 855 | pair: slice; operation |
| 856 | operator: in |
| 857 | operator: not in |
| 858 | single: count() (sequence method) |
| 859 | single: index() (sequence method) |
| 860 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 861 | +--------------------------+--------------------------------+----------+ |
| 862 | | Operation | Result | Notes | |
| 863 | +==========================+================================+==========+ |
| 864 | | ``x in s`` | ``True`` if an item of *s* is | \(1) | |
| 865 | | | equal to *x*, else ``False`` | | |
| 866 | +--------------------------+--------------------------------+----------+ |
| 867 | | ``x not in s`` | ``False`` if an item of *s* is | \(1) | |
| 868 | | | equal to *x*, else ``True`` | | |
| 869 | +--------------------------+--------------------------------+----------+ |
| 870 | | ``s + t`` | the concatenation of *s* and | (6)(7) | |
| 871 | | | *t* | | |
| 872 | +--------------------------+--------------------------------+----------+ |
Martin Panter | 7f02d6d | 2015-09-07 02:08:55 +0000 | [diff] [blame] | 873 | | ``s * n`` or | equivalent to adding *s* to | (2)(7) | |
| 874 | | ``n * s`` | itself *n* times | | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 875 | +--------------------------+--------------------------------+----------+ |
| 876 | | ``s[i]`` | *i*\ th item of *s*, origin 0 | \(3) | |
| 877 | +--------------------------+--------------------------------+----------+ |
| 878 | | ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) | |
| 879 | +--------------------------+--------------------------------+----------+ |
| 880 | | ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) | |
| 881 | | | with step *k* | | |
| 882 | +--------------------------+--------------------------------+----------+ |
| 883 | | ``len(s)`` | length of *s* | | |
| 884 | +--------------------------+--------------------------------+----------+ |
| 885 | | ``min(s)`` | smallest item of *s* | | |
| 886 | +--------------------------+--------------------------------+----------+ |
| 887 | | ``max(s)`` | largest item of *s* | | |
| 888 | +--------------------------+--------------------------------+----------+ |
Ned Deily | 0995c47 | 2013-07-14 12:43:16 -0700 | [diff] [blame] | 889 | | ``s.index(x[, i[, j]])`` | index of the first occurrence | \(8) | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 890 | | | of *x* in *s* (at or after | | |
| 891 | | | index *i* and before index *j*)| | |
| 892 | +--------------------------+--------------------------------+----------+ |
Ned Deily | 0995c47 | 2013-07-14 12:43:16 -0700 | [diff] [blame] | 893 | | ``s.count(x)`` | total number of occurrences of | | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 894 | | | *x* in *s* | | |
| 895 | +--------------------------+--------------------------------+----------+ |
| 896 | |
| 897 | Sequences of the same type also support comparisons. In particular, tuples |
| 898 | and lists are compared lexicographically by comparing corresponding elements. |
| 899 | This means that to compare equal, every element must compare equal and the |
| 900 | two sequences must be of the same type and have the same length. (For full |
| 901 | details see :ref:`comparisons` in the language reference.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 902 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 903 | Notes: |
| 904 | |
| 905 | (1) |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 906 | While the ``in`` and ``not in`` operations are used only for simple |
| 907 | containment testing in the general case, some specialised sequences |
| 908 | (such as :class:`str`, :class:`bytes` and :class:`bytearray`) also use |
| 909 | them for subsequence testing:: |
| 910 | |
| 911 | >>> "gg" in "eggs" |
| 912 | True |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 913 | |
| 914 | (2) |
| 915 | Values of *n* less than ``0`` are treated as ``0`` (which yields an empty |
Martin Panter | 7f02d6d | 2015-09-07 02:08:55 +0000 | [diff] [blame] | 916 | sequence of the same type as *s*). Note that items in the sequence *s* |
| 917 | are not copied; they are referenced multiple times. This often haunts |
| 918 | new Python programmers; consider:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 919 | |
| 920 | >>> lists = [[]] * 3 |
| 921 | >>> lists |
| 922 | [[], [], []] |
| 923 | >>> lists[0].append(3) |
| 924 | >>> lists |
| 925 | [[3], [3], [3]] |
| 926 | |
| 927 | What has happened is that ``[[]]`` is a one-element list containing an empty |
Martin Panter | 7f02d6d | 2015-09-07 02:08:55 +0000 | [diff] [blame] | 928 | list, so all three elements of ``[[]] * 3`` are references to this single empty |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 929 | list. Modifying any of the elements of ``lists`` modifies this single list. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 930 | You can create a list of different lists this way:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 931 | |
| 932 | >>> lists = [[] for i in range(3)] |
| 933 | >>> lists[0].append(3) |
| 934 | >>> lists[1].append(5) |
| 935 | >>> lists[2].append(7) |
| 936 | >>> lists |
| 937 | [[3], [5], [7]] |
| 938 | |
Martin Panter | 7f02d6d | 2015-09-07 02:08:55 +0000 | [diff] [blame] | 939 | Further explanation is available in the FAQ entry |
| 940 | :ref:`faq-multidimensional-list`. |
| 941 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 942 | (3) |
Xiang Zhang | cea904f | 2016-12-30 11:57:09 +0800 | [diff] [blame] | 943 | If *i* or *j* is negative, the index is relative to the end of sequence *s*: |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 944 | ``len(s) + i`` or ``len(s) + j`` is substituted. But note that ``-0`` is |
| 945 | still ``0``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 946 | |
| 947 | (4) |
| 948 | The slice of *s* from *i* to *j* is defined as the sequence of items with index |
| 949 | *k* such that ``i <= k < j``. If *i* or *j* is greater than ``len(s)``, use |
| 950 | ``len(s)``. If *i* is omitted or ``None``, use ``0``. If *j* is omitted or |
| 951 | ``None``, use ``len(s)``. If *i* is greater than or equal to *j*, the slice is |
| 952 | empty. |
| 953 | |
| 954 | (5) |
| 955 | The slice of *s* from *i* to *j* with step *k* is defined as the sequence of |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 956 | items with index ``x = i + n*k`` such that ``0 <= n < (j-i)/k``. In other words, |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 957 | the indices are ``i``, ``i+k``, ``i+2*k``, ``i+3*k`` and so on, stopping when |
Martin Panter | 3dbd87f | 2016-12-24 08:25:15 +0000 | [diff] [blame] | 958 | *j* is reached (but never including *j*). When *k* is positive, |
| 959 | *i* and *j* are reduced to ``len(s)`` if they are greater. |
| 960 | When *k* is negative, *i* and *j* are reduced to ``len(s) - 1`` if |
| 961 | they are greater. If *i* or *j* are omitted or ``None``, they become |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 962 | "end" values (which end depends on the sign of *k*). Note, *k* cannot be zero. |
| 963 | If *k* is ``None``, it is treated like ``1``. |
| 964 | |
| 965 | (6) |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 966 | Concatenating immutable sequences always results in a new object. This |
| 967 | means that building up a sequence by repeated concatenation will have a |
| 968 | quadratic runtime cost in the total sequence length. To get a linear |
| 969 | runtime cost, you must switch to one of the alternatives below: |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 970 | |
Antoine Pitrou | fd9ebd4 | 2011-11-25 16:33:53 +0100 | [diff] [blame] | 971 | * if concatenating :class:`str` objects, you can build a list and use |
Martin Panter | 7462b649 | 2015-11-02 03:37:02 +0000 | [diff] [blame] | 972 | :meth:`str.join` at the end or else write to an :class:`io.StringIO` |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 973 | instance and retrieve its value when complete |
Antoine Pitrou | fd9ebd4 | 2011-11-25 16:33:53 +0100 | [diff] [blame] | 974 | |
| 975 | * if concatenating :class:`bytes` objects, you can similarly use |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 976 | :meth:`bytes.join` or :class:`io.BytesIO`, or you can do in-place |
| 977 | concatenation with a :class:`bytearray` object. :class:`bytearray` |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 978 | objects are mutable and have an efficient overallocation mechanism |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 979 | |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 980 | * if concatenating :class:`tuple` objects, extend a :class:`list` instead |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 981 | |
| 982 | * for other types, investigate the relevant class documentation |
| 983 | |
| 984 | |
| 985 | (7) |
| 986 | Some sequence types (such as :class:`range`) only support item sequences |
| 987 | that follow specific patterns, and hence don't support sequence |
| 988 | concatenation or repetition. |
| 989 | |
| 990 | (8) |
| 991 | ``index`` raises :exc:`ValueError` when *x* is not found in *s*. |
Nitish Chandra | 5ce0a2a | 2017-12-12 15:52:30 +0530 | [diff] [blame] | 992 | Not all implementations support passing the additional arguments *i* and *j*. |
| 993 | These arguments allow efficient searching of subsections of the sequence. Passing |
| 994 | the extra arguments is roughly equivalent to using ``s[i:j].index(x)``, only |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 995 | without copying any data and with the returned index being relative to |
| 996 | the start of the sequence rather than the start of the slice. |
| 997 | |
| 998 | |
| 999 | .. _typesseq-immutable: |
| 1000 | |
| 1001 | Immutable Sequence Types |
| 1002 | ------------------------ |
| 1003 | |
| 1004 | .. index:: |
| 1005 | triple: immutable; sequence; types |
| 1006 | object: tuple |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1007 | builtin: hash |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1008 | |
| 1009 | The only operation that immutable sequence types generally implement that is |
| 1010 | not also implemented by mutable sequence types is support for the :func:`hash` |
| 1011 | built-in. |
| 1012 | |
| 1013 | This support allows immutable sequences, such as :class:`tuple` instances, to |
| 1014 | be used as :class:`dict` keys and stored in :class:`set` and :class:`frozenset` |
| 1015 | instances. |
| 1016 | |
| 1017 | Attempting to hash an immutable sequence that contains unhashable values will |
| 1018 | result in :exc:`TypeError`. |
| 1019 | |
| 1020 | |
| 1021 | .. _typesseq-mutable: |
| 1022 | |
| 1023 | Mutable Sequence Types |
| 1024 | ---------------------- |
| 1025 | |
| 1026 | .. index:: |
| 1027 | triple: mutable; sequence; types |
| 1028 | object: list |
| 1029 | object: bytearray |
| 1030 | |
| 1031 | The operations in the following table are defined on mutable sequence types. |
| 1032 | The :class:`collections.abc.MutableSequence` ABC is provided to make it |
| 1033 | easier to correctly implement these operations on custom sequence types. |
| 1034 | |
| 1035 | In the table *s* is an instance of a mutable sequence type, *t* is any |
| 1036 | iterable object and *x* is an arbitrary object that meets any type |
| 1037 | and value restrictions imposed by *s* (for example, :class:`bytearray` only |
| 1038 | accepts integers that meet the value restriction ``0 <= x <= 255``). |
| 1039 | |
| 1040 | |
| 1041 | .. index:: |
| 1042 | triple: operations on; sequence; types |
| 1043 | triple: operations on; list; type |
| 1044 | pair: subscript; assignment |
| 1045 | pair: slice; assignment |
| 1046 | statement: del |
| 1047 | single: append() (sequence method) |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1048 | single: clear() (sequence method) |
| 1049 | single: copy() (sequence method) |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1050 | single: extend() (sequence method) |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1051 | single: insert() (sequence method) |
| 1052 | single: pop() (sequence method) |
| 1053 | single: remove() (sequence method) |
| 1054 | single: reverse() (sequence method) |
| 1055 | |
| 1056 | +------------------------------+--------------------------------+---------------------+ |
| 1057 | | Operation | Result | Notes | |
| 1058 | +==============================+================================+=====================+ |
| 1059 | | ``s[i] = x`` | item *i* of *s* is replaced by | | |
| 1060 | | | *x* | | |
| 1061 | +------------------------------+--------------------------------+---------------------+ |
| 1062 | | ``s[i:j] = t`` | slice of *s* from *i* to *j* | | |
| 1063 | | | is replaced by the contents of | | |
| 1064 | | | the iterable *t* | | |
| 1065 | +------------------------------+--------------------------------+---------------------+ |
| 1066 | | ``del s[i:j]`` | same as ``s[i:j] = []`` | | |
| 1067 | +------------------------------+--------------------------------+---------------------+ |
| 1068 | | ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` | \(1) | |
| 1069 | | | are replaced by those of *t* | | |
| 1070 | +------------------------------+--------------------------------+---------------------+ |
| 1071 | | ``del s[i:j:k]`` | removes the elements of | | |
| 1072 | | | ``s[i:j:k]`` from the list | | |
| 1073 | +------------------------------+--------------------------------+---------------------+ |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1074 | | ``s.append(x)`` | appends *x* to the end of the | | |
| 1075 | | | sequence (same as | | |
| 1076 | | | ``s[len(s):len(s)] = [x]``) | | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1077 | +------------------------------+--------------------------------+---------------------+ |
Andrés Delfino | 2e5d2ea | 2018-08-25 11:08:20 -0300 | [diff] [blame] | 1078 | | ``s.clear()`` | removes all items from *s* | \(5) | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1079 | | | (same as ``del s[:]``) | | |
| 1080 | +------------------------------+--------------------------------+---------------------+ |
Andrés Delfino | 2e5d2ea | 2018-08-25 11:08:20 -0300 | [diff] [blame] | 1081 | | ``s.copy()`` | creates a shallow copy of *s* | \(5) | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1082 | | | (same as ``s[:]``) | | |
| 1083 | +------------------------------+--------------------------------+---------------------+ |
Martin Panter | 3795d12 | 2015-10-03 07:46:04 +0000 | [diff] [blame] | 1084 | | ``s.extend(t)`` or | extends *s* with the | | |
| 1085 | | ``s += t`` | contents of *t* (for the | | |
| 1086 | | | most part the same as | | |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1087 | | | ``s[len(s):len(s)] = t``) | | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1088 | +------------------------------+--------------------------------+---------------------+ |
Martin Panter | 3795d12 | 2015-10-03 07:46:04 +0000 | [diff] [blame] | 1089 | | ``s *= n`` | updates *s* with its contents | \(6) | |
| 1090 | | | repeated *n* times | | |
| 1091 | +------------------------------+--------------------------------+---------------------+ |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1092 | | ``s.insert(i, x)`` | inserts *x* into *s* at the | | |
| 1093 | | | index given by *i* | | |
| 1094 | | | (same as ``s[i:i] = [x]``) | | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1095 | +------------------------------+--------------------------------+---------------------+ |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1096 | | ``s.pop([i])`` | retrieves the item at *i* and | \(2) | |
| 1097 | | | also removes it from *s* | | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1098 | +------------------------------+--------------------------------+---------------------+ |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1099 | | ``s.remove(x)`` | remove the first item from *s* | \(3) | |
Xiang Zhang | b2d7717 | 2017-03-13 10:09:16 +0800 | [diff] [blame] | 1100 | | | where ``s[i]`` is equal to *x* | | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1101 | +------------------------------+--------------------------------+---------------------+ |
| 1102 | | ``s.reverse()`` | reverses the items of *s* in | \(4) | |
| 1103 | | | place | | |
| 1104 | +------------------------------+--------------------------------+---------------------+ |
| 1105 | |
| 1106 | |
| 1107 | Notes: |
| 1108 | |
| 1109 | (1) |
| 1110 | *t* must have the same length as the slice it is replacing. |
| 1111 | |
| 1112 | (2) |
| 1113 | The optional argument *i* defaults to ``-1``, so that by default the last |
| 1114 | item is removed and returned. |
| 1115 | |
| 1116 | (3) |
Jelle Zijlstra | 9892f45 | 2019-05-18 17:17:56 -0700 | [diff] [blame] | 1117 | :meth:`remove` raises :exc:`ValueError` when *x* is not found in *s*. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1118 | |
| 1119 | (4) |
| 1120 | The :meth:`reverse` method modifies the sequence in place for economy of |
| 1121 | space when reversing a large sequence. To remind users that it operates by |
| 1122 | side effect, it does not return the reversed sequence. |
| 1123 | |
| 1124 | (5) |
| 1125 | :meth:`clear` and :meth:`!copy` are included for consistency with the |
| 1126 | interfaces of mutable containers that don't support slicing operations |
Jelle Zijlstra | 9892f45 | 2019-05-18 17:17:56 -0700 | [diff] [blame] | 1127 | (such as :class:`dict` and :class:`set`). :meth:`!copy` is not part of the |
| 1128 | :class:`collections.abc.MutableSequence` ABC, but most concrete |
| 1129 | mutable sequence classes provide it. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1130 | |
| 1131 | .. versionadded:: 3.3 |
| 1132 | :meth:`clear` and :meth:`!copy` methods. |
| 1133 | |
Martin Panter | 3795d12 | 2015-10-03 07:46:04 +0000 | [diff] [blame] | 1134 | (6) |
| 1135 | The value *n* is an integer, or an object implementing |
| 1136 | :meth:`~object.__index__`. Zero and negative values of *n* clear |
| 1137 | the sequence. Items in the sequence are not copied; they are referenced |
| 1138 | multiple times, as explained for ``s * n`` under :ref:`typesseq-common`. |
| 1139 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1140 | |
| 1141 | .. _typesseq-list: |
| 1142 | |
| 1143 | Lists |
| 1144 | ----- |
| 1145 | |
| 1146 | .. index:: object: list |
| 1147 | |
| 1148 | Lists are mutable sequences, typically used to store collections of |
| 1149 | homogeneous items (where the precise degree of similarity will vary by |
| 1150 | application). |
| 1151 | |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1152 | .. class:: list([iterable]) |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1153 | |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1154 | Lists may be constructed in several ways: |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1155 | |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1156 | * Using a pair of square brackets to denote the empty list: ``[]`` |
| 1157 | * Using square brackets, separating items with commas: ``[a]``, ``[a, b, c]`` |
| 1158 | * Using a list comprehension: ``[x for x in iterable]`` |
| 1159 | * Using the type constructor: ``list()`` or ``list(iterable)`` |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1160 | |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1161 | The constructor builds a list whose items are the same and in the same |
| 1162 | order as *iterable*'s items. *iterable* may be either a sequence, a |
| 1163 | container that supports iteration, or an iterator object. If *iterable* |
| 1164 | is already a list, a copy is made and returned, similar to ``iterable[:]``. |
| 1165 | For example, ``list('abc')`` returns ``['a', 'b', 'c']`` and |
| 1166 | ``list( (1, 2, 3) )`` returns ``[1, 2, 3]``. |
| 1167 | If no argument is given, the constructor creates a new empty list, ``[]``. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1168 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1169 | |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1170 | Many other operations also produce lists, including the :func:`sorted` |
| 1171 | built-in. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1172 | |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1173 | Lists implement all of the :ref:`common <typesseq-common>` and |
| 1174 | :ref:`mutable <typesseq-mutable>` sequence operations. Lists also provide the |
| 1175 | following additional method: |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1176 | |
Łukasz Rogalski | be37beb | 2017-07-14 21:23:39 +0200 | [diff] [blame] | 1177 | .. method:: list.sort(*, key=None, reverse=False) |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1178 | |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1179 | This method sorts the list in place, using only ``<`` comparisons |
| 1180 | between items. Exceptions are not suppressed - if any comparison operations |
| 1181 | fail, the entire sort operation will fail (and the list will likely be left |
| 1182 | in a partially modified state). |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1183 | |
Zachary Ware | e1391a0 | 2013-11-22 13:58:34 -0600 | [diff] [blame] | 1184 | :meth:`sort` accepts two arguments that can only be passed by keyword |
| 1185 | (:ref:`keyword-only arguments <keyword-only_parameter>`): |
| 1186 | |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1187 | *key* specifies a function of one argument that is used to extract a |
| 1188 | comparison key from each list element (for example, ``key=str.lower``). |
| 1189 | The key corresponding to each item in the list is calculated once and |
| 1190 | then used for the entire sorting process. The default value of ``None`` |
| 1191 | means that list items are sorted directly without calculating a separate |
| 1192 | key value. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1193 | |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1194 | The :func:`functools.cmp_to_key` utility is available to convert a 2.x |
| 1195 | style *cmp* function to a *key* function. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1196 | |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1197 | *reverse* is a boolean value. If set to ``True``, then the list elements |
| 1198 | are sorted as if each comparison were reversed. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1199 | |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1200 | This method modifies the sequence in place for economy of space when |
| 1201 | sorting a large sequence. To remind users that it operates by side |
| 1202 | effect, it does not return the sorted sequence (use :func:`sorted` to |
| 1203 | explicitly request a new sorted list instance). |
| 1204 | |
| 1205 | The :meth:`sort` method is guaranteed to be stable. A sort is stable if it |
| 1206 | guarantees not to change the relative order of elements that compare equal |
| 1207 | --- this is helpful for sorting in multiple passes (for example, sort by |
| 1208 | department, then by salary grade). |
| 1209 | |
Xtreak | 890a4b9 | 2018-10-21 03:09:03 +0530 | [diff] [blame] | 1210 | For sorting examples and a brief sorting tutorial, see :ref:`sortinghowto`. |
| 1211 | |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1212 | .. impl-detail:: |
| 1213 | |
| 1214 | While a list is being sorted, the effect of attempting to mutate, or even |
| 1215 | inspect, the list is undefined. The C implementation of Python makes the |
| 1216 | list appear empty for the duration, and raises :exc:`ValueError` if it can |
| 1217 | detect that the list has been mutated during a sort. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1218 | |
| 1219 | |
| 1220 | .. _typesseq-tuple: |
| 1221 | |
| 1222 | Tuples |
| 1223 | ------ |
| 1224 | |
| 1225 | .. index:: object: tuple |
| 1226 | |
| 1227 | Tuples are immutable sequences, typically used to store collections of |
| 1228 | heterogeneous data (such as the 2-tuples produced by the :func:`enumerate` |
| 1229 | built-in). Tuples are also used for cases where an immutable sequence of |
| 1230 | homogeneous data is needed (such as allowing storage in a :class:`set` or |
| 1231 | :class:`dict` instance). |
| 1232 | |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1233 | .. class:: tuple([iterable]) |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1234 | |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1235 | Tuples may be constructed in a number of ways: |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1236 | |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1237 | * Using a pair of parentheses to denote the empty tuple: ``()`` |
| 1238 | * Using a trailing comma for a singleton tuple: ``a,`` or ``(a,)`` |
| 1239 | * Separating items with commas: ``a, b, c`` or ``(a, b, c)`` |
| 1240 | * Using the :func:`tuple` built-in: ``tuple()`` or ``tuple(iterable)`` |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1241 | |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1242 | The constructor builds a tuple whose items are the same and in the same |
| 1243 | order as *iterable*'s items. *iterable* may be either a sequence, a |
| 1244 | container that supports iteration, or an iterator object. If *iterable* |
| 1245 | is already a tuple, it is returned unchanged. For example, |
| 1246 | ``tuple('abc')`` returns ``('a', 'b', 'c')`` and |
| 1247 | ``tuple( [1, 2, 3] )`` returns ``(1, 2, 3)``. |
| 1248 | If no argument is given, the constructor creates a new empty tuple, ``()``. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1249 | |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1250 | Note that it is actually the comma which makes a tuple, not the parentheses. |
| 1251 | The parentheses are optional, except in the empty tuple case, or |
| 1252 | when they are needed to avoid syntactic ambiguity. For example, |
| 1253 | ``f(a, b, c)`` is a function call with three arguments, while |
| 1254 | ``f((a, b, c))`` is a function call with a 3-tuple as the sole argument. |
| 1255 | |
| 1256 | Tuples implement all of the :ref:`common <typesseq-common>` sequence |
| 1257 | operations. |
| 1258 | |
| 1259 | For heterogeneous collections of data where access by name is clearer than |
| 1260 | access by index, :func:`collections.namedtuple` may be a more appropriate |
| 1261 | choice than a simple tuple object. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1262 | |
| 1263 | |
| 1264 | .. _typesseq-range: |
| 1265 | |
| 1266 | Ranges |
| 1267 | ------ |
| 1268 | |
| 1269 | .. index:: object: range |
| 1270 | |
| 1271 | The :class:`range` type represents an immutable sequence of numbers and is |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1272 | commonly used for looping a specific number of times in :keyword:`for` |
| 1273 | loops. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1274 | |
Ezio Melotti | 8429b67 | 2012-09-14 06:35:09 +0300 | [diff] [blame] | 1275 | .. class:: range(stop) |
| 1276 | range(start, stop[, step]) |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1277 | |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1278 | The arguments to the range constructor must be integers (either built-in |
| 1279 | :class:`int` or any object that implements the ``__index__`` special |
| 1280 | method). If the *step* argument is omitted, it defaults to ``1``. |
| 1281 | If the *start* argument is omitted, it defaults to ``0``. |
| 1282 | If *step* is zero, :exc:`ValueError` is raised. |
| 1283 | |
| 1284 | For a positive *step*, the contents of a range ``r`` are determined by the |
| 1285 | formula ``r[i] = start + step*i`` where ``i >= 0`` and |
| 1286 | ``r[i] < stop``. |
| 1287 | |
| 1288 | For a negative *step*, the contents of the range are still determined by |
| 1289 | the formula ``r[i] = start + step*i``, but the constraints are ``i >= 0`` |
| 1290 | and ``r[i] > stop``. |
| 1291 | |
Sandro Tosi | 4c1b9f4 | 2013-01-27 00:33:04 +0100 | [diff] [blame] | 1292 | A range object will be empty if ``r[0]`` does not meet the value |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1293 | constraint. Ranges do support negative indices, but these are interpreted |
| 1294 | as indexing from the end of the sequence determined by the positive |
| 1295 | indices. |
| 1296 | |
| 1297 | Ranges containing absolute values larger than :data:`sys.maxsize` are |
| 1298 | permitted but some features (such as :func:`len`) may raise |
| 1299 | :exc:`OverflowError`. |
| 1300 | |
| 1301 | Range examples:: |
| 1302 | |
| 1303 | >>> list(range(10)) |
| 1304 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] |
| 1305 | >>> list(range(1, 11)) |
| 1306 | [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
| 1307 | >>> list(range(0, 30, 5)) |
| 1308 | [0, 5, 10, 15, 20, 25] |
| 1309 | >>> list(range(0, 10, 3)) |
| 1310 | [0, 3, 6, 9] |
| 1311 | >>> list(range(0, -10, -1)) |
| 1312 | [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] |
| 1313 | >>> list(range(0)) |
| 1314 | [] |
| 1315 | >>> list(range(1, 0)) |
| 1316 | [] |
| 1317 | |
| 1318 | Ranges implement all of the :ref:`common <typesseq-common>` sequence operations |
| 1319 | except concatenation and repetition (due to the fact that range objects can |
| 1320 | only represent sequences that follow a strict pattern and repetition and |
| 1321 | concatenation will usually violate that pattern). |
| 1322 | |
Georg Brandl | 8c16cb9 | 2016-02-25 20:17:45 +0100 | [diff] [blame] | 1323 | .. attribute:: start |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1324 | |
| 1325 | The value of the *start* parameter (or ``0`` if the parameter was |
| 1326 | not supplied) |
| 1327 | |
Georg Brandl | 8c16cb9 | 2016-02-25 20:17:45 +0100 | [diff] [blame] | 1328 | .. attribute:: stop |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1329 | |
| 1330 | The value of the *stop* parameter |
| 1331 | |
Georg Brandl | 8c16cb9 | 2016-02-25 20:17:45 +0100 | [diff] [blame] | 1332 | .. attribute:: step |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1333 | |
| 1334 | The value of the *step* parameter (or ``1`` if the parameter was |
| 1335 | not supplied) |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1336 | |
| 1337 | The advantage of the :class:`range` type over a regular :class:`list` or |
| 1338 | :class:`tuple` is that a :class:`range` object will always take the same |
| 1339 | (small) amount of memory, no matter the size of the range it represents (as it |
| 1340 | only stores the ``start``, ``stop`` and ``step`` values, calculating individual |
| 1341 | items and subranges as needed). |
| 1342 | |
Serhiy Storchaka | 0d196ed | 2013-10-09 14:02:31 +0300 | [diff] [blame] | 1343 | Range objects implement the :class:`collections.abc.Sequence` ABC, and provide |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1344 | features such as containment tests, element index lookup, slicing and |
| 1345 | support for negative indices (see :ref:`typesseq`): |
| 1346 | |
| 1347 | >>> r = range(0, 20, 2) |
| 1348 | >>> r |
| 1349 | range(0, 20, 2) |
| 1350 | >>> 11 in r |
| 1351 | False |
| 1352 | >>> 10 in r |
| 1353 | True |
| 1354 | >>> r.index(10) |
| 1355 | 5 |
| 1356 | >>> r[5] |
| 1357 | 10 |
| 1358 | >>> r[:5] |
| 1359 | range(0, 10, 2) |
| 1360 | >>> r[-1] |
| 1361 | 18 |
| 1362 | |
| 1363 | Testing range objects for equality with ``==`` and ``!=`` compares |
| 1364 | them as sequences. That is, two range objects are considered equal if |
| 1365 | they represent the same sequence of values. (Note that two range |
Serhiy Storchaka | 0d196ed | 2013-10-09 14:02:31 +0300 | [diff] [blame] | 1366 | objects that compare equal might have different :attr:`~range.start`, |
| 1367 | :attr:`~range.stop` and :attr:`~range.step` attributes, for example |
| 1368 | ``range(0) == range(2, 1, 3)`` or ``range(0, 3, 2) == range(0, 4, 2)``.) |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1369 | |
| 1370 | .. versionchanged:: 3.2 |
| 1371 | Implement the Sequence ABC. |
| 1372 | Support slicing and negative indices. |
| 1373 | Test :class:`int` objects for membership in constant time instead of |
| 1374 | iterating through all items. |
| 1375 | |
| 1376 | .. versionchanged:: 3.3 |
| 1377 | Define '==' and '!=' to compare range objects based on the |
| 1378 | sequence of values they define (instead of comparing based on |
| 1379 | object identity). |
| 1380 | |
| 1381 | .. versionadded:: 3.3 |
Serhiy Storchaka | 0d196ed | 2013-10-09 14:02:31 +0300 | [diff] [blame] | 1382 | The :attr:`~range.start`, :attr:`~range.stop` and :attr:`~range.step` |
| 1383 | attributes. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1384 | |
Raymond Hettinger | e256acc | 2016-09-06 16:35:34 -0700 | [diff] [blame] | 1385 | .. seealso:: |
| 1386 | |
| 1387 | * The `linspace recipe <http://code.activestate.com/recipes/579000/>`_ |
Andrés Delfino | b6efc2c | 2018-08-03 02:12:51 -0300 | [diff] [blame] | 1388 | shows how to implement a lazy version of range suitable for floating |
Raymond Hettinger | e256acc | 2016-09-06 16:35:34 -0700 | [diff] [blame] | 1389 | point applications. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1390 | |
Chris Jerdonek | 5fae0e5 | 2012-11-20 17:45:51 -0800 | [diff] [blame] | 1391 | .. index:: |
| 1392 | single: string; text sequence type |
Chris Jerdonek | bb4e941 | 2012-11-28 01:38:40 -0800 | [diff] [blame] | 1393 | single: str (built-in class); (see also string) |
Chris Jerdonek | 5fae0e5 | 2012-11-20 17:45:51 -0800 | [diff] [blame] | 1394 | object: string |
| 1395 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1396 | .. _textseq: |
| 1397 | |
| 1398 | Text Sequence Type --- :class:`str` |
| 1399 | =================================== |
| 1400 | |
Chris Jerdonek | 5fae0e5 | 2012-11-20 17:45:51 -0800 | [diff] [blame] | 1401 | Textual data in Python is handled with :class:`str` objects, or :dfn:`strings`. |
| 1402 | Strings are immutable |
Chris Jerdonek | c33899b | 2012-10-11 18:57:48 -0700 | [diff] [blame] | 1403 | :ref:`sequences <typesseq>` of Unicode code points. String literals are |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1404 | written in a variety of ways: |
| 1405 | |
| 1406 | * Single quotes: ``'allows embedded "double" quotes'`` |
| 1407 | * Double quotes: ``"allows embedded 'single' quotes"``. |
| 1408 | * Triple quoted: ``'''Three single quotes'''``, ``"""Three double quotes"""`` |
| 1409 | |
| 1410 | Triple quoted strings may span multiple lines - all associated whitespace will |
| 1411 | be included in the string literal. |
| 1412 | |
| 1413 | String literals that are part of a single expression and have only whitespace |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 1414 | between them will be implicitly converted to a single string literal. That |
| 1415 | is, ``("spam " "eggs") == "spam eggs"``. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1416 | |
| 1417 | See :ref:`strings` for more about the various forms of string literal, |
| 1418 | including supported escape sequences, and the ``r`` ("raw") prefix that |
| 1419 | disables most escape sequence processing. |
| 1420 | |
Chris Jerdonek | bb4e941 | 2012-11-28 01:38:40 -0800 | [diff] [blame] | 1421 | Strings may also be created from other objects using the :class:`str` |
| 1422 | constructor. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1423 | |
| 1424 | Since there is no separate "character" type, indexing a string produces |
| 1425 | strings of length 1. That is, for a non-empty string *s*, ``s[0] == s[0:1]``. |
| 1426 | |
Chris Jerdonek | 5fae0e5 | 2012-11-20 17:45:51 -0800 | [diff] [blame] | 1427 | .. index:: |
| 1428 | object: io.StringIO |
| 1429 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1430 | There is also no mutable string type, but :meth:`str.join` or |
| 1431 | :class:`io.StringIO` can be used to efficiently construct strings from |
| 1432 | multiple fragments. |
| 1433 | |
| 1434 | .. versionchanged:: 3.3 |
| 1435 | For backwards compatibility with the Python 2 series, the ``u`` prefix is |
| 1436 | once again permitted on string literals. It has no effect on the meaning |
| 1437 | of string literals and cannot be combined with the ``r`` prefix. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1438 | |
Chris Jerdonek | bb4e941 | 2012-11-28 01:38:40 -0800 | [diff] [blame] | 1439 | |
| 1440 | .. index:: |
| 1441 | single: string; str (built-in class) |
| 1442 | |
| 1443 | .. class:: str(object='') |
| 1444 | str(object=b'', encoding='utf-8', errors='strict') |
| 1445 | |
| 1446 | Return a :ref:`string <textseq>` version of *object*. If *object* is not |
| 1447 | provided, returns the empty string. Otherwise, the behavior of ``str()`` |
| 1448 | depends on whether *encoding* or *errors* is given, as follows. |
| 1449 | |
| 1450 | If neither *encoding* nor *errors* is given, ``str(object)`` returns |
| 1451 | :meth:`object.__str__() <object.__str__>`, which is the "informal" or nicely |
| 1452 | printable string representation of *object*. For string objects, this is |
| 1453 | the string itself. If *object* does not have a :meth:`~object.__str__` |
| 1454 | method, then :func:`str` falls back to returning |
| 1455 | :meth:`repr(object) <repr>`. |
| 1456 | |
| 1457 | .. index:: |
| 1458 | single: buffer protocol; str (built-in class) |
| 1459 | single: bytes; str (built-in class) |
| 1460 | |
| 1461 | If at least one of *encoding* or *errors* is given, *object* should be a |
Ezio Melotti | c228e96 | 2013-05-04 18:06:34 +0300 | [diff] [blame] | 1462 | :term:`bytes-like object` (e.g. :class:`bytes` or :class:`bytearray`). In |
| 1463 | this case, if *object* is a :class:`bytes` (or :class:`bytearray`) object, |
| 1464 | then ``str(bytes, encoding, errors)`` is equivalent to |
Chris Jerdonek | bb4e941 | 2012-11-28 01:38:40 -0800 | [diff] [blame] | 1465 | :meth:`bytes.decode(encoding, errors) <bytes.decode>`. Otherwise, the bytes |
| 1466 | object underlying the buffer object is obtained before calling |
| 1467 | :meth:`bytes.decode`. See :ref:`binaryseq` and |
| 1468 | :ref:`bufferobjects` for information on buffer objects. |
| 1469 | |
| 1470 | Passing a :class:`bytes` object to :func:`str` without the *encoding* |
| 1471 | or *errors* arguments falls under the first case of returning the informal |
| 1472 | string representation (see also the :option:`-b` command-line option to |
| 1473 | Python). For example:: |
| 1474 | |
| 1475 | >>> str(b'Zoot!') |
| 1476 | "b'Zoot!'" |
| 1477 | |
| 1478 | For more information on the ``str`` class and its methods, see |
| 1479 | :ref:`textseq` and the :ref:`string-methods` section below. To output |
Martin Panter | bc1ee46 | 2016-02-13 00:41:37 +0000 | [diff] [blame] | 1480 | formatted strings, see the :ref:`f-strings` and :ref:`formatstrings` |
| 1481 | sections. In addition, see the :ref:`stringservices` section. |
Chris Jerdonek | bb4e941 | 2012-11-28 01:38:40 -0800 | [diff] [blame] | 1482 | |
| 1483 | |
| 1484 | .. index:: |
| 1485 | pair: string; methods |
| 1486 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1487 | .. _string-methods: |
| 1488 | |
| 1489 | String Methods |
| 1490 | -------------- |
| 1491 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1492 | .. index:: |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1493 | module: re |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1494 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1495 | Strings implement all of the :ref:`common <typesseq-common>` sequence |
| 1496 | operations, along with the additional methods described below. |
Thomas Wouters | 8ce81f7 | 2007-09-20 18:22:40 +0000 | [diff] [blame] | 1497 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 1498 | Strings also support two styles of string formatting, one providing a large |
| 1499 | degree of flexibility and customization (see :meth:`str.format`, |
| 1500 | :ref:`formatstrings` and :ref:`string-formatting`) and the other based on C |
| 1501 | ``printf`` style formatting that handles a narrower range of types and is |
| 1502 | slightly harder to use correctly, but is often faster for the cases it can |
| 1503 | handle (:ref:`old-string-formatting`). |
| 1504 | |
| 1505 | The :ref:`textservices` section of the standard library covers a number of |
| 1506 | other modules that provide various text related utilities (including regular |
| 1507 | expression support in the :mod:`re` module). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1508 | |
| 1509 | .. method:: str.capitalize() |
| 1510 | |
Senthil Kumaran | fa89798 | 2010-07-05 11:41:42 +0000 | [diff] [blame] | 1511 | Return a copy of the string with its first character capitalized and the |
Senthil Kumaran | 37c63a3 | 2010-07-06 02:08:36 +0000 | [diff] [blame] | 1512 | rest lowercased. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1513 | |
Kingsley M | b015fc8 | 2019-04-12 16:35:39 +0100 | [diff] [blame] | 1514 | .. versionchanged:: 3.8 |
| 1515 | The first character is now put into titlecase rather than uppercase. |
| 1516 | This means that characters like digraphs will only have their first |
| 1517 | letter capitalized, instead of the full character. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1518 | |
Benjamin Peterson | d5890c8 | 2012-01-14 13:23:30 -0500 | [diff] [blame] | 1519 | .. method:: str.casefold() |
| 1520 | |
| 1521 | Return a casefolded copy of the string. Casefolded strings may be used for |
Benjamin Peterson | 9430354 | 2012-01-18 23:09:32 -0500 | [diff] [blame] | 1522 | caseless matching. |
| 1523 | |
| 1524 | Casefolding is similar to lowercasing but more aggressive because it is |
| 1525 | intended to remove all case distinctions in a string. For example, the German |
| 1526 | lowercase letter ``'ß'`` is equivalent to ``"ss"``. Since it is already |
| 1527 | lowercase, :meth:`lower` would do nothing to ``'ß'``; :meth:`casefold` |
| 1528 | converts it to ``"ss"``. |
| 1529 | |
| 1530 | The casefolding algorithm is described in section 3.13 of the Unicode |
| 1531 | Standard. |
Benjamin Peterson | d5890c8 | 2012-01-14 13:23:30 -0500 | [diff] [blame] | 1532 | |
| 1533 | .. versionadded:: 3.3 |
| 1534 | |
| 1535 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1536 | .. method:: str.center(width[, fillchar]) |
| 1537 | |
| 1538 | Return centered in a string of length *width*. Padding is done using the |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 1539 | specified *fillchar* (default is an ASCII space). The original string is |
| 1540 | returned if *width* is less than or equal to ``len(s)``. |
| 1541 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1542 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1543 | |
| 1544 | .. method:: str.count(sub[, start[, end]]) |
| 1545 | |
Benjamin Peterson | ad3d5c2 | 2009-02-26 03:38:59 +0000 | [diff] [blame] | 1546 | Return the number of non-overlapping occurrences of substring *sub* in the |
| 1547 | range [*start*, *end*]. Optional arguments *start* and *end* are |
| 1548 | interpreted as in slice notation. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1549 | |
| 1550 | |
Victor Stinner | e14e212 | 2010-11-07 18:41:46 +0000 | [diff] [blame] | 1551 | .. method:: str.encode(encoding="utf-8", errors="strict") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1552 | |
Victor Stinner | e14e212 | 2010-11-07 18:41:46 +0000 | [diff] [blame] | 1553 | Return an encoded version of the string as a bytes object. Default encoding |
| 1554 | is ``'utf-8'``. *errors* may be given to set a different error handling scheme. |
| 1555 | The default for *errors* is ``'strict'``, meaning that encoding errors raise |
| 1556 | a :exc:`UnicodeError`. Other possible |
Georg Brandl | 4f5f98d | 2009-05-04 21:01:20 +0000 | [diff] [blame] | 1557 | values are ``'ignore'``, ``'replace'``, ``'xmlcharrefreplace'``, |
| 1558 | ``'backslashreplace'`` and any other name registered via |
Nick Coghlan | b9fdb7a | 2015-01-07 00:22:00 +1000 | [diff] [blame] | 1559 | :func:`codecs.register_error`, see section :ref:`error-handlers`. For a |
Georg Brandl | 4f5f98d | 2009-05-04 21:01:20 +0000 | [diff] [blame] | 1560 | list of possible encodings, see section :ref:`standard-encodings`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1561 | |
Benjamin Peterson | 308d637 | 2009-09-18 21:42:35 +0000 | [diff] [blame] | 1562 | .. versionchanged:: 3.1 |
Georg Brandl | 67b21b7 | 2010-08-17 15:07:14 +0000 | [diff] [blame] | 1563 | Support for keyword arguments added. |
| 1564 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1565 | |
| 1566 | .. method:: str.endswith(suffix[, start[, end]]) |
| 1567 | |
| 1568 | Return ``True`` if the string ends with the specified *suffix*, otherwise return |
| 1569 | ``False``. *suffix* can also be a tuple of suffixes to look for. With optional |
| 1570 | *start*, test beginning at that position. With optional *end*, stop comparing |
| 1571 | at that position. |
| 1572 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1573 | |
Ezio Melotti | 745d54d | 2013-11-16 19:10:57 +0200 | [diff] [blame] | 1574 | .. method:: str.expandtabs(tabsize=8) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1575 | |
Ned Deily | bebe91a | 2013-04-21 13:05:21 -0700 | [diff] [blame] | 1576 | Return a copy of the string where all tab characters are replaced by one or |
| 1577 | more spaces, depending on the current column and the given tab size. Tab |
| 1578 | positions occur every *tabsize* characters (default is 8, giving tab |
| 1579 | positions at columns 0, 8, 16 and so on). To expand the string, the current |
| 1580 | column is set to zero and the string is examined character by character. If |
| 1581 | the character is a tab (``\t``), one or more space characters are inserted |
| 1582 | in the result until the current column is equal to the next tab position. |
| 1583 | (The tab character itself is not copied.) If the character is a newline |
| 1584 | (``\n``) or return (``\r``), it is copied and the current column is reset to |
| 1585 | zero. Any other character is copied unchanged and the current column is |
| 1586 | incremented by one regardless of how the character is represented when |
| 1587 | printed. |
| 1588 | |
| 1589 | >>> '01\t012\t0123\t01234'.expandtabs() |
| 1590 | '01 012 0123 01234' |
| 1591 | >>> '01\t012\t0123\t01234'.expandtabs(4) |
| 1592 | '01 012 0123 01234' |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1593 | |
| 1594 | |
| 1595 | .. method:: str.find(sub[, start[, end]]) |
| 1596 | |
Senthil Kumaran | 114a1d6 | 2016-01-03 17:57:10 -0800 | [diff] [blame] | 1597 | Return the lowest index in the string where substring *sub* is found within |
| 1598 | the slice ``s[start:end]``. Optional arguments *start* and *end* are |
| 1599 | interpreted as in slice notation. Return ``-1`` if *sub* is not found. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1600 | |
Ezio Melotti | 0ed8c68 | 2011-05-09 03:54:30 +0300 | [diff] [blame] | 1601 | .. note:: |
| 1602 | |
| 1603 | The :meth:`~str.find` method should be used only if you need to know the |
| 1604 | position of *sub*. To check if *sub* is a substring or not, use the |
| 1605 | :keyword:`in` operator:: |
| 1606 | |
| 1607 | >>> 'Py' in 'Python' |
| 1608 | True |
| 1609 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1610 | |
Benjamin Peterson | ad3d5c2 | 2009-02-26 03:38:59 +0000 | [diff] [blame] | 1611 | .. method:: str.format(*args, **kwargs) |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1612 | |
Georg Brandl | 1f70cdf | 2010-03-21 09:04:24 +0000 | [diff] [blame] | 1613 | Perform a string formatting operation. The string on which this method is |
| 1614 | called can contain literal text or replacement fields delimited by braces |
| 1615 | ``{}``. Each replacement field contains either the numeric index of a |
| 1616 | positional argument, or the name of a keyword argument. Returns a copy of |
| 1617 | the string where each replacement field is replaced with the string value of |
| 1618 | the corresponding argument. |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1619 | |
| 1620 | >>> "The sum of 1 + 2 is {0}".format(1+2) |
| 1621 | 'The sum of 1 + 2 is 3' |
| 1622 | |
| 1623 | See :ref:`formatstrings` for a description of the various formatting options |
| 1624 | that can be specified in format strings. |
| 1625 | |
Victor Stinner | cb064fc | 2018-01-15 15:58:02 +0100 | [diff] [blame] | 1626 | .. note:: |
Andrés Delfino | 93b5655 | 2018-08-18 14:36:24 -0300 | [diff] [blame] | 1627 | When formatting a number (:class:`int`, :class:`float`, :class:`complex`, |
| 1628 | :class:`decimal.Decimal` and subclasses) with the ``n`` type |
| 1629 | (ex: ``'{:n}'.format(1234)``), the function temporarily sets the |
| 1630 | ``LC_CTYPE`` locale to the ``LC_NUMERIC`` locale to decode |
| 1631 | ``decimal_point`` and ``thousands_sep`` fields of :c:func:`localeconv` if |
| 1632 | they are non-ASCII or longer than 1 byte, and the ``LC_NUMERIC`` locale is |
| 1633 | different than the ``LC_CTYPE`` locale. This temporary change affects |
| 1634 | other threads. |
Victor Stinner | cb064fc | 2018-01-15 15:58:02 +0100 | [diff] [blame] | 1635 | |
| 1636 | .. versionchanged:: 3.7 |
| 1637 | When formatting a number with the ``n`` type, the function sets |
| 1638 | temporarily the ``LC_CTYPE`` locale to the ``LC_NUMERIC`` locale in some |
| 1639 | cases. |
| 1640 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1641 | |
Eric Smith | 27bbca6 | 2010-11-04 17:06:58 +0000 | [diff] [blame] | 1642 | .. method:: str.format_map(mapping) |
| 1643 | |
Éric Araujo | 2642ad0 | 2010-11-06 04:59:27 +0000 | [diff] [blame] | 1644 | Similar to ``str.format(**mapping)``, except that ``mapping`` is |
Serhiy Storchaka | a4d170d | 2013-12-23 18:20:51 +0200 | [diff] [blame] | 1645 | used directly and not copied to a :class:`dict`. This is useful |
Eric Smith | 5ad85f8 | 2010-11-06 13:22:13 +0000 | [diff] [blame] | 1646 | if for example ``mapping`` is a dict subclass: |
Eric Smith | 27bbca6 | 2010-11-04 17:06:58 +0000 | [diff] [blame] | 1647 | |
Eric Smith | 5ad85f8 | 2010-11-06 13:22:13 +0000 | [diff] [blame] | 1648 | >>> class Default(dict): |
| 1649 | ... def __missing__(self, key): |
| 1650 | ... return key |
| 1651 | ... |
| 1652 | >>> '{name} was born in {country}'.format_map(Default(name='Guido')) |
| 1653 | 'Guido was born in country' |
| 1654 | |
| 1655 | .. versionadded:: 3.2 |
| 1656 | |
Eric Smith | 27bbca6 | 2010-11-04 17:06:58 +0000 | [diff] [blame] | 1657 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1658 | .. method:: str.index(sub[, start[, end]]) |
| 1659 | |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 1660 | Like :meth:`~str.find`, but raise :exc:`ValueError` when the substring is |
| 1661 | not found. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1662 | |
| 1663 | |
| 1664 | .. method:: str.isalnum() |
| 1665 | |
| 1666 | Return true if all characters in the string are alphanumeric and there is at |
Alexander Belopolsky | 0d26798 | 2010-12-23 02:58:25 +0000 | [diff] [blame] | 1667 | least one character, false otherwise. A character ``c`` is alphanumeric if one |
| 1668 | of the following returns ``True``: ``c.isalpha()``, ``c.isdecimal()``, |
| 1669 | ``c.isdigit()``, or ``c.isnumeric()``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1670 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1671 | |
| 1672 | .. method:: str.isalpha() |
| 1673 | |
| 1674 | Return true if all characters in the string are alphabetic and there is at least |
Alexander Belopolsky | 0d26798 | 2010-12-23 02:58:25 +0000 | [diff] [blame] | 1675 | one character, false otherwise. Alphabetic characters are those characters defined |
| 1676 | in the Unicode character database as "Letter", i.e., those with general category |
| 1677 | property being one of "Lm", "Lt", "Lu", "Ll", or "Lo". Note that this is different |
| 1678 | from the "Alphabetic" property defined in the Unicode Standard. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1679 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1680 | |
INADA Naoki | a49ac99 | 2018-01-27 14:06:21 +0900 | [diff] [blame] | 1681 | .. method:: str.isascii() |
| 1682 | |
| 1683 | Return true if the string is empty or all characters in the string are ASCII, |
| 1684 | false otherwise. |
| 1685 | ASCII characters have code points in the range U+0000-U+007F. |
| 1686 | |
| 1687 | .. versionadded:: 3.7 |
| 1688 | |
| 1689 | |
Mark Summerfield | bbfd71d | 2008-07-01 15:50:04 +0000 | [diff] [blame] | 1690 | .. method:: str.isdecimal() |
| 1691 | |
| 1692 | Return true if all characters in the string are decimal |
| 1693 | characters and there is at least one character, false |
Martin Panter | 49c14d8 | 2016-12-11 01:08:25 +0000 | [diff] [blame] | 1694 | otherwise. Decimal characters are those that can be used to form |
| 1695 | numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT |
| 1696 | ZERO. Formally a decimal character is a character in the Unicode |
| 1697 | General Category "Nd". |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 1698 | |
Mark Summerfield | bbfd71d | 2008-07-01 15:50:04 +0000 | [diff] [blame] | 1699 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1700 | .. method:: str.isdigit() |
| 1701 | |
| 1702 | Return true if all characters in the string are digits and there is at least one |
Alexander Belopolsky | 0d26798 | 2010-12-23 02:58:25 +0000 | [diff] [blame] | 1703 | character, false otherwise. Digits include decimal characters and digits that need |
Martin Panter | 49c14d8 | 2016-12-11 01:08:25 +0000 | [diff] [blame] | 1704 | special handling, such as the compatibility superscript digits. |
| 1705 | This covers digits which cannot be used to form numbers in base 10, |
| 1706 | like the Kharosthi numbers. Formally, a digit is a character that has the |
| 1707 | property value Numeric_Type=Digit or Numeric_Type=Decimal. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1708 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1709 | |
| 1710 | .. method:: str.isidentifier() |
| 1711 | |
| 1712 | Return true if the string is a valid identifier according to the language |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1713 | definition, section :ref:`identifiers`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1714 | |
Sanyam Khurana | ffc5a14 | 2018-10-08 12:23:32 +0530 | [diff] [blame] | 1715 | Call :func:`keyword.iskeyword` to test whether string ``s`` is a reserved |
| 1716 | identifier, such as :keyword:`def` and :keyword:`class`. |
| 1717 | |
| 1718 | Example: |
| 1719 | :: |
| 1720 | |
| 1721 | >>> from keyword import iskeyword |
| 1722 | |
| 1723 | >>> 'hello'.isidentifier(), iskeyword('hello') |
| 1724 | True, False |
| 1725 | >>> 'def'.isidentifier(), iskeyword('def') |
| 1726 | True, True |
| 1727 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1728 | |
| 1729 | .. method:: str.islower() |
| 1730 | |
Ezio Melotti | 0656a56 | 2011-08-15 14:27:19 +0300 | [diff] [blame] | 1731 | Return true if all cased characters [4]_ in the string are lowercase and |
| 1732 | there is at least one cased character, false otherwise. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1733 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1734 | |
Mark Summerfield | bbfd71d | 2008-07-01 15:50:04 +0000 | [diff] [blame] | 1735 | .. method:: str.isnumeric() |
| 1736 | |
| 1737 | Return true if all characters in the string are numeric |
| 1738 | characters, and there is at least one character, false |
| 1739 | otherwise. Numeric characters include digit characters, and all characters |
| 1740 | that have the Unicode numeric value property, e.g. U+2155, |
Alexander Belopolsky | 0d26798 | 2010-12-23 02:58:25 +0000 | [diff] [blame] | 1741 | VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property |
| 1742 | value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric. |
Mark Summerfield | bbfd71d | 2008-07-01 15:50:04 +0000 | [diff] [blame] | 1743 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 1744 | |
Georg Brandl | 559e5d7 | 2008-06-11 18:37:52 +0000 | [diff] [blame] | 1745 | .. method:: str.isprintable() |
| 1746 | |
| 1747 | Return true if all characters in the string are printable or the string is |
| 1748 | empty, false otherwise. Nonprintable characters are those characters defined |
| 1749 | in the Unicode character database as "Other" or "Separator", excepting the |
| 1750 | ASCII space (0x20) which is considered printable. (Note that printable |
| 1751 | characters in this context are those which should not be escaped when |
| 1752 | :func:`repr` is invoked on a string. It has no bearing on the handling of |
| 1753 | strings written to :data:`sys.stdout` or :data:`sys.stderr`.) |
| 1754 | |
| 1755 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1756 | .. method:: str.isspace() |
| 1757 | |
| 1758 | Return true if there are only whitespace characters in the string and there is |
Alexander Belopolsky | 0d26798 | 2010-12-23 02:58:25 +0000 | [diff] [blame] | 1759 | at least one character, false otherwise. Whitespace characters are those |
| 1760 | characters defined in the Unicode character database as "Other" or "Separator" |
| 1761 | and those with bidirectional property being one of "WS", "B", or "S". |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1762 | |
| 1763 | .. method:: str.istitle() |
| 1764 | |
| 1765 | Return true if the string is a titlecased string and there is at least one |
| 1766 | character, for example uppercase characters may only follow uncased characters |
| 1767 | and lowercase characters only cased ones. Return false otherwise. |
| 1768 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1769 | |
| 1770 | .. method:: str.isupper() |
| 1771 | |
Ezio Melotti | 0656a56 | 2011-08-15 14:27:19 +0300 | [diff] [blame] | 1772 | Return true if all cased characters [4]_ in the string are uppercase and |
| 1773 | there is at least one cased character, false otherwise. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1774 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1775 | |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 1776 | .. method:: str.join(iterable) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1777 | |
Sanyam Khurana | 08e2f35 | 2017-05-27 11:14:41 +0530 | [diff] [blame] | 1778 | Return a string which is the concatenation of the strings in *iterable*. |
| 1779 | A :exc:`TypeError` will be raised if there are any non-string values in |
| 1780 | *iterable*, including :class:`bytes` objects. The separator between |
| 1781 | elements is the string providing this method. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1782 | |
| 1783 | |
| 1784 | .. method:: str.ljust(width[, fillchar]) |
| 1785 | |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 1786 | Return the string left justified in a string of length *width*. Padding is |
| 1787 | done using the specified *fillchar* (default is an ASCII space). The |
| 1788 | original string is returned if *width* is less than or equal to ``len(s)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1789 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1790 | |
| 1791 | .. method:: str.lower() |
| 1792 | |
Ezio Melotti | 0656a56 | 2011-08-15 14:27:19 +0300 | [diff] [blame] | 1793 | Return a copy of the string with all the cased characters [4]_ converted to |
| 1794 | lowercase. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1795 | |
Benjamin Peterson | 9430354 | 2012-01-18 23:09:32 -0500 | [diff] [blame] | 1796 | The lowercasing algorithm used is described in section 3.13 of the Unicode |
| 1797 | Standard. |
| 1798 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1799 | |
| 1800 | .. method:: str.lstrip([chars]) |
| 1801 | |
| 1802 | Return a copy of the string with leading characters removed. The *chars* |
| 1803 | argument is a string specifying the set of characters to be removed. If omitted |
| 1804 | or ``None``, the *chars* argument defaults to removing whitespace. The *chars* |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 1805 | argument is not a prefix; rather, all combinations of its values are stripped:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1806 | |
| 1807 | >>> ' spacious '.lstrip() |
| 1808 | 'spacious ' |
| 1809 | >>> 'www.example.com'.lstrip('cmowz.') |
| 1810 | 'example.com' |
| 1811 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1812 | |
Georg Brandl | abc3877 | 2009-04-12 15:51:51 +0000 | [diff] [blame] | 1813 | .. staticmethod:: str.maketrans(x[, y[, z]]) |
Georg Brandl | ceee077 | 2007-11-27 23:48:05 +0000 | [diff] [blame] | 1814 | |
| 1815 | This static method returns a translation table usable for :meth:`str.translate`. |
| 1816 | |
| 1817 | If there is only one argument, it must be a dictionary mapping Unicode |
| 1818 | ordinals (integers) or characters (strings of length 1) to Unicode ordinals, |
Serhiy Storchaka | ecf41da | 2016-10-19 16:29:26 +0300 | [diff] [blame] | 1819 | strings (of arbitrary lengths) or ``None``. Character keys will then be |
Georg Brandl | ceee077 | 2007-11-27 23:48:05 +0000 | [diff] [blame] | 1820 | converted to ordinals. |
| 1821 | |
| 1822 | If there are two arguments, they must be strings of equal length, and in the |
| 1823 | resulting dictionary, each character in x will be mapped to the character at |
| 1824 | the same position in y. If there is a third argument, it must be a string, |
Serhiy Storchaka | ecf41da | 2016-10-19 16:29:26 +0300 | [diff] [blame] | 1825 | whose characters will be mapped to ``None`` in the result. |
Georg Brandl | ceee077 | 2007-11-27 23:48:05 +0000 | [diff] [blame] | 1826 | |
| 1827 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1828 | .. method:: str.partition(sep) |
| 1829 | |
| 1830 | Split the string at the first occurrence of *sep*, and return a 3-tuple |
| 1831 | containing the part before the separator, the separator itself, and the part |
| 1832 | after the separator. If the separator is not found, return a 3-tuple containing |
| 1833 | the string itself, followed by two empty strings. |
| 1834 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1835 | |
| 1836 | .. method:: str.replace(old, new[, count]) |
| 1837 | |
| 1838 | Return a copy of the string with all occurrences of substring *old* replaced by |
| 1839 | *new*. If the optional argument *count* is given, only the first *count* |
| 1840 | occurrences are replaced. |
| 1841 | |
| 1842 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1843 | .. method:: str.rfind(sub[, start[, end]]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1844 | |
Benjamin Peterson | d99cd81 | 2010-04-27 22:58:50 +0000 | [diff] [blame] | 1845 | Return the highest index in the string where substring *sub* is found, such |
| 1846 | that *sub* is contained within ``s[start:end]``. Optional arguments *start* |
| 1847 | and *end* are interpreted as in slice notation. Return ``-1`` on failure. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1848 | |
| 1849 | |
| 1850 | .. method:: str.rindex(sub[, start[, end]]) |
| 1851 | |
| 1852 | Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not |
| 1853 | found. |
| 1854 | |
| 1855 | |
| 1856 | .. method:: str.rjust(width[, fillchar]) |
| 1857 | |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 1858 | Return the string right justified in a string of length *width*. Padding is |
| 1859 | done using the specified *fillchar* (default is an ASCII space). The |
| 1860 | original string is returned if *width* is less than or equal to ``len(s)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1861 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1862 | |
| 1863 | .. method:: str.rpartition(sep) |
| 1864 | |
| 1865 | Split the string at the last occurrence of *sep*, and return a 3-tuple |
| 1866 | containing the part before the separator, the separator itself, and the part |
| 1867 | after the separator. If the separator is not found, return a 3-tuple containing |
| 1868 | two empty strings, followed by the string itself. |
| 1869 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1870 | |
Ezio Melotti | cda6b6d | 2012-02-26 09:39:55 +0200 | [diff] [blame] | 1871 | .. method:: str.rsplit(sep=None, maxsplit=-1) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1872 | |
| 1873 | Return a list of the words in the string, using *sep* as the delimiter string. |
| 1874 | If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost* |
| 1875 | ones. If *sep* is not specified or ``None``, any whitespace string is a |
| 1876 | separator. Except for splitting from the right, :meth:`rsplit` behaves like |
| 1877 | :meth:`split` which is described in detail below. |
| 1878 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1879 | |
| 1880 | .. method:: str.rstrip([chars]) |
| 1881 | |
| 1882 | Return a copy of the string with trailing characters removed. The *chars* |
| 1883 | argument is a string specifying the set of characters to be removed. If omitted |
| 1884 | or ``None``, the *chars* argument defaults to removing whitespace. The *chars* |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 1885 | argument is not a suffix; rather, all combinations of its values are stripped:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1886 | |
| 1887 | >>> ' spacious '.rstrip() |
| 1888 | ' spacious' |
| 1889 | >>> 'mississippi'.rstrip('ipz') |
| 1890 | 'mississ' |
| 1891 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1892 | |
Ezio Melotti | cda6b6d | 2012-02-26 09:39:55 +0200 | [diff] [blame] | 1893 | .. method:: str.split(sep=None, maxsplit=-1) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1894 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1895 | Return a list of the words in the string, using *sep* as the delimiter |
| 1896 | string. If *maxsplit* is given, at most *maxsplit* splits are done (thus, |
| 1897 | the list will have at most ``maxsplit+1`` elements). If *maxsplit* is not |
Ezio Melotti | bf3165b | 2012-05-10 15:30:42 +0300 | [diff] [blame] | 1898 | specified or ``-1``, then there is no limit on the number of splits |
| 1899 | (all possible splits are made). |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 1900 | |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 1901 | If *sep* is given, consecutive delimiters are not grouped together and are |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1902 | deemed to delimit empty strings (for example, ``'1,,2'.split(',')`` returns |
| 1903 | ``['1', '', '2']``). The *sep* argument may consist of multiple characters |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 1904 | (for example, ``'1<>2<>3'.split('<>')`` returns ``['1', '2', '3']``). |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1905 | Splitting an empty string with a specified separator returns ``['']``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1906 | |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 1907 | For example:: |
| 1908 | |
| 1909 | >>> '1,2,3'.split(',') |
| 1910 | ['1', '2', '3'] |
| 1911 | >>> '1,2,3'.split(',', maxsplit=1) |
Benjamin Peterson | eb83ffe | 2014-09-22 22:43:50 -0400 | [diff] [blame] | 1912 | ['1', '2,3'] |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 1913 | >>> '1,2,,3,'.split(',') |
| 1914 | ['1', '2', '', '3', ''] |
| 1915 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1916 | If *sep* is not specified or is ``None``, a different splitting algorithm is |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 1917 | applied: runs of consecutive whitespace are regarded as a single separator, |
| 1918 | and the result will contain no empty strings at the start or end if the |
| 1919 | string has leading or trailing whitespace. Consequently, splitting an empty |
| 1920 | string or a string consisting of just whitespace with a ``None`` separator |
| 1921 | returns ``[]``. |
| 1922 | |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 1923 | For example:: |
| 1924 | |
| 1925 | >>> '1 2 3'.split() |
| 1926 | ['1', '2', '3'] |
| 1927 | >>> '1 2 3'.split(maxsplit=1) |
| 1928 | ['1', '2 3'] |
| 1929 | >>> ' 1 2 3 '.split() |
| 1930 | ['1', '2', '3'] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1931 | |
| 1932 | |
R David Murray | 1b00f25 | 2012-08-15 10:43:58 -0400 | [diff] [blame] | 1933 | .. index:: |
| 1934 | single: universal newlines; str.splitlines method |
| 1935 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1936 | .. method:: str.splitlines([keepends]) |
| 1937 | |
Benjamin Peterson | 8218bd4 | 2015-03-31 21:20:36 -0400 | [diff] [blame] | 1938 | Return a list of the lines in the string, breaking at line boundaries. Line |
| 1939 | breaks are not included in the resulting list unless *keepends* is given and |
| 1940 | true. |
| 1941 | |
| 1942 | This method splits on the following line boundaries. In particular, the |
| 1943 | boundaries are a superset of :term:`universal newlines`. |
| 1944 | |
| 1945 | +-----------------------+-----------------------------+ |
| 1946 | | Representation | Description | |
| 1947 | +=======================+=============================+ |
| 1948 | | ``\n`` | Line Feed | |
| 1949 | +-----------------------+-----------------------------+ |
| 1950 | | ``\r`` | Carriage Return | |
| 1951 | +-----------------------+-----------------------------+ |
| 1952 | | ``\r\n`` | Carriage Return + Line Feed | |
| 1953 | +-----------------------+-----------------------------+ |
| 1954 | | ``\v`` or ``\x0b`` | Line Tabulation | |
| 1955 | +-----------------------+-----------------------------+ |
| 1956 | | ``\f`` or ``\x0c`` | Form Feed | |
| 1957 | +-----------------------+-----------------------------+ |
| 1958 | | ``\x1c`` | File Separator | |
| 1959 | +-----------------------+-----------------------------+ |
| 1960 | | ``\x1d`` | Group Separator | |
| 1961 | +-----------------------+-----------------------------+ |
| 1962 | | ``\x1e`` | Record Separator | |
| 1963 | +-----------------------+-----------------------------+ |
| 1964 | | ``\x85`` | Next Line (C1 Control Code) | |
| 1965 | +-----------------------+-----------------------------+ |
| 1966 | | ``\u2028`` | Line Separator | |
| 1967 | +-----------------------+-----------------------------+ |
| 1968 | | ``\u2029`` | Paragraph Separator | |
| 1969 | +-----------------------+-----------------------------+ |
| 1970 | |
| 1971 | .. versionchanged:: 3.2 |
| 1972 | |
| 1973 | ``\v`` and ``\f`` added to list of line boundaries. |
R David Murray | ae1b94b | 2012-06-01 16:19:36 -0400 | [diff] [blame] | 1974 | |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 1975 | For example:: |
| 1976 | |
| 1977 | >>> 'ab c\n\nde fg\rkl\r\n'.splitlines() |
Larry Hastings | c6256e5 | 2014-10-05 19:03:48 -0700 | [diff] [blame] | 1978 | ['ab c', '', 'de fg', 'kl'] |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 1979 | >>> 'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True) |
| 1980 | ['ab c\n', '\n', 'de fg\r', 'kl\r\n'] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1981 | |
R David Murray | 05c35a6 | 2012-08-06 16:08:09 -0400 | [diff] [blame] | 1982 | Unlike :meth:`~str.split` when a delimiter string *sep* is given, this |
| 1983 | method returns an empty list for the empty string, and a terminal line |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 1984 | break does not result in an extra line:: |
| 1985 | |
| 1986 | >>> "".splitlines() |
| 1987 | [] |
| 1988 | >>> "One line\n".splitlines() |
| 1989 | ['One line'] |
| 1990 | |
| 1991 | For comparison, ``split('\n')`` gives:: |
| 1992 | |
| 1993 | >>> ''.split('\n') |
| 1994 | [''] |
| 1995 | >>> 'Two lines\n'.split('\n') |
| 1996 | ['Two lines', ''] |
R David Murray | 05c35a6 | 2012-08-06 16:08:09 -0400 | [diff] [blame] | 1997 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1998 | |
| 1999 | .. method:: str.startswith(prefix[, start[, end]]) |
| 2000 | |
| 2001 | Return ``True`` if string starts with the *prefix*, otherwise return ``False``. |
| 2002 | *prefix* can also be a tuple of prefixes to look for. With optional *start*, |
| 2003 | test string beginning at that position. With optional *end*, stop comparing |
| 2004 | string at that position. |
| 2005 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2006 | |
| 2007 | .. method:: str.strip([chars]) |
| 2008 | |
| 2009 | Return a copy of the string with the leading and trailing characters removed. |
| 2010 | The *chars* argument is a string specifying the set of characters to be removed. |
| 2011 | If omitted or ``None``, the *chars* argument defaults to removing whitespace. |
| 2012 | The *chars* argument is not a prefix or suffix; rather, all combinations of its |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2013 | values are stripped:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2014 | |
| 2015 | >>> ' spacious '.strip() |
| 2016 | 'spacious' |
| 2017 | >>> 'www.example.com'.strip('cmowz.') |
| 2018 | 'example' |
| 2019 | |
Raymond Hettinger | 19cfb57 | 2015-05-23 09:11:55 -0700 | [diff] [blame] | 2020 | The outermost leading and trailing *chars* argument values are stripped |
| 2021 | from the string. Characters are removed from the leading end until |
| 2022 | reaching a string character that is not contained in the set of |
| 2023 | characters in *chars*. A similar action takes place on the trailing end. |
| 2024 | For example:: |
| 2025 | |
| 2026 | >>> comment_string = '#....... Section 3.2.1 Issue #32 .......' |
| 2027 | >>> comment_string.strip('.#! ') |
| 2028 | 'Section 3.2.1 Issue #32' |
| 2029 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2030 | |
| 2031 | .. method:: str.swapcase() |
| 2032 | |
| 2033 | Return a copy of the string with uppercase characters converted to lowercase and |
Benjamin Peterson | b2bf01d | 2012-01-11 18:17:06 -0500 | [diff] [blame] | 2034 | vice versa. Note that it is not necessarily true that |
| 2035 | ``s.swapcase().swapcase() == s``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2036 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2037 | |
| 2038 | .. method:: str.title() |
| 2039 | |
Raymond Hettinger | b8b0ba1 | 2009-09-29 06:22:28 +0000 | [diff] [blame] | 2040 | Return a titlecased version of the string where words start with an uppercase |
| 2041 | character and the remaining characters are lowercase. |
| 2042 | |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2043 | For example:: |
| 2044 | |
| 2045 | >>> 'Hello world'.title() |
| 2046 | 'Hello World' |
| 2047 | |
Raymond Hettinger | b8b0ba1 | 2009-09-29 06:22:28 +0000 | [diff] [blame] | 2048 | The algorithm uses a simple language-independent definition of a word as |
| 2049 | groups of consecutive letters. The definition works in many contexts but |
| 2050 | it means that apostrophes in contractions and possessives form word |
| 2051 | boundaries, which may not be the desired result:: |
| 2052 | |
| 2053 | >>> "they're bill's friends from the UK".title() |
| 2054 | "They'Re Bill'S Friends From The Uk" |
| 2055 | |
| 2056 | A workaround for apostrophes can be constructed using regular expressions:: |
| 2057 | |
| 2058 | >>> import re |
| 2059 | >>> def titlecase(s): |
Andrew Svetlov | 5c90436 | 2012-11-08 17:26:53 +0200 | [diff] [blame] | 2060 | ... return re.sub(r"[A-Za-z]+('[A-Za-z]+)?", |
Kingsley M | b015fc8 | 2019-04-12 16:35:39 +0100 | [diff] [blame] | 2061 | ... lambda mo: mo.group(0).capitalize(), |
Andrew Svetlov | 5c90436 | 2012-11-08 17:26:53 +0200 | [diff] [blame] | 2062 | ... s) |
| 2063 | ... |
Raymond Hettinger | b8b0ba1 | 2009-09-29 06:22:28 +0000 | [diff] [blame] | 2064 | >>> titlecase("they're bill's friends.") |
| 2065 | "They're Bill's Friends." |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2066 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2067 | |
Zachary Ware | 79b98df | 2015-08-05 23:54:15 -0500 | [diff] [blame] | 2068 | .. method:: str.translate(table) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2069 | |
Zachary Ware | 79b98df | 2015-08-05 23:54:15 -0500 | [diff] [blame] | 2070 | Return a copy of the string in which each character has been mapped through |
| 2071 | the given translation table. The table must be an object that implements |
| 2072 | indexing via :meth:`__getitem__`, typically a :term:`mapping` or |
| 2073 | :term:`sequence`. When indexed by a Unicode ordinal (an integer), the |
| 2074 | table object can do any of the following: return a Unicode ordinal or a |
| 2075 | string, to map the character to one or more other characters; return |
| 2076 | ``None``, to delete the character from the return string; or raise a |
| 2077 | :exc:`LookupError` exception, to map the character to itself. |
Georg Brandl | ceee077 | 2007-11-27 23:48:05 +0000 | [diff] [blame] | 2078 | |
Georg Brandl | 454636f | 2008-12-27 23:33:20 +0000 | [diff] [blame] | 2079 | You can use :meth:`str.maketrans` to create a translation map from |
| 2080 | character-to-character mappings in different formats. |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 2081 | |
Zachary Ware | 79b98df | 2015-08-05 23:54:15 -0500 | [diff] [blame] | 2082 | See also the :mod:`codecs` module for a more flexible approach to custom |
| 2083 | character mappings. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2084 | |
| 2085 | |
| 2086 | .. method:: str.upper() |
| 2087 | |
Ezio Melotti | 0656a56 | 2011-08-15 14:27:19 +0300 | [diff] [blame] | 2088 | Return a copy of the string with all the cased characters [4]_ converted to |
Andrés Delfino | 4a6e746 | 2018-06-25 07:34:22 -0300 | [diff] [blame] | 2089 | uppercase. Note that ``s.upper().isupper()`` might be ``False`` if ``s`` |
Ezio Melotti | 0656a56 | 2011-08-15 14:27:19 +0300 | [diff] [blame] | 2090 | contains uncased characters or if the Unicode category of the resulting |
Benjamin Peterson | 9430354 | 2012-01-18 23:09:32 -0500 | [diff] [blame] | 2091 | character(s) is not "Lu" (Letter, uppercase), but e.g. "Lt" (Letter, |
| 2092 | titlecase). |
| 2093 | |
| 2094 | The uppercasing algorithm used is described in section 3.13 of the Unicode |
| 2095 | Standard. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2096 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2097 | |
| 2098 | .. method:: str.zfill(width) |
| 2099 | |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2100 | Return a copy of the string left filled with ASCII ``'0'`` digits to |
Tim Golden | 42c235e | 2015-04-06 11:04:49 +0100 | [diff] [blame] | 2101 | make a string of length *width*. A leading sign prefix (``'+'``/``'-'``) |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2102 | is handled by inserting the padding *after* the sign character rather |
| 2103 | than before. The original string is returned if *width* is less than |
| 2104 | or equal to ``len(s)``. |
| 2105 | |
| 2106 | For example:: |
| 2107 | |
| 2108 | >>> "42".zfill(5) |
| 2109 | '00042' |
| 2110 | >>> "-42".zfill(5) |
| 2111 | '-0042' |
Christian Heimes | b186d00 | 2008-03-18 15:15:01 +0000 | [diff] [blame] | 2112 | |
| 2113 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2114 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 2115 | .. _old-string-formatting: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2116 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2117 | ``printf``-style String Formatting |
| 2118 | ---------------------------------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2119 | |
| 2120 | .. index:: |
| 2121 | single: formatting, string (%) |
| 2122 | single: interpolation, string (%) |
Martin Panter | bc1ee46 | 2016-02-13 00:41:37 +0000 | [diff] [blame] | 2123 | single: string; formatting, printf |
| 2124 | single: string; interpolation, printf |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2125 | single: printf-style formatting |
| 2126 | single: sprintf-style formatting |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 2127 | single: % (percent); printf-style formatting |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2128 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 2129 | .. note:: |
| 2130 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2131 | The formatting operations described here exhibit a variety of quirks that |
| 2132 | lead to a number of common errors (such as failing to display tuples and |
Barry Warsaw | 9f74deb | 2017-03-28 10:02:07 -0400 | [diff] [blame] | 2133 | dictionaries correctly). Using the newer :ref:`formatted string literals |
| 2134 | <f-strings>`, the :meth:`str.format` interface, or :ref:`template strings |
| 2135 | <template-strings>` may help avoid these errors. Each of these |
| 2136 | alternatives provides their own trade-offs and benefits of simplicity, |
| 2137 | flexibility, and/or extensibility. |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 2138 | |
| 2139 | String objects have one unique built-in operation: the ``%`` operator (modulo). |
| 2140 | This is also known as the string *formatting* or *interpolation* operator. |
| 2141 | Given ``format % values`` (where *format* is a string), ``%`` conversion |
| 2142 | specifications in *format* are replaced with zero or more elements of *values*. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2143 | The effect is similar to using the :c:func:`sprintf` in the C language. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2144 | |
| 2145 | If *format* requires a single argument, *values* may be a single non-tuple |
Ezio Melotti | 0656a56 | 2011-08-15 14:27:19 +0300 | [diff] [blame] | 2146 | object. [5]_ Otherwise, *values* must be a tuple with exactly the number of |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2147 | items specified by the format string, or a single mapping object (for example, a |
| 2148 | dictionary). |
| 2149 | |
Andre Delfino | de9e9b4 | 2018-12-09 04:00:20 -0300 | [diff] [blame] | 2150 | .. index:: |
| 2151 | single: () (parentheses); in printf-style formatting |
| 2152 | single: * (asterisk); in printf-style formatting |
| 2153 | single: . (dot); in printf-style formatting |
| 2154 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2155 | A conversion specifier contains two or more characters and has the following |
| 2156 | components, which must occur in this order: |
| 2157 | |
| 2158 | #. The ``'%'`` character, which marks the start of the specifier. |
| 2159 | |
| 2160 | #. Mapping key (optional), consisting of a parenthesised sequence of characters |
| 2161 | (for example, ``(somename)``). |
| 2162 | |
| 2163 | #. Conversion flags (optional), which affect the result of some conversion |
| 2164 | types. |
| 2165 | |
| 2166 | #. Minimum field width (optional). If specified as an ``'*'`` (asterisk), the |
| 2167 | actual width is read from the next element of the tuple in *values*, and the |
| 2168 | object to convert comes after the minimum field width and optional precision. |
| 2169 | |
| 2170 | #. Precision (optional), given as a ``'.'`` (dot) followed by the precision. If |
Eli Bendersky | ef4902a | 2011-07-29 09:30:42 +0300 | [diff] [blame] | 2171 | specified as ``'*'`` (an asterisk), the actual precision is read from the next |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2172 | element of the tuple in *values*, and the value to convert comes after the |
| 2173 | precision. |
| 2174 | |
| 2175 | #. Length modifier (optional). |
| 2176 | |
| 2177 | #. Conversion type. |
| 2178 | |
| 2179 | When the right argument is a dictionary (or other mapping type), then the |
| 2180 | formats in the string *must* include a parenthesised mapping key into that |
| 2181 | dictionary inserted immediately after the ``'%'`` character. The mapping key |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 2182 | selects the value to be formatted from the mapping. For example: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2183 | |
Georg Brandl | edc9e7f | 2010-10-17 09:19:03 +0000 | [diff] [blame] | 2184 | >>> print('%(language)s has %(number)03d quote types.' % |
| 2185 | ... {'language': "Python", "number": 2}) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2186 | Python has 002 quote types. |
| 2187 | |
| 2188 | In this case no ``*`` specifiers may occur in a format (since they require a |
| 2189 | sequential parameter list). |
| 2190 | |
| 2191 | The conversion flag characters are: |
| 2192 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 2193 | .. index:: |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 2194 | single: # (hash); in printf-style formatting |
| 2195 | single: - (minus); in printf-style formatting |
| 2196 | single: + (plus); in printf-style formatting |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 2197 | single: space; in printf-style formatting |
| 2198 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2199 | +---------+---------------------------------------------------------------------+ |
| 2200 | | Flag | Meaning | |
| 2201 | +=========+=====================================================================+ |
| 2202 | | ``'#'`` | The value conversion will use the "alternate form" (where defined | |
| 2203 | | | below). | |
| 2204 | +---------+---------------------------------------------------------------------+ |
| 2205 | | ``'0'`` | The conversion will be zero padded for numeric values. | |
| 2206 | +---------+---------------------------------------------------------------------+ |
| 2207 | | ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` | |
| 2208 | | | conversion if both are given). | |
| 2209 | +---------+---------------------------------------------------------------------+ |
| 2210 | | ``' '`` | (a space) A blank should be left before a positive number (or empty | |
| 2211 | | | string) produced by a signed conversion. | |
| 2212 | +---------+---------------------------------------------------------------------+ |
| 2213 | | ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion | |
| 2214 | | | (overrides a "space" flag). | |
| 2215 | +---------+---------------------------------------------------------------------+ |
| 2216 | |
| 2217 | A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 2218 | is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2219 | |
| 2220 | The conversion types are: |
| 2221 | |
| 2222 | +------------+-----------------------------------------------------+-------+ |
| 2223 | | Conversion | Meaning | Notes | |
| 2224 | +============+=====================================================+=======+ |
| 2225 | | ``'d'`` | Signed integer decimal. | | |
| 2226 | +------------+-----------------------------------------------------+-------+ |
| 2227 | | ``'i'`` | Signed integer decimal. | | |
| 2228 | +------------+-----------------------------------------------------+-------+ |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 2229 | | ``'o'`` | Signed octal value. | \(1) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2230 | +------------+-----------------------------------------------------+-------+ |
Berker Peksag | 7b440df | 2016-12-15 05:37:56 +0300 | [diff] [blame] | 2231 | | ``'u'`` | Obsolete type -- it is identical to ``'d'``. | \(6) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2232 | +------------+-----------------------------------------------------+-------+ |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 2233 | | ``'x'`` | Signed hexadecimal (lowercase). | \(2) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2234 | +------------+-----------------------------------------------------+-------+ |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 2235 | | ``'X'`` | Signed hexadecimal (uppercase). | \(2) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2236 | +------------+-----------------------------------------------------+-------+ |
| 2237 | | ``'e'`` | Floating point exponential format (lowercase). | \(3) | |
| 2238 | +------------+-----------------------------------------------------+-------+ |
| 2239 | | ``'E'`` | Floating point exponential format (uppercase). | \(3) | |
| 2240 | +------------+-----------------------------------------------------+-------+ |
Eric Smith | 22b85b3 | 2008-07-17 19:18:29 +0000 | [diff] [blame] | 2241 | | ``'f'`` | Floating point decimal format. | \(3) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2242 | +------------+-----------------------------------------------------+-------+ |
Eric Smith | 22b85b3 | 2008-07-17 19:18:29 +0000 | [diff] [blame] | 2243 | | ``'F'`` | Floating point decimal format. | \(3) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2244 | +------------+-----------------------------------------------------+-------+ |
Christian Heimes | 8dc226f | 2008-05-06 23:45:46 +0000 | [diff] [blame] | 2245 | | ``'g'`` | Floating point format. Uses lowercase exponential | \(4) | |
| 2246 | | | format if exponent is less than -4 or not less than | | |
| 2247 | | | precision, decimal format otherwise. | | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2248 | +------------+-----------------------------------------------------+-------+ |
Christian Heimes | 8dc226f | 2008-05-06 23:45:46 +0000 | [diff] [blame] | 2249 | | ``'G'`` | Floating point format. Uses uppercase exponential | \(4) | |
| 2250 | | | format if exponent is less than -4 or not less than | | |
| 2251 | | | precision, decimal format otherwise. | | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2252 | +------------+-----------------------------------------------------+-------+ |
| 2253 | | ``'c'`` | Single character (accepts integer or single | | |
| 2254 | | | character string). | | |
| 2255 | +------------+-----------------------------------------------------+-------+ |
Ezio Melotti | 0639d5a | 2009-12-19 23:26:38 +0000 | [diff] [blame] | 2256 | | ``'r'`` | String (converts any Python object using | \(5) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2257 | | | :func:`repr`). | | |
| 2258 | +------------+-----------------------------------------------------+-------+ |
Eli Bendersky | ef4902a | 2011-07-29 09:30:42 +0300 | [diff] [blame] | 2259 | | ``'s'`` | String (converts any Python object using | \(5) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2260 | | | :func:`str`). | | |
| 2261 | +------------+-----------------------------------------------------+-------+ |
Eli Bendersky | ef4902a | 2011-07-29 09:30:42 +0300 | [diff] [blame] | 2262 | | ``'a'`` | String (converts any Python object using | \(5) | |
| 2263 | | | :func:`ascii`). | | |
| 2264 | +------------+-----------------------------------------------------+-------+ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2265 | | ``'%'`` | No argument is converted, results in a ``'%'`` | | |
| 2266 | | | character in the result. | | |
| 2267 | +------------+-----------------------------------------------------+-------+ |
| 2268 | |
| 2269 | Notes: |
| 2270 | |
| 2271 | (1) |
Martin Panter | 41176ae | 2016-12-11 01:07:29 +0000 | [diff] [blame] | 2272 | The alternate form causes a leading octal specifier (``'0o'``) to be |
| 2273 | inserted before the first digit. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2274 | |
| 2275 | (2) |
| 2276 | The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether |
Martin Panter | 41176ae | 2016-12-11 01:07:29 +0000 | [diff] [blame] | 2277 | the ``'x'`` or ``'X'`` format was used) to be inserted before the first digit. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2278 | |
| 2279 | (3) |
| 2280 | The alternate form causes the result to always contain a decimal point, even if |
| 2281 | no digits follow it. |
| 2282 | |
| 2283 | The precision determines the number of digits after the decimal point and |
| 2284 | defaults to 6. |
| 2285 | |
| 2286 | (4) |
| 2287 | The alternate form causes the result to always contain a decimal point, and |
| 2288 | trailing zeroes are not removed as they would otherwise be. |
| 2289 | |
| 2290 | The precision determines the number of significant digits before and after the |
| 2291 | decimal point and defaults to 6. |
| 2292 | |
| 2293 | (5) |
Eli Bendersky | ef4902a | 2011-07-29 09:30:42 +0300 | [diff] [blame] | 2294 | If precision is ``N``, the output is truncated to ``N`` characters. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2295 | |
Berker Peksag | 7b440df | 2016-12-15 05:37:56 +0300 | [diff] [blame] | 2296 | (6) |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 2297 | See :pep:`237`. |
| 2298 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2299 | Since Python strings have an explicit length, ``%s`` conversions do not assume |
| 2300 | that ``'\0'`` is the end of the string. |
| 2301 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 2302 | .. XXX Examples? |
| 2303 | |
Mark Dickinson | 33841c3 | 2009-05-01 15:37:04 +0000 | [diff] [blame] | 2304 | .. versionchanged:: 3.1 |
| 2305 | ``%f`` conversions for numbers whose absolute value is over 1e50 are no |
| 2306 | longer replaced by ``%g`` conversions. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2307 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2308 | |
Chris Jerdonek | 5fae0e5 | 2012-11-20 17:45:51 -0800 | [diff] [blame] | 2309 | .. index:: |
| 2310 | single: buffer protocol; binary sequence types |
| 2311 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2312 | .. _binaryseq: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2313 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2314 | Binary Sequence Types --- :class:`bytes`, :class:`bytearray`, :class:`memoryview` |
| 2315 | ================================================================================= |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2316 | |
| 2317 | .. index:: |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2318 | object: bytes |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 2319 | object: bytearray |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2320 | object: memoryview |
| 2321 | module: array |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2322 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2323 | The core built-in types for manipulating binary data are :class:`bytes` and |
| 2324 | :class:`bytearray`. They are supported by :class:`memoryview` which uses |
Chris Jerdonek | 5fae0e5 | 2012-11-20 17:45:51 -0800 | [diff] [blame] | 2325 | the :ref:`buffer protocol <bufferobjects>` to access the memory of other |
| 2326 | binary objects without needing to make a copy. |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2327 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2328 | The :mod:`array` module supports efficient storage of basic data types like |
| 2329 | 32-bit integers and IEEE754 double-precision floating values. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2330 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2331 | .. _typebytes: |
Senthil Kumaran | 7cafd26 | 2010-10-02 03:16:04 +0000 | [diff] [blame] | 2332 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2333 | Bytes Objects |
| 2334 | ------------- |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2335 | |
| 2336 | .. index:: object: bytes |
| 2337 | |
| 2338 | Bytes objects are immutable sequences of single bytes. Since many major |
| 2339 | binary protocols are based on the ASCII text encoding, bytes objects offer |
| 2340 | several methods that are only valid when working with ASCII compatible |
| 2341 | data and are closely related to string objects in a variety of other ways. |
| 2342 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2343 | .. class:: bytes([source[, encoding[, errors]]]) |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2344 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2345 | Firstly, the syntax for bytes literals is largely the same as that for string |
| 2346 | literals, except that a ``b`` prefix is added: |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2347 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2348 | * Single quotes: ``b'still allows embedded "double" quotes'`` |
| 2349 | * Double quotes: ``b"still allows embedded 'single' quotes"``. |
| 2350 | * Triple quoted: ``b'''3 single quotes'''``, ``b"""3 double quotes"""`` |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2351 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2352 | Only ASCII characters are permitted in bytes literals (regardless of the |
| 2353 | declared source code encoding). Any binary values over 127 must be entered |
| 2354 | into bytes literals using the appropriate escape sequence. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2355 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2356 | As with string literals, bytes literals may also use a ``r`` prefix to disable |
| 2357 | processing of escape sequences. See :ref:`strings` for more about the various |
| 2358 | forms of bytes literal, including supported escape sequences. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2359 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2360 | While bytes literals and representations are based on ASCII text, bytes |
| 2361 | objects actually behave like immutable sequences of integers, with each |
| 2362 | value in the sequence restricted such that ``0 <= x < 256`` (attempts to |
Andrés Delfino | 03dd0e7 | 2018-07-07 16:00:46 -0300 | [diff] [blame] | 2363 | violate this restriction will trigger :exc:`ValueError`). This is done |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2364 | deliberately to emphasise that while many binary formats include ASCII based |
| 2365 | elements and can be usefully manipulated with some text-oriented algorithms, |
| 2366 | this is not generally the case for arbitrary binary data (blindly applying |
| 2367 | text processing algorithms to binary data formats that are not ASCII |
| 2368 | compatible will usually lead to data corruption). |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2369 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2370 | In addition to the literal forms, bytes objects can be created in a number of |
| 2371 | other ways: |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2372 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2373 | * A zero-filled bytes object of a specified length: ``bytes(10)`` |
| 2374 | * From an iterable of integers: ``bytes(range(20))`` |
| 2375 | * Copying existing binary data via the buffer protocol: ``bytes(obj)`` |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 2376 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2377 | Also see the :ref:`bytes <func-bytes>` built-in. |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2378 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2379 | Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal |
| 2380 | numbers are a commonly used format for describing binary data. Accordingly, |
| 2381 | the bytes type has an additional class method to read data in that format: |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2382 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2383 | .. classmethod:: fromhex(string) |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2384 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2385 | This :class:`bytes` class method returns a bytes object, decoding the |
| 2386 | given string object. The string must contain two hexadecimal digits per |
| 2387 | byte, with ASCII whitespace being ignored. |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2388 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2389 | >>> bytes.fromhex('2Ef0 F1f2 ') |
| 2390 | b'.\xf0\xf1\xf2' |
Serhiy Storchaka | dd1da7f | 2016-12-19 18:51:37 +0200 | [diff] [blame] | 2391 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2392 | .. versionchanged:: 3.7 |
| 2393 | :meth:`bytes.fromhex` now skips all ASCII whitespace in the string, |
| 2394 | not just spaces. |
Gregory P. Smith | 8cb6569 | 2015-04-25 23:22:26 +0000 | [diff] [blame] | 2395 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2396 | A reverse conversion function exists to transform a bytes object into its |
| 2397 | hexadecimal representation. |
Gregory P. Smith | 8cb6569 | 2015-04-25 23:22:26 +0000 | [diff] [blame] | 2398 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2399 | .. method:: hex() |
Gregory P. Smith | 8cb6569 | 2015-04-25 23:22:26 +0000 | [diff] [blame] | 2400 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2401 | Return a string object containing two hexadecimal digits for each |
| 2402 | byte in the instance. |
Gregory P. Smith | 8cb6569 | 2015-04-25 23:22:26 +0000 | [diff] [blame] | 2403 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2404 | >>> b'\xf0\xf1\xf2'.hex() |
| 2405 | 'f0f1f2' |
| 2406 | |
Gregory P. Smith | 0c2f930 | 2019-05-29 11:46:58 -0700 | [diff] [blame] | 2407 | If you want to make the hex string easier to read, you can specify a |
| 2408 | single character separator *sep* parameter to include in the output. |
| 2409 | By default between each byte. A second optional *bytes_per_sep* |
| 2410 | parameter controls the spacing. Positive values calculate the |
| 2411 | separator position from the right, negative values from the left. |
| 2412 | |
| 2413 | >>> value = b'\xf0\xf1\xf2' |
| 2414 | >>> value.hex('-') |
| 2415 | 'f0-f1-f2' |
| 2416 | >>> value.hex('_', 2) |
| 2417 | 'f0_f1f2' |
| 2418 | >>> b'UUDDLRLRAB'.hex(' ', -4) |
| 2419 | '55554444 4c524c52 4142' |
| 2420 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2421 | .. versionadded:: 3.5 |
Gregory P. Smith | 8cb6569 | 2015-04-25 23:22:26 +0000 | [diff] [blame] | 2422 | |
Gregory P. Smith | 0c2f930 | 2019-05-29 11:46:58 -0700 | [diff] [blame] | 2423 | .. versionchanged:: 3.8 |
| 2424 | :meth:`bytes.hex` now supports optional *sep* and *bytes_per_sep* |
| 2425 | parameters to insert separators between bytes in the hex output. |
| 2426 | |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2427 | Since bytes objects are sequences of integers (akin to a tuple), for a bytes |
| 2428 | object *b*, ``b[0]`` will be an integer, while ``b[0:1]`` will be a bytes |
| 2429 | object of length 1. (This contrasts with text strings, where both indexing |
| 2430 | and slicing will produce a string of length 1) |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2431 | |
| 2432 | The representation of bytes objects uses the literal format (``b'...'``) |
| 2433 | since it is often more useful than e.g. ``bytes([46, 46, 46])``. You can |
| 2434 | always convert a bytes object into a list of integers using ``list(b)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2435 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2436 | .. note:: |
| 2437 | For Python 2.x users: In the Python 2.x series, a variety of implicit |
| 2438 | conversions between 8-bit strings (the closest thing 2.x offers to a |
| 2439 | built-in binary data type) and Unicode strings were permitted. This was a |
| 2440 | backwards compatibility workaround to account for the fact that Python |
| 2441 | originally only supported 8-bit text, and Unicode text was a later |
| 2442 | addition. In Python 3.x, those implicit conversions are gone - conversions |
| 2443 | between 8-bit binary data and Unicode text must be explicit, and bytes and |
| 2444 | string objects will always compare unequal. |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 2445 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2446 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2447 | .. _typebytearray: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2448 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2449 | Bytearray Objects |
| 2450 | ----------------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2451 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2452 | .. index:: object: bytearray |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 2453 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2454 | :class:`bytearray` objects are a mutable counterpart to :class:`bytes` |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2455 | objects. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2456 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2457 | .. class:: bytearray([source[, encoding[, errors]]]) |
Eli Bendersky | cbbaa96 | 2011-02-25 05:47:53 +0000 | [diff] [blame] | 2458 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2459 | There is no dedicated literal syntax for bytearray objects, instead |
| 2460 | they are always created by calling the constructor: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2461 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2462 | * Creating an empty instance: ``bytearray()`` |
| 2463 | * Creating a zero-filled instance with a given length: ``bytearray(10)`` |
| 2464 | * From an iterable of integers: ``bytearray(range(20))`` |
| 2465 | * Copying existing binary data via the buffer protocol: ``bytearray(b'Hi!')`` |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 2466 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2467 | As bytearray objects are mutable, they support the |
| 2468 | :ref:`mutable <typesseq-mutable>` sequence operations in addition to the |
| 2469 | common bytes and bytearray operations described in :ref:`bytes-methods`. |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2470 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2471 | Also see the :ref:`bytearray <func-bytearray>` built-in. |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2472 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2473 | Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal |
| 2474 | numbers are a commonly used format for describing binary data. Accordingly, |
| 2475 | the bytearray type has an additional class method to read data in that format: |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2476 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2477 | .. classmethod:: fromhex(string) |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2478 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2479 | This :class:`bytearray` class method returns bytearray object, decoding |
| 2480 | the given string object. The string must contain two hexadecimal digits |
| 2481 | per byte, with ASCII whitespace being ignored. |
Serhiy Storchaka | dd1da7f | 2016-12-19 18:51:37 +0200 | [diff] [blame] | 2482 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2483 | >>> bytearray.fromhex('2Ef0 F1f2 ') |
| 2484 | bytearray(b'.\xf0\xf1\xf2') |
Gregory P. Smith | 8cb6569 | 2015-04-25 23:22:26 +0000 | [diff] [blame] | 2485 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2486 | .. versionchanged:: 3.7 |
| 2487 | :meth:`bytearray.fromhex` now skips all ASCII whitespace in the string, |
| 2488 | not just spaces. |
Gregory P. Smith | 8cb6569 | 2015-04-25 23:22:26 +0000 | [diff] [blame] | 2489 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2490 | A reverse conversion function exists to transform a bytearray object into its |
| 2491 | hexadecimal representation. |
Gregory P. Smith | 8cb6569 | 2015-04-25 23:22:26 +0000 | [diff] [blame] | 2492 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2493 | .. method:: hex() |
Gregory P. Smith | 8cb6569 | 2015-04-25 23:22:26 +0000 | [diff] [blame] | 2494 | |
csabella | c6db481 | 2017-04-26 01:47:01 -0400 | [diff] [blame] | 2495 | Return a string object containing two hexadecimal digits for each |
| 2496 | byte in the instance. |
| 2497 | |
| 2498 | >>> bytearray(b'\xf0\xf1\xf2').hex() |
| 2499 | 'f0f1f2' |
| 2500 | |
| 2501 | .. versionadded:: 3.5 |
Gregory P. Smith | 8cb6569 | 2015-04-25 23:22:26 +0000 | [diff] [blame] | 2502 | |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2503 | Since bytearray objects are sequences of integers (akin to a list), for a |
| 2504 | bytearray object *b*, ``b[0]`` will be an integer, while ``b[0:1]`` will be |
| 2505 | a bytearray object of length 1. (This contrasts with text strings, where |
| 2506 | both indexing and slicing will produce a string of length 1) |
| 2507 | |
| 2508 | The representation of bytearray objects uses the bytes literal format |
| 2509 | (``bytearray(b'...')``) since it is often more useful than e.g. |
| 2510 | ``bytearray([46, 46, 46])``. You can always convert a bytearray object into |
| 2511 | a list of integers using ``list(b)``. |
| 2512 | |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 2513 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2514 | .. _bytes-methods: |
| 2515 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2516 | Bytes and Bytearray Operations |
| 2517 | ------------------------------ |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2518 | |
| 2519 | .. index:: pair: bytes; methods |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 2520 | pair: bytearray; methods |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2521 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2522 | Both bytes and bytearray objects support the :ref:`common <typesseq-common>` |
| 2523 | sequence operations. They interoperate not just with operands of the same |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2524 | type, but with any :term:`bytes-like object`. Due to this flexibility, they can be |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2525 | freely mixed in operations without causing errors. However, the return type |
| 2526 | of the result may depend on the order of operands. |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 2527 | |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 2528 | .. note:: |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2529 | |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 2530 | The methods on bytes and bytearray objects don't accept strings as their |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 2531 | arguments, just as the methods on strings don't accept bytes as their |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2532 | arguments. For example, you have to write:: |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2533 | |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 2534 | a = "abc" |
| 2535 | b = a.replace("a", "f") |
| 2536 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2537 | and:: |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 2538 | |
| 2539 | a = b"abc" |
| 2540 | b = a.replace(b"a", b"f") |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2541 | |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2542 | Some bytes and bytearray operations assume the use of ASCII compatible |
| 2543 | binary formats, and hence should be avoided when working with arbitrary |
| 2544 | binary data. These restrictions are covered below. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2545 | |
| 2546 | .. note:: |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2547 | Using these ASCII based operations to manipulate binary data that is not |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2548 | stored in an ASCII based format may lead to data corruption. |
| 2549 | |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2550 | The following methods on bytes and bytearray objects can be used with |
| 2551 | arbitrary binary data. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2552 | |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2553 | .. method:: bytes.count(sub[, start[, end]]) |
| 2554 | bytearray.count(sub[, start[, end]]) |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2555 | |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2556 | Return the number of non-overlapping occurrences of subsequence *sub* in |
| 2557 | the range [*start*, *end*]. Optional arguments *start* and *end* are |
| 2558 | interpreted as in slice notation. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 2559 | |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2560 | The subsequence to search for may be any :term:`bytes-like object` or an |
| 2561 | integer in the range 0 to 255. |
| 2562 | |
| 2563 | .. versionchanged:: 3.3 |
| 2564 | Also accept an integer in the range 0 to 255 as the subsequence. |
| 2565 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2566 | |
Victor Stinner | e14e212 | 2010-11-07 18:41:46 +0000 | [diff] [blame] | 2567 | .. method:: bytes.decode(encoding="utf-8", errors="strict") |
| 2568 | bytearray.decode(encoding="utf-8", errors="strict") |
Georg Brandl | 4f5f98d | 2009-05-04 21:01:20 +0000 | [diff] [blame] | 2569 | |
Victor Stinner | e14e212 | 2010-11-07 18:41:46 +0000 | [diff] [blame] | 2570 | Return a string decoded from the given bytes. Default encoding is |
| 2571 | ``'utf-8'``. *errors* may be given to set a different |
Georg Brandl | 4f5f98d | 2009-05-04 21:01:20 +0000 | [diff] [blame] | 2572 | error handling scheme. The default for *errors* is ``'strict'``, meaning |
| 2573 | that encoding errors raise a :exc:`UnicodeError`. Other possible values are |
| 2574 | ``'ignore'``, ``'replace'`` and any other name registered via |
Nick Coghlan | b9fdb7a | 2015-01-07 00:22:00 +1000 | [diff] [blame] | 2575 | :func:`codecs.register_error`, see section :ref:`error-handlers`. For a |
Georg Brandl | 4f5f98d | 2009-05-04 21:01:20 +0000 | [diff] [blame] | 2576 | list of possible encodings, see section :ref:`standard-encodings`. |
| 2577 | |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2578 | .. note:: |
| 2579 | |
| 2580 | Passing the *encoding* argument to :class:`str` allows decoding any |
| 2581 | :term:`bytes-like object` directly, without needing to make a temporary |
| 2582 | bytes or bytearray object. |
| 2583 | |
Benjamin Peterson | 308d637 | 2009-09-18 21:42:35 +0000 | [diff] [blame] | 2584 | .. versionchanged:: 3.1 |
| 2585 | Added support for keyword arguments. |
| 2586 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2587 | |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2588 | .. method:: bytes.endswith(suffix[, start[, end]]) |
| 2589 | bytearray.endswith(suffix[, start[, end]]) |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2590 | |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2591 | Return ``True`` if the binary data ends with the specified *suffix*, |
| 2592 | otherwise return ``False``. *suffix* can also be a tuple of suffixes to |
| 2593 | look for. With optional *start*, test beginning at that position. With |
| 2594 | optional *end*, stop comparing at that position. |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2595 | |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2596 | The suffix(es) to search for may be any :term:`bytes-like object`. |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2597 | |
Georg Brandl | abc3877 | 2009-04-12 15:51:51 +0000 | [diff] [blame] | 2598 | |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2599 | .. method:: bytes.find(sub[, start[, end]]) |
| 2600 | bytearray.find(sub[, start[, end]]) |
| 2601 | |
| 2602 | Return the lowest index in the data where the subsequence *sub* is found, |
| 2603 | such that *sub* is contained in the slice ``s[start:end]``. Optional |
| 2604 | arguments *start* and *end* are interpreted as in slice notation. Return |
| 2605 | ``-1`` if *sub* is not found. |
| 2606 | |
| 2607 | The subsequence to search for may be any :term:`bytes-like object` or an |
| 2608 | integer in the range 0 to 255. |
| 2609 | |
| 2610 | .. note:: |
| 2611 | |
| 2612 | The :meth:`~bytes.find` method should be used only if you need to know the |
| 2613 | position of *sub*. To check if *sub* is a substring or not, use the |
| 2614 | :keyword:`in` operator:: |
| 2615 | |
| 2616 | >>> b'Py' in b'Python' |
| 2617 | True |
| 2618 | |
| 2619 | .. versionchanged:: 3.3 |
| 2620 | Also accept an integer in the range 0 to 255 as the subsequence. |
| 2621 | |
| 2622 | |
| 2623 | .. method:: bytes.index(sub[, start[, end]]) |
| 2624 | bytearray.index(sub[, start[, end]]) |
| 2625 | |
| 2626 | Like :meth:`~bytes.find`, but raise :exc:`ValueError` when the |
| 2627 | subsequence is not found. |
| 2628 | |
| 2629 | The subsequence to search for may be any :term:`bytes-like object` or an |
| 2630 | integer in the range 0 to 255. |
| 2631 | |
| 2632 | .. versionchanged:: 3.3 |
| 2633 | Also accept an integer in the range 0 to 255 as the subsequence. |
| 2634 | |
| 2635 | |
| 2636 | .. method:: bytes.join(iterable) |
| 2637 | bytearray.join(iterable) |
| 2638 | |
| 2639 | Return a bytes or bytearray object which is the concatenation of the |
Sanyam Khurana | 08e2f35 | 2017-05-27 11:14:41 +0530 | [diff] [blame] | 2640 | binary data sequences in *iterable*. A :exc:`TypeError` will be raised |
| 2641 | if there are any values in *iterable* that are not :term:`bytes-like |
| 2642 | objects <bytes-like object>`, including :class:`str` objects. The |
| 2643 | separator between elements is the contents of the bytes or |
| 2644 | bytearray object providing this method. |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2645 | |
| 2646 | |
| 2647 | .. staticmethod:: bytes.maketrans(from, to) |
| 2648 | bytearray.maketrans(from, to) |
| 2649 | |
| 2650 | This static method returns a translation table usable for |
| 2651 | :meth:`bytes.translate` that will map each character in *from* into the |
| 2652 | character at the same position in *to*; *from* and *to* must both be |
| 2653 | :term:`bytes-like objects <bytes-like object>` and have the same length. |
| 2654 | |
| 2655 | .. versionadded:: 3.1 |
| 2656 | |
| 2657 | |
| 2658 | .. method:: bytes.partition(sep) |
| 2659 | bytearray.partition(sep) |
| 2660 | |
| 2661 | Split the sequence at the first occurrence of *sep*, and return a 3-tuple |
Serhiy Storchaka | a231428 | 2017-10-29 02:11:54 +0300 | [diff] [blame] | 2662 | containing the part before the separator, the separator itself or its |
| 2663 | bytearray copy, and the part after the separator. |
| 2664 | If the separator is not found, return a 3-tuple |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2665 | containing a copy of the original sequence, followed by two empty bytes or |
| 2666 | bytearray objects. |
| 2667 | |
| 2668 | The separator to search for may be any :term:`bytes-like object`. |
| 2669 | |
| 2670 | |
| 2671 | .. method:: bytes.replace(old, new[, count]) |
| 2672 | bytearray.replace(old, new[, count]) |
| 2673 | |
| 2674 | Return a copy of the sequence with all occurrences of subsequence *old* |
| 2675 | replaced by *new*. If the optional argument *count* is given, only the |
| 2676 | first *count* occurrences are replaced. |
| 2677 | |
| 2678 | The subsequence to search for and its replacement may be any |
| 2679 | :term:`bytes-like object`. |
| 2680 | |
| 2681 | .. note:: |
| 2682 | |
| 2683 | The bytearray version of this method does *not* operate in place - it |
| 2684 | always produces a new object, even if no changes were made. |
| 2685 | |
| 2686 | |
| 2687 | .. method:: bytes.rfind(sub[, start[, end]]) |
| 2688 | bytearray.rfind(sub[, start[, end]]) |
| 2689 | |
| 2690 | Return the highest index in the sequence where the subsequence *sub* is |
| 2691 | found, such that *sub* is contained within ``s[start:end]``. Optional |
| 2692 | arguments *start* and *end* are interpreted as in slice notation. Return |
| 2693 | ``-1`` on failure. |
| 2694 | |
| 2695 | The subsequence to search for may be any :term:`bytes-like object` or an |
| 2696 | integer in the range 0 to 255. |
| 2697 | |
| 2698 | .. versionchanged:: 3.3 |
| 2699 | Also accept an integer in the range 0 to 255 as the subsequence. |
| 2700 | |
| 2701 | |
| 2702 | .. method:: bytes.rindex(sub[, start[, end]]) |
| 2703 | bytearray.rindex(sub[, start[, end]]) |
| 2704 | |
| 2705 | Like :meth:`~bytes.rfind` but raises :exc:`ValueError` when the |
| 2706 | subsequence *sub* is not found. |
| 2707 | |
| 2708 | The subsequence to search for may be any :term:`bytes-like object` or an |
| 2709 | integer in the range 0 to 255. |
| 2710 | |
| 2711 | .. versionchanged:: 3.3 |
| 2712 | Also accept an integer in the range 0 to 255 as the subsequence. |
| 2713 | |
| 2714 | |
| 2715 | .. method:: bytes.rpartition(sep) |
| 2716 | bytearray.rpartition(sep) |
| 2717 | |
| 2718 | Split the sequence at the last occurrence of *sep*, and return a 3-tuple |
Serhiy Storchaka | a231428 | 2017-10-29 02:11:54 +0300 | [diff] [blame] | 2719 | containing the part before the separator, the separator itself or its |
| 2720 | bytearray copy, and the part after the separator. |
| 2721 | If the separator is not found, return a 3-tuple |
pewscorner | efc4870 | 2019-04-11 08:58:43 +0200 | [diff] [blame] | 2722 | containing two empty bytes or bytearray objects, followed by a copy of the |
| 2723 | original sequence. |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2724 | |
| 2725 | The separator to search for may be any :term:`bytes-like object`. |
| 2726 | |
| 2727 | |
| 2728 | .. method:: bytes.startswith(prefix[, start[, end]]) |
| 2729 | bytearray.startswith(prefix[, start[, end]]) |
| 2730 | |
| 2731 | Return ``True`` if the binary data starts with the specified *prefix*, |
| 2732 | otherwise return ``False``. *prefix* can also be a tuple of prefixes to |
| 2733 | look for. With optional *start*, test beginning at that position. With |
| 2734 | optional *end*, stop comparing at that position. |
| 2735 | |
| 2736 | The prefix(es) to search for may be any :term:`bytes-like object`. |
| 2737 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 2738 | |
Pablo Galindo | de76c07 | 2019-06-07 00:38:41 +0100 | [diff] [blame^] | 2739 | .. method:: bytes.translate(table, /, delete=b'') |
| 2740 | bytearray.translate(table, /, delete=b'') |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2741 | |
Georg Brandl | 454636f | 2008-12-27 23:33:20 +0000 | [diff] [blame] | 2742 | Return a copy of the bytes or bytearray object where all bytes occurring in |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2743 | the optional argument *delete* are removed, and the remaining bytes have |
| 2744 | been mapped through the given translation table, which must be a bytes |
| 2745 | object of length 256. |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2746 | |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2747 | You can use the :func:`bytes.maketrans` method to create a translation |
| 2748 | table. |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2749 | |
Georg Brandl | 454636f | 2008-12-27 23:33:20 +0000 | [diff] [blame] | 2750 | Set the *table* argument to ``None`` for translations that only delete |
| 2751 | characters:: |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2752 | |
Georg Brandl | 454636f | 2008-12-27 23:33:20 +0000 | [diff] [blame] | 2753 | >>> b'read this short text'.translate(None, b'aeiou') |
| 2754 | b'rd ths shrt txt' |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2755 | |
Martin Panter | 1b6c6da | 2016-08-27 08:35:02 +0000 | [diff] [blame] | 2756 | .. versionchanged:: 3.6 |
| 2757 | *delete* is now supported as a keyword argument. |
| 2758 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2759 | |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2760 | The following methods on bytes and bytearray objects have default behaviours |
| 2761 | that assume the use of ASCII compatible binary formats, but can still be used |
| 2762 | with arbitrary binary data by passing appropriate arguments. Note that all of |
| 2763 | the bytearray methods in this section do *not* operate in place, and instead |
| 2764 | produce new objects. |
Georg Brandl | abc3877 | 2009-04-12 15:51:51 +0000 | [diff] [blame] | 2765 | |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2766 | .. method:: bytes.center(width[, fillbyte]) |
| 2767 | bytearray.center(width[, fillbyte]) |
Georg Brandl | abc3877 | 2009-04-12 15:51:51 +0000 | [diff] [blame] | 2768 | |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2769 | Return a copy of the object centered in a sequence of length *width*. |
| 2770 | Padding is done using the specified *fillbyte* (default is an ASCII |
| 2771 | space). For :class:`bytes` objects, the original sequence is returned if |
| 2772 | *width* is less than or equal to ``len(s)``. |
| 2773 | |
| 2774 | .. note:: |
| 2775 | |
| 2776 | The bytearray version of this method does *not* operate in place - |
| 2777 | it always produces a new object, even if no changes were made. |
| 2778 | |
| 2779 | |
| 2780 | .. method:: bytes.ljust(width[, fillbyte]) |
| 2781 | bytearray.ljust(width[, fillbyte]) |
| 2782 | |
| 2783 | Return a copy of the object left justified in a sequence of length *width*. |
| 2784 | Padding is done using the specified *fillbyte* (default is an ASCII |
| 2785 | space). For :class:`bytes` objects, the original sequence is returned if |
| 2786 | *width* is less than or equal to ``len(s)``. |
| 2787 | |
| 2788 | .. note:: |
| 2789 | |
| 2790 | The bytearray version of this method does *not* operate in place - |
| 2791 | it always produces a new object, even if no changes were made. |
| 2792 | |
| 2793 | |
| 2794 | .. method:: bytes.lstrip([chars]) |
| 2795 | bytearray.lstrip([chars]) |
| 2796 | |
| 2797 | Return a copy of the sequence with specified leading bytes removed. The |
| 2798 | *chars* argument is a binary sequence specifying the set of byte values to |
| 2799 | be removed - the name refers to the fact this method is usually used with |
| 2800 | ASCII characters. If omitted or ``None``, the *chars* argument defaults |
| 2801 | to removing ASCII whitespace. The *chars* argument is not a prefix; |
| 2802 | rather, all combinations of its values are stripped:: |
| 2803 | |
| 2804 | >>> b' spacious '.lstrip() |
| 2805 | b'spacious ' |
| 2806 | >>> b'www.example.com'.lstrip(b'cmowz.') |
| 2807 | b'example.com' |
| 2808 | |
| 2809 | The binary sequence of byte values to remove may be any |
| 2810 | :term:`bytes-like object`. |
| 2811 | |
| 2812 | .. note:: |
| 2813 | |
| 2814 | The bytearray version of this method does *not* operate in place - |
| 2815 | it always produces a new object, even if no changes were made. |
| 2816 | |
| 2817 | |
| 2818 | .. method:: bytes.rjust(width[, fillbyte]) |
| 2819 | bytearray.rjust(width[, fillbyte]) |
| 2820 | |
| 2821 | Return a copy of the object right justified in a sequence of length *width*. |
| 2822 | Padding is done using the specified *fillbyte* (default is an ASCII |
| 2823 | space). For :class:`bytes` objects, the original sequence is returned if |
| 2824 | *width* is less than or equal to ``len(s)``. |
| 2825 | |
| 2826 | .. note:: |
| 2827 | |
| 2828 | The bytearray version of this method does *not* operate in place - |
| 2829 | it always produces a new object, even if no changes were made. |
| 2830 | |
| 2831 | |
| 2832 | .. method:: bytes.rsplit(sep=None, maxsplit=-1) |
| 2833 | bytearray.rsplit(sep=None, maxsplit=-1) |
| 2834 | |
| 2835 | Split the binary sequence into subsequences of the same type, using *sep* |
| 2836 | as the delimiter string. If *maxsplit* is given, at most *maxsplit* splits |
| 2837 | are done, the *rightmost* ones. If *sep* is not specified or ``None``, |
| 2838 | any subsequence consisting solely of ASCII whitespace is a separator. |
| 2839 | Except for splitting from the right, :meth:`rsplit` behaves like |
| 2840 | :meth:`split` which is described in detail below. |
| 2841 | |
| 2842 | |
| 2843 | .. method:: bytes.rstrip([chars]) |
| 2844 | bytearray.rstrip([chars]) |
| 2845 | |
| 2846 | Return a copy of the sequence with specified trailing bytes removed. The |
| 2847 | *chars* argument is a binary sequence specifying the set of byte values to |
| 2848 | be removed - the name refers to the fact this method is usually used with |
| 2849 | ASCII characters. If omitted or ``None``, the *chars* argument defaults to |
| 2850 | removing ASCII whitespace. The *chars* argument is not a suffix; rather, |
| 2851 | all combinations of its values are stripped:: |
| 2852 | |
| 2853 | >>> b' spacious '.rstrip() |
| 2854 | b' spacious' |
| 2855 | >>> b'mississippi'.rstrip(b'ipz') |
| 2856 | b'mississ' |
| 2857 | |
| 2858 | The binary sequence of byte values to remove may be any |
| 2859 | :term:`bytes-like object`. |
| 2860 | |
| 2861 | .. note:: |
| 2862 | |
| 2863 | The bytearray version of this method does *not* operate in place - |
| 2864 | it always produces a new object, even if no changes were made. |
| 2865 | |
| 2866 | |
| 2867 | .. method:: bytes.split(sep=None, maxsplit=-1) |
| 2868 | bytearray.split(sep=None, maxsplit=-1) |
| 2869 | |
| 2870 | Split the binary sequence into subsequences of the same type, using *sep* |
| 2871 | as the delimiter string. If *maxsplit* is given and non-negative, at most |
| 2872 | *maxsplit* splits are done (thus, the list will have at most ``maxsplit+1`` |
| 2873 | elements). If *maxsplit* is not specified or is ``-1``, then there is no |
| 2874 | limit on the number of splits (all possible splits are made). |
| 2875 | |
| 2876 | If *sep* is given, consecutive delimiters are not grouped together and are |
| 2877 | deemed to delimit empty subsequences (for example, ``b'1,,2'.split(b',')`` |
| 2878 | returns ``[b'1', b'', b'2']``). The *sep* argument may consist of a |
| 2879 | multibyte sequence (for example, ``b'1<>2<>3'.split(b'<>')`` returns |
| 2880 | ``[b'1', b'2', b'3']``). Splitting an empty sequence with a specified |
| 2881 | separator returns ``[b'']`` or ``[bytearray(b'')]`` depending on the type |
| 2882 | of object being split. The *sep* argument may be any |
| 2883 | :term:`bytes-like object`. |
| 2884 | |
| 2885 | For example:: |
| 2886 | |
| 2887 | >>> b'1,2,3'.split(b',') |
| 2888 | [b'1', b'2', b'3'] |
| 2889 | >>> b'1,2,3'.split(b',', maxsplit=1) |
Benjamin Peterson | eb83ffe | 2014-09-22 22:43:50 -0400 | [diff] [blame] | 2890 | [b'1', b'2,3'] |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 2891 | >>> b'1,2,,3,'.split(b',') |
| 2892 | [b'1', b'2', b'', b'3', b''] |
| 2893 | |
| 2894 | If *sep* is not specified or is ``None``, a different splitting algorithm |
| 2895 | is applied: runs of consecutive ASCII whitespace are regarded as a single |
| 2896 | separator, and the result will contain no empty strings at the start or |
| 2897 | end if the sequence has leading or trailing whitespace. Consequently, |
| 2898 | splitting an empty sequence or a sequence consisting solely of ASCII |
| 2899 | whitespace without a specified separator returns ``[]``. |
| 2900 | |
| 2901 | For example:: |
| 2902 | |
| 2903 | |
| 2904 | >>> b'1 2 3'.split() |
| 2905 | [b'1', b'2', b'3'] |
| 2906 | >>> b'1 2 3'.split(maxsplit=1) |
| 2907 | [b'1', b'2 3'] |
| 2908 | >>> b' 1 2 3 '.split() |
| 2909 | [b'1', b'2', b'3'] |
| 2910 | |
| 2911 | |
| 2912 | .. method:: bytes.strip([chars]) |
| 2913 | bytearray.strip([chars]) |
| 2914 | |
| 2915 | Return a copy of the sequence with specified leading and trailing bytes |
| 2916 | removed. The *chars* argument is a binary sequence specifying the set of |
| 2917 | byte values to be removed - the name refers to the fact this method is |
| 2918 | usually used with ASCII characters. If omitted or ``None``, the *chars* |
| 2919 | argument defaults to removing ASCII whitespace. The *chars* argument is |
| 2920 | not a prefix or suffix; rather, all combinations of its values are |
| 2921 | stripped:: |
| 2922 | |
| 2923 | >>> b' spacious '.strip() |
| 2924 | b'spacious' |
| 2925 | >>> b'www.example.com'.strip(b'cmowz.') |
| 2926 | b'example' |
| 2927 | |
| 2928 | The binary sequence of byte values to remove may be any |
| 2929 | :term:`bytes-like object`. |
| 2930 | |
| 2931 | .. note:: |
| 2932 | |
| 2933 | The bytearray version of this method does *not* operate in place - |
| 2934 | it always produces a new object, even if no changes were made. |
| 2935 | |
| 2936 | |
| 2937 | The following methods on bytes and bytearray objects assume the use of ASCII |
| 2938 | compatible binary formats and should not be applied to arbitrary binary data. |
| 2939 | Note that all of the bytearray methods in this section do *not* operate in |
| 2940 | place, and instead produce new objects. |
| 2941 | |
| 2942 | .. method:: bytes.capitalize() |
| 2943 | bytearray.capitalize() |
| 2944 | |
| 2945 | Return a copy of the sequence with each byte interpreted as an ASCII |
| 2946 | character, and the first byte capitalized and the rest lowercased. |
| 2947 | Non-ASCII byte values are passed through unchanged. |
| 2948 | |
| 2949 | .. note:: |
| 2950 | |
| 2951 | The bytearray version of this method does *not* operate in place - it |
| 2952 | always produces a new object, even if no changes were made. |
| 2953 | |
| 2954 | |
| 2955 | .. method:: bytes.expandtabs(tabsize=8) |
| 2956 | bytearray.expandtabs(tabsize=8) |
| 2957 | |
| 2958 | Return a copy of the sequence where all ASCII tab characters are replaced |
| 2959 | by one or more ASCII spaces, depending on the current column and the given |
| 2960 | tab size. Tab positions occur every *tabsize* bytes (default is 8, |
| 2961 | giving tab positions at columns 0, 8, 16 and so on). To expand the |
| 2962 | sequence, the current column is set to zero and the sequence is examined |
| 2963 | byte by byte. If the byte is an ASCII tab character (``b'\t'``), one or |
| 2964 | more space characters are inserted in the result until the current column |
| 2965 | is equal to the next tab position. (The tab character itself is not |
| 2966 | copied.) If the current byte is an ASCII newline (``b'\n'``) or |
| 2967 | carriage return (``b'\r'``), it is copied and the current column is reset |
| 2968 | to zero. Any other byte value is copied unchanged and the current column |
| 2969 | is incremented by one regardless of how the byte value is represented when |
| 2970 | printed:: |
| 2971 | |
| 2972 | >>> b'01\t012\t0123\t01234'.expandtabs() |
| 2973 | b'01 012 0123 01234' |
| 2974 | >>> b'01\t012\t0123\t01234'.expandtabs(4) |
| 2975 | b'01 012 0123 01234' |
| 2976 | |
| 2977 | .. note:: |
| 2978 | |
| 2979 | The bytearray version of this method does *not* operate in place - it |
| 2980 | always produces a new object, even if no changes were made. |
| 2981 | |
| 2982 | |
| 2983 | .. method:: bytes.isalnum() |
| 2984 | bytearray.isalnum() |
| 2985 | |
| 2986 | Return true if all bytes in the sequence are alphabetical ASCII characters |
| 2987 | or ASCII decimal digits and the sequence is not empty, false otherwise. |
| 2988 | Alphabetic ASCII characters are those byte values in the sequence |
| 2989 | ``b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'``. ASCII decimal |
| 2990 | digits are those byte values in the sequence ``b'0123456789'``. |
| 2991 | |
| 2992 | For example:: |
| 2993 | |
| 2994 | >>> b'ABCabc1'.isalnum() |
| 2995 | True |
| 2996 | >>> b'ABC abc1'.isalnum() |
| 2997 | False |
| 2998 | |
| 2999 | |
| 3000 | .. method:: bytes.isalpha() |
| 3001 | bytearray.isalpha() |
| 3002 | |
| 3003 | Return true if all bytes in the sequence are alphabetic ASCII characters |
| 3004 | and the sequence is not empty, false otherwise. Alphabetic ASCII |
| 3005 | characters are those byte values in the sequence |
| 3006 | ``b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'``. |
| 3007 | |
| 3008 | For example:: |
| 3009 | |
| 3010 | >>> b'ABCabc'.isalpha() |
| 3011 | True |
| 3012 | >>> b'ABCabc1'.isalpha() |
| 3013 | False |
| 3014 | |
| 3015 | |
INADA Naoki | a49ac99 | 2018-01-27 14:06:21 +0900 | [diff] [blame] | 3016 | .. method:: bytes.isascii() |
| 3017 | bytearray.isascii() |
| 3018 | |
| 3019 | Return true if the sequence is empty or all bytes in the sequence are ASCII, |
| 3020 | false otherwise. |
| 3021 | ASCII bytes are in the range 0-0x7F. |
| 3022 | |
| 3023 | .. versionadded:: 3.7 |
| 3024 | |
| 3025 | |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 3026 | .. method:: bytes.isdigit() |
| 3027 | bytearray.isdigit() |
| 3028 | |
| 3029 | Return true if all bytes in the sequence are ASCII decimal digits |
| 3030 | and the sequence is not empty, false otherwise. ASCII decimal digits are |
| 3031 | those byte values in the sequence ``b'0123456789'``. |
| 3032 | |
| 3033 | For example:: |
| 3034 | |
| 3035 | >>> b'1234'.isdigit() |
| 3036 | True |
| 3037 | >>> b'1.23'.isdigit() |
| 3038 | False |
| 3039 | |
| 3040 | |
| 3041 | .. method:: bytes.islower() |
| 3042 | bytearray.islower() |
| 3043 | |
| 3044 | Return true if there is at least one lowercase ASCII character |
| 3045 | in the sequence and no uppercase ASCII characters, false otherwise. |
| 3046 | |
| 3047 | For example:: |
| 3048 | |
| 3049 | >>> b'hello world'.islower() |
| 3050 | True |
| 3051 | >>> b'Hello world'.islower() |
| 3052 | False |
| 3053 | |
| 3054 | Lowercase ASCII characters are those byte values in the sequence |
| 3055 | ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters |
| 3056 | are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. |
| 3057 | |
| 3058 | |
| 3059 | .. method:: bytes.isspace() |
| 3060 | bytearray.isspace() |
| 3061 | |
| 3062 | Return true if all bytes in the sequence are ASCII whitespace and the |
| 3063 | sequence is not empty, false otherwise. ASCII whitespace characters are |
Serhiy Storchaka | bf7b9ed | 2015-11-23 16:43:05 +0200 | [diff] [blame] | 3064 | those byte values in the sequence ``b' \t\n\r\x0b\f'`` (space, tab, newline, |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 3065 | carriage return, vertical tab, form feed). |
| 3066 | |
| 3067 | |
| 3068 | .. method:: bytes.istitle() |
| 3069 | bytearray.istitle() |
| 3070 | |
| 3071 | Return true if the sequence is ASCII titlecase and the sequence is not |
| 3072 | empty, false otherwise. See :meth:`bytes.title` for more details on the |
| 3073 | definition of "titlecase". |
| 3074 | |
| 3075 | For example:: |
| 3076 | |
| 3077 | >>> b'Hello World'.istitle() |
| 3078 | True |
| 3079 | >>> b'Hello world'.istitle() |
| 3080 | False |
| 3081 | |
| 3082 | |
| 3083 | .. method:: bytes.isupper() |
| 3084 | bytearray.isupper() |
| 3085 | |
Zachary Ware | 0b49637 | 2015-02-27 01:40:22 -0600 | [diff] [blame] | 3086 | Return true if there is at least one uppercase alphabetic ASCII character |
| 3087 | in the sequence and no lowercase ASCII characters, false otherwise. |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 3088 | |
| 3089 | For example:: |
| 3090 | |
| 3091 | >>> b'HELLO WORLD'.isupper() |
| 3092 | True |
| 3093 | >>> b'Hello world'.isupper() |
| 3094 | False |
| 3095 | |
| 3096 | Lowercase ASCII characters are those byte values in the sequence |
| 3097 | ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters |
| 3098 | are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. |
| 3099 | |
| 3100 | |
| 3101 | .. method:: bytes.lower() |
| 3102 | bytearray.lower() |
| 3103 | |
| 3104 | Return a copy of the sequence with all the uppercase ASCII characters |
| 3105 | converted to their corresponding lowercase counterpart. |
| 3106 | |
| 3107 | For example:: |
| 3108 | |
| 3109 | >>> b'Hello World'.lower() |
| 3110 | b'hello world' |
| 3111 | |
| 3112 | Lowercase ASCII characters are those byte values in the sequence |
| 3113 | ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters |
| 3114 | are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. |
| 3115 | |
| 3116 | .. note:: |
| 3117 | |
| 3118 | The bytearray version of this method does *not* operate in place - it |
| 3119 | always produces a new object, even if no changes were made. |
| 3120 | |
| 3121 | |
| 3122 | .. index:: |
| 3123 | single: universal newlines; bytes.splitlines method |
| 3124 | single: universal newlines; bytearray.splitlines method |
| 3125 | |
| 3126 | .. method:: bytes.splitlines(keepends=False) |
| 3127 | bytearray.splitlines(keepends=False) |
| 3128 | |
| 3129 | Return a list of the lines in the binary sequence, breaking at ASCII |
| 3130 | line boundaries. This method uses the :term:`universal newlines` approach |
| 3131 | to splitting lines. Line breaks are not included in the resulting list |
| 3132 | unless *keepends* is given and true. |
| 3133 | |
| 3134 | For example:: |
| 3135 | |
| 3136 | >>> b'ab c\n\nde fg\rkl\r\n'.splitlines() |
Larry Hastings | c6256e5 | 2014-10-05 19:03:48 -0700 | [diff] [blame] | 3137 | [b'ab c', b'', b'de fg', b'kl'] |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 3138 | >>> b'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True) |
| 3139 | [b'ab c\n', b'\n', b'de fg\r', b'kl\r\n'] |
| 3140 | |
| 3141 | Unlike :meth:`~bytes.split` when a delimiter string *sep* is given, this |
| 3142 | method returns an empty list for the empty string, and a terminal line |
| 3143 | break does not result in an extra line:: |
| 3144 | |
| 3145 | >>> b"".split(b'\n'), b"Two lines\n".split(b'\n') |
| 3146 | ([b''], [b'Two lines', b'']) |
| 3147 | >>> b"".splitlines(), b"One line\n".splitlines() |
| 3148 | ([], [b'One line']) |
| 3149 | |
| 3150 | |
| 3151 | .. method:: bytes.swapcase() |
| 3152 | bytearray.swapcase() |
| 3153 | |
| 3154 | Return a copy of the sequence with all the lowercase ASCII characters |
| 3155 | converted to their corresponding uppercase counterpart and vice-versa. |
| 3156 | |
| 3157 | For example:: |
| 3158 | |
| 3159 | >>> b'Hello World'.swapcase() |
| 3160 | b'hELLO wORLD' |
| 3161 | |
| 3162 | Lowercase ASCII characters are those byte values in the sequence |
| 3163 | ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters |
| 3164 | are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. |
| 3165 | |
| 3166 | Unlike :func:`str.swapcase()`, it is always the case that |
| 3167 | ``bin.swapcase().swapcase() == bin`` for the binary versions. Case |
| 3168 | conversions are symmetrical in ASCII, even though that is not generally |
| 3169 | true for arbitrary Unicode code points. |
| 3170 | |
| 3171 | .. note:: |
| 3172 | |
| 3173 | The bytearray version of this method does *not* operate in place - it |
| 3174 | always produces a new object, even if no changes were made. |
| 3175 | |
| 3176 | |
| 3177 | .. method:: bytes.title() |
| 3178 | bytearray.title() |
| 3179 | |
| 3180 | Return a titlecased version of the binary sequence where words start with |
| 3181 | an uppercase ASCII character and the remaining characters are lowercase. |
| 3182 | Uncased byte values are left unmodified. |
| 3183 | |
| 3184 | For example:: |
| 3185 | |
| 3186 | >>> b'Hello world'.title() |
| 3187 | b'Hello World' |
| 3188 | |
| 3189 | Lowercase ASCII characters are those byte values in the sequence |
| 3190 | ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters |
| 3191 | are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. |
| 3192 | All other byte values are uncased. |
| 3193 | |
| 3194 | The algorithm uses a simple language-independent definition of a word as |
| 3195 | groups of consecutive letters. The definition works in many contexts but |
| 3196 | it means that apostrophes in contractions and possessives form word |
| 3197 | boundaries, which may not be the desired result:: |
| 3198 | |
| 3199 | >>> b"they're bill's friends from the UK".title() |
| 3200 | b"They'Re Bill'S Friends From The Uk" |
| 3201 | |
| 3202 | A workaround for apostrophes can be constructed using regular expressions:: |
| 3203 | |
| 3204 | >>> import re |
| 3205 | >>> def titlecase(s): |
| 3206 | ... return re.sub(rb"[A-Za-z]+('[A-Za-z]+)?", |
| 3207 | ... lambda mo: mo.group(0)[0:1].upper() + |
| 3208 | ... mo.group(0)[1:].lower(), |
| 3209 | ... s) |
| 3210 | ... |
| 3211 | >>> titlecase(b"they're bill's friends.") |
| 3212 | b"They're Bill's Friends." |
| 3213 | |
| 3214 | .. note:: |
| 3215 | |
| 3216 | The bytearray version of this method does *not* operate in place - it |
| 3217 | always produces a new object, even if no changes were made. |
| 3218 | |
| 3219 | |
| 3220 | .. method:: bytes.upper() |
| 3221 | bytearray.upper() |
| 3222 | |
| 3223 | Return a copy of the sequence with all the lowercase ASCII characters |
| 3224 | converted to their corresponding uppercase counterpart. |
| 3225 | |
| 3226 | For example:: |
| 3227 | |
| 3228 | >>> b'Hello World'.upper() |
| 3229 | b'HELLO WORLD' |
| 3230 | |
| 3231 | Lowercase ASCII characters are those byte values in the sequence |
| 3232 | ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters |
| 3233 | are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. |
| 3234 | |
| 3235 | .. note:: |
| 3236 | |
| 3237 | The bytearray version of this method does *not* operate in place - it |
| 3238 | always produces a new object, even if no changes were made. |
| 3239 | |
| 3240 | |
| 3241 | .. method:: bytes.zfill(width) |
| 3242 | bytearray.zfill(width) |
| 3243 | |
| 3244 | Return a copy of the sequence left filled with ASCII ``b'0'`` digits to |
| 3245 | make a sequence of length *width*. A leading sign prefix (``b'+'``/ |
Andre Delfino | 55f41e4 | 2018-12-05 16:45:30 -0300 | [diff] [blame] | 3246 | ``b'-'``) is handled by inserting the padding *after* the sign character |
Nick Coghlan | e4936b8 | 2014-08-09 16:14:04 +1000 | [diff] [blame] | 3247 | rather than before. For :class:`bytes` objects, the original sequence is |
| 3248 | returned if *width* is less than or equal to ``len(seq)``. |
| 3249 | |
| 3250 | For example:: |
| 3251 | |
| 3252 | >>> b"42".zfill(5) |
| 3253 | b'00042' |
| 3254 | >>> b"-42".zfill(5) |
| 3255 | b'-0042' |
| 3256 | |
| 3257 | .. note:: |
| 3258 | |
| 3259 | The bytearray version of this method does *not* operate in place - it |
| 3260 | always produces a new object, even if no changes were made. |
Georg Brandl | abc3877 | 2009-04-12 15:51:51 +0000 | [diff] [blame] | 3261 | |
| 3262 | |
Ethan Furman | b95b561 | 2015-01-23 20:05:18 -0800 | [diff] [blame] | 3263 | .. _bytes-formatting: |
| 3264 | |
| 3265 | ``printf``-style Bytes Formatting |
| 3266 | ---------------------------------- |
| 3267 | |
| 3268 | .. index:: |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 3269 | single: formatting; bytes (%) |
| 3270 | single: formatting; bytearray (%) |
| 3271 | single: interpolation; bytes (%) |
| 3272 | single: interpolation; bytearray (%) |
Ethan Furman | b95b561 | 2015-01-23 20:05:18 -0800 | [diff] [blame] | 3273 | single: bytes; formatting |
| 3274 | single: bytearray; formatting |
| 3275 | single: bytes; interpolation |
| 3276 | single: bytearray; interpolation |
| 3277 | single: printf-style formatting |
| 3278 | single: sprintf-style formatting |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 3279 | single: % (percent); printf-style formatting |
Ethan Furman | b95b561 | 2015-01-23 20:05:18 -0800 | [diff] [blame] | 3280 | |
| 3281 | .. note:: |
| 3282 | |
| 3283 | The formatting operations described here exhibit a variety of quirks that |
| 3284 | lead to a number of common errors (such as failing to display tuples and |
| 3285 | dictionaries correctly). If the value being printed may be a tuple or |
| 3286 | dictionary, wrap it in a tuple. |
| 3287 | |
| 3288 | Bytes objects (``bytes``/``bytearray``) have one unique built-in operation: |
| 3289 | the ``%`` operator (modulo). |
| 3290 | This is also known as the bytes *formatting* or *interpolation* operator. |
| 3291 | Given ``format % values`` (where *format* is a bytes object), ``%`` conversion |
| 3292 | specifications in *format* are replaced with zero or more elements of *values*. |
| 3293 | The effect is similar to using the :c:func:`sprintf` in the C language. |
| 3294 | |
| 3295 | If *format* requires a single argument, *values* may be a single non-tuple |
| 3296 | object. [5]_ Otherwise, *values* must be a tuple with exactly the number of |
| 3297 | items specified by the format bytes object, or a single mapping object (for |
| 3298 | example, a dictionary). |
| 3299 | |
Andre Delfino | de9e9b4 | 2018-12-09 04:00:20 -0300 | [diff] [blame] | 3300 | .. index:: |
| 3301 | single: () (parentheses); in printf-style formatting |
| 3302 | single: * (asterisk); in printf-style formatting |
| 3303 | single: . (dot); in printf-style formatting |
| 3304 | |
Ethan Furman | b95b561 | 2015-01-23 20:05:18 -0800 | [diff] [blame] | 3305 | A conversion specifier contains two or more characters and has the following |
| 3306 | components, which must occur in this order: |
| 3307 | |
| 3308 | #. The ``'%'`` character, which marks the start of the specifier. |
| 3309 | |
| 3310 | #. Mapping key (optional), consisting of a parenthesised sequence of characters |
| 3311 | (for example, ``(somename)``). |
| 3312 | |
| 3313 | #. Conversion flags (optional), which affect the result of some conversion |
| 3314 | types. |
| 3315 | |
| 3316 | #. Minimum field width (optional). If specified as an ``'*'`` (asterisk), the |
| 3317 | actual width is read from the next element of the tuple in *values*, and the |
| 3318 | object to convert comes after the minimum field width and optional precision. |
| 3319 | |
| 3320 | #. Precision (optional), given as a ``'.'`` (dot) followed by the precision. If |
| 3321 | specified as ``'*'`` (an asterisk), the actual precision is read from the next |
| 3322 | element of the tuple in *values*, and the value to convert comes after the |
| 3323 | precision. |
| 3324 | |
| 3325 | #. Length modifier (optional). |
| 3326 | |
| 3327 | #. Conversion type. |
| 3328 | |
| 3329 | When the right argument is a dictionary (or other mapping type), then the |
| 3330 | formats in the bytes object *must* include a parenthesised mapping key into that |
| 3331 | dictionary inserted immediately after the ``'%'`` character. The mapping key |
| 3332 | selects the value to be formatted from the mapping. For example: |
| 3333 | |
| 3334 | >>> print(b'%(language)s has %(number)03d quote types.' % |
| 3335 | ... {b'language': b"Python", b"number": 2}) |
| 3336 | b'Python has 002 quote types.' |
| 3337 | |
| 3338 | In this case no ``*`` specifiers may occur in a format (since they require a |
| 3339 | sequential parameter list). |
| 3340 | |
| 3341 | The conversion flag characters are: |
| 3342 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 3343 | .. index:: |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 3344 | single: # (hash); in printf-style formatting |
| 3345 | single: - (minus); in printf-style formatting |
| 3346 | single: + (plus); in printf-style formatting |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 3347 | single: space; in printf-style formatting |
| 3348 | |
Ethan Furman | b95b561 | 2015-01-23 20:05:18 -0800 | [diff] [blame] | 3349 | +---------+---------------------------------------------------------------------+ |
| 3350 | | Flag | Meaning | |
| 3351 | +=========+=====================================================================+ |
| 3352 | | ``'#'`` | The value conversion will use the "alternate form" (where defined | |
| 3353 | | | below). | |
| 3354 | +---------+---------------------------------------------------------------------+ |
| 3355 | | ``'0'`` | The conversion will be zero padded for numeric values. | |
| 3356 | +---------+---------------------------------------------------------------------+ |
| 3357 | | ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` | |
| 3358 | | | conversion if both are given). | |
| 3359 | +---------+---------------------------------------------------------------------+ |
| 3360 | | ``' '`` | (a space) A blank should be left before a positive number (or empty | |
| 3361 | | | string) produced by a signed conversion. | |
| 3362 | +---------+---------------------------------------------------------------------+ |
| 3363 | | ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion | |
| 3364 | | | (overrides a "space" flag). | |
| 3365 | +---------+---------------------------------------------------------------------+ |
| 3366 | |
| 3367 | A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it |
| 3368 | is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``. |
| 3369 | |
| 3370 | The conversion types are: |
| 3371 | |
| 3372 | +------------+-----------------------------------------------------+-------+ |
| 3373 | | Conversion | Meaning | Notes | |
| 3374 | +============+=====================================================+=======+ |
| 3375 | | ``'d'`` | Signed integer decimal. | | |
| 3376 | +------------+-----------------------------------------------------+-------+ |
| 3377 | | ``'i'`` | Signed integer decimal. | | |
| 3378 | +------------+-----------------------------------------------------+-------+ |
| 3379 | | ``'o'`` | Signed octal value. | \(1) | |
| 3380 | +------------+-----------------------------------------------------+-------+ |
Ethan Furman | 62e977f | 2015-03-11 08:17:00 -0700 | [diff] [blame] | 3381 | | ``'u'`` | Obsolete type -- it is identical to ``'d'``. | \(8) | |
Ethan Furman | b95b561 | 2015-01-23 20:05:18 -0800 | [diff] [blame] | 3382 | +------------+-----------------------------------------------------+-------+ |
| 3383 | | ``'x'`` | Signed hexadecimal (lowercase). | \(2) | |
| 3384 | +------------+-----------------------------------------------------+-------+ |
| 3385 | | ``'X'`` | Signed hexadecimal (uppercase). | \(2) | |
| 3386 | +------------+-----------------------------------------------------+-------+ |
| 3387 | | ``'e'`` | Floating point exponential format (lowercase). | \(3) | |
| 3388 | +------------+-----------------------------------------------------+-------+ |
| 3389 | | ``'E'`` | Floating point exponential format (uppercase). | \(3) | |
| 3390 | +------------+-----------------------------------------------------+-------+ |
| 3391 | | ``'f'`` | Floating point decimal format. | \(3) | |
| 3392 | +------------+-----------------------------------------------------+-------+ |
| 3393 | | ``'F'`` | Floating point decimal format. | \(3) | |
| 3394 | +------------+-----------------------------------------------------+-------+ |
| 3395 | | ``'g'`` | Floating point format. Uses lowercase exponential | \(4) | |
| 3396 | | | format if exponent is less than -4 or not less than | | |
| 3397 | | | precision, decimal format otherwise. | | |
| 3398 | +------------+-----------------------------------------------------+-------+ |
| 3399 | | ``'G'`` | Floating point format. Uses uppercase exponential | \(4) | |
| 3400 | | | format if exponent is less than -4 or not less than | | |
| 3401 | | | precision, decimal format otherwise. | | |
| 3402 | +------------+-----------------------------------------------------+-------+ |
| 3403 | | ``'c'`` | Single byte (accepts integer or single | | |
| 3404 | | | byte objects). | | |
| 3405 | +------------+-----------------------------------------------------+-------+ |
| 3406 | | ``'b'`` | Bytes (any object that follows the | \(5) | |
| 3407 | | | :ref:`buffer protocol <bufferobjects>` or has | | |
| 3408 | | | :meth:`__bytes__`). | | |
| 3409 | +------------+-----------------------------------------------------+-------+ |
| 3410 | | ``'s'`` | ``'s'`` is an alias for ``'b'`` and should only | \(6) | |
| 3411 | | | be used for Python2/3 code bases. | | |
| 3412 | +------------+-----------------------------------------------------+-------+ |
| 3413 | | ``'a'`` | Bytes (converts any Python object using | \(5) | |
| 3414 | | | ``repr(obj).encode('ascii','backslashreplace)``). | | |
| 3415 | +------------+-----------------------------------------------------+-------+ |
Ethan Furman | 62e977f | 2015-03-11 08:17:00 -0700 | [diff] [blame] | 3416 | | ``'r'`` | ``'r'`` is an alias for ``'a'`` and should only | \(7) | |
| 3417 | | | be used for Python2/3 code bases. | | |
| 3418 | +------------+-----------------------------------------------------+-------+ |
Ethan Furman | b95b561 | 2015-01-23 20:05:18 -0800 | [diff] [blame] | 3419 | | ``'%'`` | No argument is converted, results in a ``'%'`` | | |
| 3420 | | | character in the result. | | |
| 3421 | +------------+-----------------------------------------------------+-------+ |
| 3422 | |
| 3423 | Notes: |
| 3424 | |
| 3425 | (1) |
Martin Panter | 41176ae | 2016-12-11 01:07:29 +0000 | [diff] [blame] | 3426 | The alternate form causes a leading octal specifier (``'0o'``) to be |
| 3427 | inserted before the first digit. |
Ethan Furman | b95b561 | 2015-01-23 20:05:18 -0800 | [diff] [blame] | 3428 | |
| 3429 | (2) |
| 3430 | The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether |
Martin Panter | 41176ae | 2016-12-11 01:07:29 +0000 | [diff] [blame] | 3431 | the ``'x'`` or ``'X'`` format was used) to be inserted before the first digit. |
Ethan Furman | b95b561 | 2015-01-23 20:05:18 -0800 | [diff] [blame] | 3432 | |
| 3433 | (3) |
| 3434 | The alternate form causes the result to always contain a decimal point, even if |
| 3435 | no digits follow it. |
| 3436 | |
| 3437 | The precision determines the number of digits after the decimal point and |
| 3438 | defaults to 6. |
| 3439 | |
| 3440 | (4) |
| 3441 | The alternate form causes the result to always contain a decimal point, and |
| 3442 | trailing zeroes are not removed as they would otherwise be. |
| 3443 | |
| 3444 | The precision determines the number of significant digits before and after the |
| 3445 | decimal point and defaults to 6. |
| 3446 | |
| 3447 | (5) |
| 3448 | If precision is ``N``, the output is truncated to ``N`` characters. |
| 3449 | |
| 3450 | (6) |
| 3451 | ``b'%s'`` is deprecated, but will not be removed during the 3.x series. |
| 3452 | |
| 3453 | (7) |
Ethan Furman | 62e977f | 2015-03-11 08:17:00 -0700 | [diff] [blame] | 3454 | ``b'%r'`` is deprecated, but will not be removed during the 3.x series. |
| 3455 | |
| 3456 | (8) |
Ethan Furman | b95b561 | 2015-01-23 20:05:18 -0800 | [diff] [blame] | 3457 | See :pep:`237`. |
| 3458 | |
| 3459 | .. note:: |
| 3460 | |
| 3461 | The bytearray version of this method does *not* operate in place - it |
| 3462 | always produces a new object, even if no changes were made. |
| 3463 | |
Andrés Delfino | a9d0b34 | 2018-06-15 16:42:20 -0300 | [diff] [blame] | 3464 | .. seealso:: |
| 3465 | |
| 3466 | :pep:`461` - Adding % formatting to bytes and bytearray |
| 3467 | |
Ethan Furman | b95b561 | 2015-01-23 20:05:18 -0800 | [diff] [blame] | 3468 | .. versionadded:: 3.5 |
| 3469 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 3470 | .. _typememoryview: |
| 3471 | |
| 3472 | Memory Views |
| 3473 | ------------ |
| 3474 | |
| 3475 | :class:`memoryview` objects allow Python code to access the internal data |
| 3476 | of an object that supports the :ref:`buffer protocol <bufferobjects>` without |
| 3477 | copying. |
| 3478 | |
| 3479 | .. class:: memoryview(obj) |
| 3480 | |
| 3481 | Create a :class:`memoryview` that references *obj*. *obj* must support the |
| 3482 | buffer protocol. Built-in objects that support the buffer protocol include |
| 3483 | :class:`bytes` and :class:`bytearray`. |
| 3484 | |
| 3485 | A :class:`memoryview` has the notion of an *element*, which is the |
| 3486 | atomic memory unit handled by the originating object *obj*. For many |
| 3487 | simple types such as :class:`bytes` and :class:`bytearray`, an element |
| 3488 | is a single byte, but other types such as :class:`array.array` may have |
| 3489 | bigger elements. |
| 3490 | |
| 3491 | ``len(view)`` is equal to the length of :class:`~memoryview.tolist`. |
| 3492 | If ``view.ndim = 0``, the length is 1. If ``view.ndim = 1``, the length |
| 3493 | is equal to the number of elements in the view. For higher dimensions, |
| 3494 | the length is equal to the length of the nested list representation of |
| 3495 | the view. The :class:`~memoryview.itemsize` attribute will give you the |
| 3496 | number of bytes in a single element. |
| 3497 | |
Antoine Pitrou | 31084ba | 2015-03-19 23:29:36 +0100 | [diff] [blame] | 3498 | A :class:`memoryview` supports slicing and indexing to expose its data. |
| 3499 | One-dimensional slicing will result in a subview:: |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 3500 | |
| 3501 | >>> v = memoryview(b'abcefg') |
| 3502 | >>> v[1] |
| 3503 | 98 |
| 3504 | >>> v[-1] |
| 3505 | 103 |
| 3506 | >>> v[1:4] |
| 3507 | <memory at 0x7f3ddc9f4350> |
| 3508 | >>> bytes(v[1:4]) |
| 3509 | b'bce' |
| 3510 | |
Antoine Pitrou | 31084ba | 2015-03-19 23:29:36 +0100 | [diff] [blame] | 3511 | If :class:`~memoryview.format` is one of the native format specifiers |
| 3512 | from the :mod:`struct` module, indexing with an integer or a tuple of |
| 3513 | integers is also supported and returns a single *element* with |
| 3514 | the correct type. One-dimensional memoryviews can be indexed |
| 3515 | with an integer or a one-integer tuple. Multi-dimensional memoryviews |
| 3516 | can be indexed with tuples of exactly *ndim* integers where *ndim* is |
| 3517 | the number of dimensions. Zero-dimensional memoryviews can be indexed |
| 3518 | with the empty tuple. |
| 3519 | |
| 3520 | Here is an example with a non-byte format:: |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 3521 | |
| 3522 | >>> import array |
| 3523 | >>> a = array.array('l', [-11111111, 22222222, -33333333, 44444444]) |
Antoine Pitrou | 31084ba | 2015-03-19 23:29:36 +0100 | [diff] [blame] | 3524 | >>> m = memoryview(a) |
| 3525 | >>> m[0] |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 3526 | -11111111 |
Antoine Pitrou | 31084ba | 2015-03-19 23:29:36 +0100 | [diff] [blame] | 3527 | >>> m[-1] |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 3528 | 44444444 |
Antoine Pitrou | 31084ba | 2015-03-19 23:29:36 +0100 | [diff] [blame] | 3529 | >>> m[::2].tolist() |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 3530 | [-11111111, -33333333] |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 3531 | |
Antoine Pitrou | 31084ba | 2015-03-19 23:29:36 +0100 | [diff] [blame] | 3532 | If the underlying object is writable, the memoryview supports |
| 3533 | one-dimensional slice assignment. Resizing is not allowed:: |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 3534 | |
| 3535 | >>> data = bytearray(b'abcefg') |
| 3536 | >>> v = memoryview(data) |
| 3537 | >>> v.readonly |
| 3538 | False |
| 3539 | >>> v[0] = ord(b'z') |
| 3540 | >>> data |
| 3541 | bytearray(b'zbcefg') |
| 3542 | >>> v[1:4] = b'123' |
| 3543 | >>> data |
| 3544 | bytearray(b'z123fg') |
| 3545 | >>> v[2:3] = b'spam' |
| 3546 | Traceback (most recent call last): |
| 3547 | File "<stdin>", line 1, in <module> |
| 3548 | ValueError: memoryview assignment: lvalue and rvalue have different structures |
| 3549 | >>> v[2:6] = b'spam' |
| 3550 | >>> data |
| 3551 | bytearray(b'z1spam') |
| 3552 | |
Stefan Krah | a3b84fb | 2012-09-02 14:50:56 +0200 | [diff] [blame] | 3553 | One-dimensional memoryviews of hashable (read-only) types with formats |
| 3554 | 'B', 'b' or 'c' are also hashable. The hash is defined as |
| 3555 | ``hash(m) == hash(m.tobytes())``:: |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 3556 | |
| 3557 | >>> v = memoryview(b'abcefg') |
| 3558 | >>> hash(v) == hash(b'abcefg') |
| 3559 | True |
| 3560 | >>> hash(v[2:4]) == hash(b'ce') |
| 3561 | True |
| 3562 | >>> hash(v[::-2]) == hash(b'abcefg'[::-2]) |
| 3563 | True |
| 3564 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 3565 | .. versionchanged:: 3.3 |
Antoine Pitrou | 31084ba | 2015-03-19 23:29:36 +0100 | [diff] [blame] | 3566 | One-dimensional memoryviews can now be sliced. |
Stefan Krah | a3b84fb | 2012-09-02 14:50:56 +0200 | [diff] [blame] | 3567 | One-dimensional memoryviews with formats 'B', 'b' or 'c' are now hashable. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 3568 | |
Nick Coghlan | 45163cc | 2013-10-02 22:31:47 +1000 | [diff] [blame] | 3569 | .. versionchanged:: 3.4 |
| 3570 | memoryview is now registered automatically with |
| 3571 | :class:`collections.abc.Sequence` |
| 3572 | |
Antoine Pitrou | 31084ba | 2015-03-19 23:29:36 +0100 | [diff] [blame] | 3573 | .. versionchanged:: 3.5 |
| 3574 | memoryviews can now be indexed with tuple of integers. |
| 3575 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 3576 | :class:`memoryview` has several methods: |
| 3577 | |
Nick Coghlan | 06e1ab0 | 2012-08-25 17:59:50 +1000 | [diff] [blame] | 3578 | .. method:: __eq__(exporter) |
| 3579 | |
| 3580 | A memoryview and a :pep:`3118` exporter are equal if their shapes are |
| 3581 | equivalent and if all corresponding values are equal when the operands' |
| 3582 | respective format codes are interpreted using :mod:`struct` syntax. |
| 3583 | |
| 3584 | For the subset of :mod:`struct` format strings currently supported by |
| 3585 | :meth:`tolist`, ``v`` and ``w`` are equal if ``v.tolist() == w.tolist()``:: |
| 3586 | |
| 3587 | >>> import array |
| 3588 | >>> a = array.array('I', [1, 2, 3, 4, 5]) |
| 3589 | >>> b = array.array('d', [1.0, 2.0, 3.0, 4.0, 5.0]) |
| 3590 | >>> c = array.array('b', [5, 3, 1]) |
| 3591 | >>> x = memoryview(a) |
| 3592 | >>> y = memoryview(b) |
| 3593 | >>> x == a == y == b |
| 3594 | True |
| 3595 | >>> x.tolist() == a.tolist() == y.tolist() == b.tolist() |
| 3596 | True |
| 3597 | >>> z = y[::-2] |
| 3598 | >>> z == c |
| 3599 | True |
| 3600 | >>> z.tolist() == c.tolist() |
| 3601 | True |
| 3602 | |
| 3603 | If either format string is not supported by the :mod:`struct` module, |
| 3604 | then the objects will always compare as unequal (even if the format |
| 3605 | strings and buffer contents are identical):: |
| 3606 | |
| 3607 | >>> from ctypes import BigEndianStructure, c_long |
| 3608 | >>> class BEPoint(BigEndianStructure): |
| 3609 | ... _fields_ = [("x", c_long), ("y", c_long)] |
| 3610 | ... |
| 3611 | >>> point = BEPoint(100, 200) |
| 3612 | >>> a = memoryview(point) |
| 3613 | >>> b = memoryview(point) |
| 3614 | >>> a == point |
| 3615 | False |
| 3616 | >>> a == b |
| 3617 | False |
| 3618 | |
| 3619 | Note that, as with floating point numbers, ``v is w`` does *not* imply |
| 3620 | ``v == w`` for memoryview objects. |
| 3621 | |
| 3622 | .. versionchanged:: 3.3 |
Stefan Krah | ab0c3c7 | 2012-08-30 12:09:09 +0200 | [diff] [blame] | 3623 | Previous versions compared the raw memory disregarding the item format |
| 3624 | and the logical array structure. |
Nick Coghlan | 06e1ab0 | 2012-08-25 17:59:50 +1000 | [diff] [blame] | 3625 | |
Stefan Krah | d08ea70 | 2019-02-02 18:57:41 +0100 | [diff] [blame] | 3626 | .. method:: tobytes(order=None) |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 3627 | |
| 3628 | Return the data in the buffer as a bytestring. This is equivalent to |
| 3629 | calling the :class:`bytes` constructor on the memoryview. :: |
| 3630 | |
| 3631 | >>> m = memoryview(b"abc") |
| 3632 | >>> m.tobytes() |
| 3633 | b'abc' |
| 3634 | >>> bytes(m) |
| 3635 | b'abc' |
| 3636 | |
| 3637 | For non-contiguous arrays the result is equal to the flattened list |
Nick Coghlan | 06e1ab0 | 2012-08-25 17:59:50 +1000 | [diff] [blame] | 3638 | representation with all elements converted to bytes. :meth:`tobytes` |
| 3639 | supports all format strings, including those that are not in |
| 3640 | :mod:`struct` module syntax. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 3641 | |
Stefan Krah | d08ea70 | 2019-02-02 18:57:41 +0100 | [diff] [blame] | 3642 | .. versionadded:: 3.8 |
| 3643 | *Order* can be {'C', 'F', 'A'}. When *order* is 'C' or 'F', the data |
| 3644 | of the original array is converted to C or Fortran order. For contiguous |
| 3645 | views, 'A' returns an exact copy of the physical memory. In particular, |
| 3646 | in-memory Fortran order is preserved. For non-contiguous views, the |
| 3647 | data is converted to C first. *order=None* is the same as *order='C'*. |
| 3648 | |
Gregory P. Smith | 8cb6569 | 2015-04-25 23:22:26 +0000 | [diff] [blame] | 3649 | .. method:: hex() |
| 3650 | |
| 3651 | Return a string object containing two hexadecimal digits for each |
| 3652 | byte in the buffer. :: |
| 3653 | |
| 3654 | >>> m = memoryview(b"abc") |
| 3655 | >>> m.hex() |
| 3656 | '616263' |
| 3657 | |
| 3658 | .. versionadded:: 3.5 |
| 3659 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 3660 | .. method:: tolist() |
| 3661 | |
| 3662 | Return the data in the buffer as a list of elements. :: |
| 3663 | |
| 3664 | >>> memoryview(b'abc').tolist() |
| 3665 | [97, 98, 99] |
| 3666 | >>> import array |
| 3667 | >>> a = array.array('d', [1.1, 2.2, 3.3]) |
| 3668 | >>> m = memoryview(a) |
| 3669 | >>> m.tolist() |
| 3670 | [1.1, 2.2, 3.3] |
| 3671 | |
Stefan Krah | ab0c3c7 | 2012-08-30 12:09:09 +0200 | [diff] [blame] | 3672 | .. versionchanged:: 3.3 |
| 3673 | :meth:`tolist` now supports all single character native formats in |
| 3674 | :mod:`struct` module syntax as well as multi-dimensional |
| 3675 | representations. |
Nick Coghlan | 06e1ab0 | 2012-08-25 17:59:50 +1000 | [diff] [blame] | 3676 | |
Antoine Pitrou | 480ab05 | 2018-04-14 19:49:21 +0200 | [diff] [blame] | 3677 | .. method:: toreadonly() |
| 3678 | |
| 3679 | Return a readonly version of the memoryview object. The original |
| 3680 | memoryview object is unchanged. :: |
| 3681 | |
| 3682 | >>> m = memoryview(bytearray(b'abc')) |
| 3683 | >>> mm = m.toreadonly() |
| 3684 | >>> mm.tolist() |
| 3685 | [89, 98, 99] |
| 3686 | >>> mm[0] = 42 |
| 3687 | Traceback (most recent call last): |
| 3688 | File "<stdin>", line 1, in <module> |
| 3689 | TypeError: cannot modify read-only memory |
| 3690 | >>> m[0] = 43 |
| 3691 | >>> mm.tolist() |
| 3692 | [43, 98, 99] |
| 3693 | |
| 3694 | .. versionadded:: 3.8 |
| 3695 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 3696 | .. method:: release() |
| 3697 | |
| 3698 | Release the underlying buffer exposed by the memoryview object. Many |
| 3699 | objects take special actions when a view is held on them (for example, |
| 3700 | a :class:`bytearray` would temporarily forbid resizing); therefore, |
| 3701 | calling release() is handy to remove these restrictions (and free any |
| 3702 | dangling resources) as soon as possible. |
| 3703 | |
| 3704 | After this method has been called, any further operation on the view |
| 3705 | raises a :class:`ValueError` (except :meth:`release()` itself which can |
| 3706 | be called multiple times):: |
| 3707 | |
| 3708 | >>> m = memoryview(b'abc') |
| 3709 | >>> m.release() |
| 3710 | >>> m[0] |
| 3711 | Traceback (most recent call last): |
| 3712 | File "<stdin>", line 1, in <module> |
| 3713 | ValueError: operation forbidden on released memoryview object |
| 3714 | |
| 3715 | The context management protocol can be used for a similar effect, |
| 3716 | using the ``with`` statement:: |
| 3717 | |
| 3718 | >>> with memoryview(b'abc') as m: |
| 3719 | ... m[0] |
| 3720 | ... |
| 3721 | 97 |
| 3722 | >>> m[0] |
| 3723 | Traceback (most recent call last): |
| 3724 | File "<stdin>", line 1, in <module> |
| 3725 | ValueError: operation forbidden on released memoryview object |
| 3726 | |
| 3727 | .. versionadded:: 3.2 |
| 3728 | |
| 3729 | .. method:: cast(format[, shape]) |
| 3730 | |
| 3731 | Cast a memoryview to a new format or shape. *shape* defaults to |
| 3732 | ``[byte_length//new_itemsize]``, which means that the result view |
| 3733 | will be one-dimensional. The return value is a new memoryview, but |
Stefan Krah | 70e543b | 2015-08-08 14:33:28 +0200 | [diff] [blame] | 3734 | the buffer itself is not copied. Supported casts are 1D -> C-:term:`contiguous` |
Nick Coghlan | 06e1ab0 | 2012-08-25 17:59:50 +1000 | [diff] [blame] | 3735 | and C-contiguous -> 1D. |
| 3736 | |
Stefan Krah | 0c51595 | 2015-08-08 13:38:10 +0200 | [diff] [blame] | 3737 | The destination format is restricted to a single element native format in |
Nick Coghlan | 06e1ab0 | 2012-08-25 17:59:50 +1000 | [diff] [blame] | 3738 | :mod:`struct` syntax. One of the formats must be a byte format |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 3739 | ('B', 'b' or 'c'). The byte length of the result must be the same |
| 3740 | as the original length. |
| 3741 | |
| 3742 | Cast 1D/long to 1D/unsigned bytes:: |
| 3743 | |
| 3744 | >>> import array |
| 3745 | >>> a = array.array('l', [1,2,3]) |
| 3746 | >>> x = memoryview(a) |
| 3747 | >>> x.format |
| 3748 | 'l' |
| 3749 | >>> x.itemsize |
| 3750 | 8 |
| 3751 | >>> len(x) |
| 3752 | 3 |
| 3753 | >>> x.nbytes |
| 3754 | 24 |
| 3755 | >>> y = x.cast('B') |
| 3756 | >>> y.format |
| 3757 | 'B' |
| 3758 | >>> y.itemsize |
| 3759 | 1 |
| 3760 | >>> len(y) |
| 3761 | 24 |
| 3762 | >>> y.nbytes |
| 3763 | 24 |
| 3764 | |
| 3765 | Cast 1D/unsigned bytes to 1D/char:: |
| 3766 | |
| 3767 | >>> b = bytearray(b'zyz') |
| 3768 | >>> x = memoryview(b) |
| 3769 | >>> x[0] = b'a' |
| 3770 | Traceback (most recent call last): |
| 3771 | File "<stdin>", line 1, in <module> |
| 3772 | ValueError: memoryview: invalid value for format "B" |
| 3773 | >>> y = x.cast('c') |
| 3774 | >>> y[0] = b'a' |
| 3775 | >>> b |
| 3776 | bytearray(b'ayz') |
| 3777 | |
| 3778 | Cast 1D/bytes to 3D/ints to 1D/signed char:: |
| 3779 | |
| 3780 | >>> import struct |
| 3781 | >>> buf = struct.pack("i"*12, *list(range(12))) |
| 3782 | >>> x = memoryview(buf) |
| 3783 | >>> y = x.cast('i', shape=[2,2,3]) |
| 3784 | >>> y.tolist() |
| 3785 | [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]] |
| 3786 | >>> y.format |
| 3787 | 'i' |
| 3788 | >>> y.itemsize |
| 3789 | 4 |
| 3790 | >>> len(y) |
| 3791 | 2 |
| 3792 | >>> y.nbytes |
| 3793 | 48 |
| 3794 | >>> z = y.cast('b') |
| 3795 | >>> z.format |
| 3796 | 'b' |
| 3797 | >>> z.itemsize |
| 3798 | 1 |
| 3799 | >>> len(z) |
| 3800 | 48 |
| 3801 | >>> z.nbytes |
| 3802 | 48 |
| 3803 | |
Terry Jan Reedy | 0f84764 | 2013-03-11 18:34:00 -0400 | [diff] [blame] | 3804 | Cast 1D/unsigned char to 2D/unsigned long:: |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 3805 | |
| 3806 | >>> buf = struct.pack("L"*6, *list(range(6))) |
| 3807 | >>> x = memoryview(buf) |
| 3808 | >>> y = x.cast('L', shape=[2,3]) |
| 3809 | >>> len(y) |
| 3810 | 2 |
| 3811 | >>> y.nbytes |
| 3812 | 48 |
| 3813 | >>> y.tolist() |
| 3814 | [[0, 1, 2], [3, 4, 5]] |
| 3815 | |
| 3816 | .. versionadded:: 3.3 |
| 3817 | |
Stefan Krah | 0c51595 | 2015-08-08 13:38:10 +0200 | [diff] [blame] | 3818 | .. versionchanged:: 3.5 |
| 3819 | The source format is no longer restricted when casting to a byte view. |
| 3820 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 3821 | There are also several readonly attributes available: |
| 3822 | |
| 3823 | .. attribute:: obj |
| 3824 | |
| 3825 | The underlying object of the memoryview:: |
| 3826 | |
| 3827 | >>> b = bytearray(b'xyz') |
| 3828 | >>> m = memoryview(b) |
| 3829 | >>> m.obj is b |
| 3830 | True |
| 3831 | |
| 3832 | .. versionadded:: 3.3 |
| 3833 | |
| 3834 | .. attribute:: nbytes |
| 3835 | |
| 3836 | ``nbytes == product(shape) * itemsize == len(m.tobytes())``. This is |
| 3837 | the amount of space in bytes that the array would use in a contiguous |
Andrés Delfino | ca03f3b | 2018-11-07 14:22:47 -0300 | [diff] [blame] | 3838 | representation. It is not necessarily equal to ``len(m)``:: |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 3839 | |
| 3840 | >>> import array |
| 3841 | >>> a = array.array('i', [1,2,3,4,5]) |
| 3842 | >>> m = memoryview(a) |
| 3843 | >>> len(m) |
| 3844 | 5 |
| 3845 | >>> m.nbytes |
| 3846 | 20 |
| 3847 | >>> y = m[::2] |
| 3848 | >>> len(y) |
| 3849 | 3 |
| 3850 | >>> y.nbytes |
| 3851 | 12 |
| 3852 | >>> len(y.tobytes()) |
| 3853 | 12 |
| 3854 | |
| 3855 | Multi-dimensional arrays:: |
| 3856 | |
| 3857 | >>> import struct |
| 3858 | >>> buf = struct.pack("d"*12, *[1.5*x for x in range(12)]) |
| 3859 | >>> x = memoryview(buf) |
| 3860 | >>> y = x.cast('d', shape=[3,4]) |
| 3861 | >>> y.tolist() |
| 3862 | [[0.0, 1.5, 3.0, 4.5], [6.0, 7.5, 9.0, 10.5], [12.0, 13.5, 15.0, 16.5]] |
| 3863 | >>> len(y) |
| 3864 | 3 |
| 3865 | >>> y.nbytes |
| 3866 | 96 |
| 3867 | |
| 3868 | .. versionadded:: 3.3 |
| 3869 | |
| 3870 | .. attribute:: readonly |
| 3871 | |
| 3872 | A bool indicating whether the memory is read only. |
| 3873 | |
| 3874 | .. attribute:: format |
| 3875 | |
| 3876 | A string containing the format (in :mod:`struct` module style) for each |
| 3877 | element in the view. A memoryview can be created from exporters with |
| 3878 | arbitrary format strings, but some methods (e.g. :meth:`tolist`) are |
Nick Coghlan | 06e1ab0 | 2012-08-25 17:59:50 +1000 | [diff] [blame] | 3879 | restricted to native single element formats. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 3880 | |
Stefan Krah | ab0c3c7 | 2012-08-30 12:09:09 +0200 | [diff] [blame] | 3881 | .. versionchanged:: 3.3 |
| 3882 | format ``'B'`` is now handled according to the struct module syntax. |
| 3883 | This means that ``memoryview(b'abc')[0] == b'abc'[0] == 97``. |
| 3884 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 3885 | .. attribute:: itemsize |
| 3886 | |
| 3887 | The size in bytes of each element of the memoryview:: |
| 3888 | |
| 3889 | >>> import array, struct |
| 3890 | >>> m = memoryview(array.array('H', [32000, 32001, 32002])) |
| 3891 | >>> m.itemsize |
| 3892 | 2 |
| 3893 | >>> m[0] |
| 3894 | 32000 |
| 3895 | >>> struct.calcsize('H') == m.itemsize |
| 3896 | True |
| 3897 | |
| 3898 | .. attribute:: ndim |
| 3899 | |
| 3900 | An integer indicating how many dimensions of a multi-dimensional array the |
| 3901 | memory represents. |
| 3902 | |
| 3903 | .. attribute:: shape |
| 3904 | |
| 3905 | A tuple of integers the length of :attr:`ndim` giving the shape of the |
Alexander Belopolsky | e8677c0 | 2012-09-03 17:29:22 -0400 | [diff] [blame] | 3906 | memory as an N-dimensional array. |
| 3907 | |
| 3908 | .. versionchanged:: 3.3 |
Serhiy Storchaka | ecf41da | 2016-10-19 16:29:26 +0300 | [diff] [blame] | 3909 | An empty tuple instead of ``None`` when ndim = 0. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 3910 | |
| 3911 | .. attribute:: strides |
| 3912 | |
| 3913 | A tuple of integers the length of :attr:`ndim` giving the size in bytes to |
| 3914 | access each element for each dimension of the array. |
| 3915 | |
Alexander Belopolsky | e8677c0 | 2012-09-03 17:29:22 -0400 | [diff] [blame] | 3916 | .. versionchanged:: 3.3 |
Serhiy Storchaka | ecf41da | 2016-10-19 16:29:26 +0300 | [diff] [blame] | 3917 | An empty tuple instead of ``None`` when ndim = 0. |
Alexander Belopolsky | e8677c0 | 2012-09-03 17:29:22 -0400 | [diff] [blame] | 3918 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 3919 | .. attribute:: suboffsets |
| 3920 | |
| 3921 | Used internally for PIL-style arrays. The value is informational only. |
| 3922 | |
| 3923 | .. attribute:: c_contiguous |
| 3924 | |
Stefan Krah | 70e543b | 2015-08-08 14:33:28 +0200 | [diff] [blame] | 3925 | A bool indicating whether the memory is C-:term:`contiguous`. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 3926 | |
| 3927 | .. versionadded:: 3.3 |
| 3928 | |
| 3929 | .. attribute:: f_contiguous |
| 3930 | |
Stefan Krah | 70e543b | 2015-08-08 14:33:28 +0200 | [diff] [blame] | 3931 | A bool indicating whether the memory is Fortran :term:`contiguous`. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 3932 | |
| 3933 | .. versionadded:: 3.3 |
| 3934 | |
| 3935 | .. attribute:: contiguous |
| 3936 | |
Stefan Krah | 70e543b | 2015-08-08 14:33:28 +0200 | [diff] [blame] | 3937 | A bool indicating whether the memory is :term:`contiguous`. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 3938 | |
| 3939 | .. versionadded:: 3.3 |
| 3940 | |
| 3941 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3942 | .. _types-set: |
| 3943 | |
| 3944 | Set Types --- :class:`set`, :class:`frozenset` |
| 3945 | ============================================== |
| 3946 | |
| 3947 | .. index:: object: set |
| 3948 | |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 3949 | A :dfn:`set` object is an unordered collection of distinct :term:`hashable` objects. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3950 | Common uses include membership testing, removing duplicates from a sequence, and |
| 3951 | computing mathematical operations such as intersection, union, difference, and |
| 3952 | symmetric difference. |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 3953 | (For other containers see the built-in :class:`dict`, :class:`list`, |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3954 | and :class:`tuple` classes, and the :mod:`collections` module.) |
| 3955 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3956 | Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in |
| 3957 | set``. Being an unordered collection, sets do not record element position or |
| 3958 | order of insertion. Accordingly, sets do not support indexing, slicing, or |
| 3959 | other sequence-like behavior. |
| 3960 | |
Georg Brandl | 22b3431 | 2009-07-26 14:54:51 +0000 | [diff] [blame] | 3961 | There are currently two built-in set types, :class:`set` and :class:`frozenset`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3962 | The :class:`set` type is mutable --- the contents can be changed using methods |
Serhiy Storchaka | 0d196ed | 2013-10-09 14:02:31 +0300 | [diff] [blame] | 3963 | like :meth:`~set.add` and :meth:`~set.remove`. Since it is mutable, it has no |
| 3964 | hash value and cannot be used as either a dictionary key or as an element of |
| 3965 | another set. The :class:`frozenset` type is immutable and :term:`hashable` --- |
| 3966 | its contents cannot be altered after it is created; it can therefore be used as |
| 3967 | a dictionary key or as an element of another set. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3968 | |
Georg Brandl | 99cd957 | 2010-03-21 09:10:32 +0000 | [diff] [blame] | 3969 | Non-empty sets (not frozensets) can be created by placing a comma-separated list |
Georg Brandl | 53b95e7 | 2010-03-21 11:53:50 +0000 | [diff] [blame] | 3970 | of elements within braces, for example: ``{'jack', 'sjoerd'}``, in addition to the |
| 3971 | :class:`set` constructor. |
Georg Brandl | 99cd957 | 2010-03-21 09:10:32 +0000 | [diff] [blame] | 3972 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3973 | The constructors for both classes work the same: |
| 3974 | |
| 3975 | .. class:: set([iterable]) |
| 3976 | frozenset([iterable]) |
| 3977 | |
| 3978 | Return a new set or frozenset object whose elements are taken from |
Andrew Svetlov | 9a411ce | 2013-04-05 16:21:50 +0300 | [diff] [blame] | 3979 | *iterable*. The elements of a set must be :term:`hashable`. To |
| 3980 | represent sets of sets, the inner sets must be :class:`frozenset` |
| 3981 | objects. If *iterable* is not specified, a new empty set is |
| 3982 | returned. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3983 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 3984 | Instances of :class:`set` and :class:`frozenset` provide the following |
| 3985 | operations: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3986 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 3987 | .. describe:: len(s) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3988 | |
Gregory P. Smith | e27403b | 2016-02-08 09:58:40 -0800 | [diff] [blame] | 3989 | Return the number of elements in set *s* (cardinality of *s*). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3990 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 3991 | .. describe:: x in s |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3992 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 3993 | Test *x* for membership in *s*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3994 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 3995 | .. describe:: x not in s |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3996 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 3997 | Test *x* for non-membership in *s*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3998 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 3999 | .. method:: isdisjoint(other) |
Guido van Rossum | 58da931 | 2007-11-10 23:39:45 +0000 | [diff] [blame] | 4000 | |
Serhiy Storchaka | fbc1c26 | 2013-11-29 12:17:13 +0200 | [diff] [blame] | 4001 | Return ``True`` if the set has no elements in common with *other*. Sets are |
Georg Brandl | 2ee470f | 2008-07-16 12:55:28 +0000 | [diff] [blame] | 4002 | disjoint if and only if their intersection is the empty set. |
Guido van Rossum | 58da931 | 2007-11-10 23:39:45 +0000 | [diff] [blame] | 4003 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4004 | .. method:: issubset(other) |
| 4005 | set <= other |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4006 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4007 | Test whether every element in the set is in *other*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4008 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4009 | .. method:: set < other |
Georg Brandl | a6f5278 | 2007-09-01 15:49:30 +0000 | [diff] [blame] | 4010 | |
Andrew Svetlov | 5bb4207 | 2012-11-01 21:47:54 +0200 | [diff] [blame] | 4011 | Test whether the set is a proper subset of *other*, that is, |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4012 | ``set <= other and set != other``. |
Georg Brandl | a6f5278 | 2007-09-01 15:49:30 +0000 | [diff] [blame] | 4013 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4014 | .. method:: issuperset(other) |
| 4015 | set >= other |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4016 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4017 | Test whether every element in *other* is in the set. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4018 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4019 | .. method:: set > other |
Georg Brandl | a6f5278 | 2007-09-01 15:49:30 +0000 | [diff] [blame] | 4020 | |
Andrew Svetlov | 5bb4207 | 2012-11-01 21:47:54 +0200 | [diff] [blame] | 4021 | Test whether the set is a proper superset of *other*, that is, ``set >= |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4022 | other and set != other``. |
Georg Brandl | a6f5278 | 2007-09-01 15:49:30 +0000 | [diff] [blame] | 4023 | |
Raymond Hettinger | a33e9f7 | 2016-09-12 23:38:50 -0700 | [diff] [blame] | 4024 | .. method:: union(*others) |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 4025 | set | other | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4026 | |
Benjamin Peterson | b58dda7 | 2009-01-18 22:27:04 +0000 | [diff] [blame] | 4027 | Return a new set with elements from the set and all others. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4028 | |
Raymond Hettinger | a33e9f7 | 2016-09-12 23:38:50 -0700 | [diff] [blame] | 4029 | .. method:: intersection(*others) |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 4030 | set & other & ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4031 | |
Benjamin Peterson | b58dda7 | 2009-01-18 22:27:04 +0000 | [diff] [blame] | 4032 | Return a new set with elements common to the set and all others. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4033 | |
Raymond Hettinger | a33e9f7 | 2016-09-12 23:38:50 -0700 | [diff] [blame] | 4034 | .. method:: difference(*others) |
Amaury Forgeot d'Arc | fdfe62d | 2008-06-17 20:36:03 +0000 | [diff] [blame] | 4035 | set - other - ... |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 4036 | |
Amaury Forgeot d'Arc | fdfe62d | 2008-06-17 20:36:03 +0000 | [diff] [blame] | 4037 | Return a new set with elements in the set that are not in the others. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4038 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4039 | .. method:: symmetric_difference(other) |
| 4040 | set ^ other |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4041 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4042 | Return a new set with elements in either the set or *other* but not both. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4043 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4044 | .. method:: copy() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4045 | |
Andre Delfino | e942e7b | 2019-03-07 02:23:21 -0300 | [diff] [blame] | 4046 | Return a shallow copy of the set. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4047 | |
| 4048 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4049 | Note, the non-operator versions of :meth:`union`, :meth:`intersection`, |
| 4050 | :meth:`difference`, and :meth:`symmetric_difference`, :meth:`issubset`, and |
| 4051 | :meth:`issuperset` methods will accept any iterable as an argument. In |
| 4052 | contrast, their operator based counterparts require their arguments to be |
| 4053 | sets. This precludes error-prone constructions like ``set('abc') & 'cbs'`` |
| 4054 | in favor of the more readable ``set('abc').intersection('cbs')``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4055 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4056 | Both :class:`set` and :class:`frozenset` support set to set comparisons. Two |
| 4057 | sets are equal if and only if every element of each set is contained in the |
| 4058 | other (each is a subset of the other). A set is less than another set if and |
| 4059 | only if the first set is a proper subset of the second set (is a subset, but |
| 4060 | is not equal). A set is greater than another set if and only if the first set |
| 4061 | is a proper superset of the second set (is a superset, but is not equal). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4062 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4063 | Instances of :class:`set` are compared to instances of :class:`frozenset` |
| 4064 | based on their members. For example, ``set('abc') == frozenset('abc')`` |
| 4065 | returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4066 | |
Raymond Hettinger | 12f588a | 2013-05-06 18:22:43 -0700 | [diff] [blame] | 4067 | The subset and equality comparisons do not generalize to a total ordering |
| 4068 | function. For example, any two nonempty disjoint sets are not equal and are not |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4069 | subsets of each other, so *all* of the following return ``False``: ``a<b``, |
Georg Brandl | 05f5ab7 | 2008-09-24 09:11:47 +0000 | [diff] [blame] | 4070 | ``a==b``, or ``a>b``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4071 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4072 | Since sets only define partial ordering (subset relationships), the output of |
| 4073 | the :meth:`list.sort` method is undefined for lists of sets. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4074 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4075 | Set elements, like dictionary keys, must be :term:`hashable`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4076 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4077 | Binary operations that mix :class:`set` instances with :class:`frozenset` |
| 4078 | return the type of the first operand. For example: ``frozenset('ab') | |
| 4079 | set('bc')`` returns an instance of :class:`frozenset`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4080 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4081 | The following table lists operations available for :class:`set` that do not |
| 4082 | apply to immutable instances of :class:`frozenset`: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4083 | |
Raymond Hettinger | a33e9f7 | 2016-09-12 23:38:50 -0700 | [diff] [blame] | 4084 | .. method:: update(*others) |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 4085 | set |= other | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4086 | |
Georg Brandl | a6053b4 | 2009-09-01 08:11:14 +0000 | [diff] [blame] | 4087 | Update the set, adding elements from all others. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4088 | |
Raymond Hettinger | a33e9f7 | 2016-09-12 23:38:50 -0700 | [diff] [blame] | 4089 | .. method:: intersection_update(*others) |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 4090 | set &= other & ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4091 | |
Georg Brandl | a6053b4 | 2009-09-01 08:11:14 +0000 | [diff] [blame] | 4092 | Update the set, keeping only elements found in it and all others. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4093 | |
Raymond Hettinger | a33e9f7 | 2016-09-12 23:38:50 -0700 | [diff] [blame] | 4094 | .. method:: difference_update(*others) |
Amaury Forgeot d'Arc | fdfe62d | 2008-06-17 20:36:03 +0000 | [diff] [blame] | 4095 | set -= other | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4096 | |
Amaury Forgeot d'Arc | fdfe62d | 2008-06-17 20:36:03 +0000 | [diff] [blame] | 4097 | Update the set, removing elements found in others. |
| 4098 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4099 | .. method:: symmetric_difference_update(other) |
| 4100 | set ^= other |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4101 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4102 | Update the set, keeping only elements found in either set, but not in both. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4103 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4104 | .. method:: add(elem) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4105 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4106 | Add element *elem* to the set. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4107 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4108 | .. method:: remove(elem) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4109 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4110 | Remove element *elem* from the set. Raises :exc:`KeyError` if *elem* is |
| 4111 | not contained in the set. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4112 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4113 | .. method:: discard(elem) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4114 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4115 | Remove element *elem* from the set if it is present. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4116 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4117 | .. method:: pop() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4118 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4119 | Remove and return an arbitrary element from the set. Raises |
| 4120 | :exc:`KeyError` if the set is empty. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4121 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4122 | .. method:: clear() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4123 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4124 | Remove all elements from the set. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4125 | |
| 4126 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4127 | Note, the non-operator versions of the :meth:`update`, |
| 4128 | :meth:`intersection_update`, :meth:`difference_update`, and |
| 4129 | :meth:`symmetric_difference_update` methods will accept any iterable as an |
| 4130 | argument. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4131 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4132 | Note, the *elem* argument to the :meth:`__contains__`, :meth:`remove`, and |
| 4133 | :meth:`discard` methods may be a set. To support searching for an equivalent |
Julien | 0737ee2 | 2017-06-01 16:02:21 +0200 | [diff] [blame] | 4134 | frozenset, a temporary one is created from *elem*. |
Benjamin Peterson | 699adb9 | 2008-05-08 22:27:58 +0000 | [diff] [blame] | 4135 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4136 | |
| 4137 | .. _typesmapping: |
| 4138 | |
| 4139 | Mapping Types --- :class:`dict` |
| 4140 | =============================== |
| 4141 | |
| 4142 | .. index:: |
| 4143 | object: mapping |
| 4144 | object: dictionary |
| 4145 | triple: operations on; mapping; types |
| 4146 | triple: operations on; dictionary; type |
| 4147 | statement: del |
| 4148 | builtin: len |
| 4149 | |
Chris Jerdonek | 11f3f17 | 2012-11-03 12:05:55 -0700 | [diff] [blame] | 4150 | A :term:`mapping` object maps :term:`hashable` values to arbitrary objects. |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 4151 | Mappings are mutable objects. There is currently only one standard mapping |
Nick Coghlan | 83c0ae5 | 2012-08-21 17:42:52 +1000 | [diff] [blame] | 4152 | type, the :dfn:`dictionary`. (For other containers see the built-in |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 4153 | :class:`list`, :class:`set`, and :class:`tuple` classes, and the |
| 4154 | :mod:`collections` module.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4155 | |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 4156 | A dictionary's keys are *almost* arbitrary values. Values that are not |
| 4157 | :term:`hashable`, that is, values containing lists, dictionaries or other |
| 4158 | mutable types (that are compared by value rather than by object identity) may |
| 4159 | not be used as keys. Numeric types used for keys obey the normal rules for |
| 4160 | numeric comparison: if two numbers compare equal (such as ``1`` and ``1.0``) |
| 4161 | then they can be used interchangeably to index the same dictionary entry. (Note |
| 4162 | however, that since computers store floating-point numbers as approximations it |
| 4163 | is usually unwise to use them as dictionary keys.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4164 | |
| 4165 | Dictionaries can be created by placing a comma-separated list of ``key: value`` |
| 4166 | pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098: |
| 4167 | 'jack', 4127: 'sjoerd'}``, or by the :class:`dict` constructor. |
| 4168 | |
Chris Jerdonek | f341317 | 2012-10-13 03:22:33 -0700 | [diff] [blame] | 4169 | .. class:: dict(**kwarg) |
| 4170 | dict(mapping, **kwarg) |
| 4171 | dict(iterable, **kwarg) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4172 | |
Chris Jerdonek | f341317 | 2012-10-13 03:22:33 -0700 | [diff] [blame] | 4173 | Return a new dictionary initialized from an optional positional argument |
| 4174 | and a possibly empty set of keyword arguments. |
| 4175 | |
| 4176 | If no positional argument is given, an empty dictionary is created. |
| 4177 | If a positional argument is given and it is a mapping object, a dictionary |
| 4178 | is created with the same key-value pairs as the mapping object. Otherwise, |
Terry Jan Reedy | b52f876 | 2014-06-02 20:42:56 -0400 | [diff] [blame] | 4179 | the positional argument must be an :term:`iterable` object. Each item in |
| 4180 | the iterable must itself be an iterable with exactly two objects. The |
Chris Jerdonek | f341317 | 2012-10-13 03:22:33 -0700 | [diff] [blame] | 4181 | first object of each item becomes a key in the new dictionary, and the |
| 4182 | second object the corresponding value. If a key occurs more than once, the |
| 4183 | last value for that key becomes the corresponding value in the new |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 4184 | dictionary. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4185 | |
Chris Jerdonek | f341317 | 2012-10-13 03:22:33 -0700 | [diff] [blame] | 4186 | If keyword arguments are given, the keyword arguments and their values are |
| 4187 | added to the dictionary created from the positional argument. If a key |
| 4188 | being added is already present, the value from the keyword argument |
| 4189 | replaces the value from the positional argument. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4190 | |
Chris Jerdonek | f341317 | 2012-10-13 03:22:33 -0700 | [diff] [blame] | 4191 | To illustrate, the following examples all return a dictionary equal to |
Ezio Melotti | a20879f | 2012-10-26 19:14:16 +0300 | [diff] [blame] | 4192 | ``{"one": 1, "two": 2, "three": 3}``:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4193 | |
Ezio Melotti | a20879f | 2012-10-26 19:14:16 +0300 | [diff] [blame] | 4194 | >>> a = dict(one=1, two=2, three=3) |
| 4195 | >>> b = {'one': 1, 'two': 2, 'three': 3} |
| 4196 | >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3])) |
| 4197 | >>> d = dict([('two', 2), ('one', 1), ('three', 3)]) |
| 4198 | >>> e = dict({'three': 3, 'one': 1, 'two': 2}) |
Chris Jerdonek | f341317 | 2012-10-13 03:22:33 -0700 | [diff] [blame] | 4199 | >>> a == b == c == d == e |
| 4200 | True |
| 4201 | |
| 4202 | Providing keyword arguments as in the first example only works for keys that |
| 4203 | are valid Python identifiers. Otherwise, any valid keys can be used. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4204 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4205 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4206 | These are the operations that dictionaries support (and therefore, custom |
| 4207 | mapping types should support too): |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4208 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4209 | .. describe:: len(d) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4210 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4211 | Return the number of items in the dictionary *d*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4212 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4213 | .. describe:: d[key] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4214 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4215 | Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key* is |
| 4216 | not in the map. |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 4217 | |
Terry Jan Reedy | 06c6218 | 2014-12-10 18:48:23 -0500 | [diff] [blame] | 4218 | .. index:: __missing__() |
Terry Jan Reedy | e40031d | 2014-12-10 18:49:58 -0500 | [diff] [blame] | 4219 | |
Terry Jan Reedy | b67f6e2 | 2014-12-10 18:38:19 -0500 | [diff] [blame] | 4220 | If a subclass of dict defines a method :meth:`__missing__` and *key* |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4221 | is not present, the ``d[key]`` operation calls that method with the key *key* |
| 4222 | as argument. The ``d[key]`` operation then returns or raises whatever is |
Terry Jan Reedy | b67f6e2 | 2014-12-10 18:38:19 -0500 | [diff] [blame] | 4223 | returned or raised by the ``__missing__(key)`` call. |
| 4224 | No other operations or methods invoke :meth:`__missing__`. If |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4225 | :meth:`__missing__` is not defined, :exc:`KeyError` is raised. |
Raymond Hettinger | 5254e97 | 2011-01-08 09:35:38 +0000 | [diff] [blame] | 4226 | :meth:`__missing__` must be a method; it cannot be an instance variable:: |
| 4227 | |
| 4228 | >>> class Counter(dict): |
| 4229 | ... def __missing__(self, key): |
| 4230 | ... return 0 |
| 4231 | >>> c = Counter() |
| 4232 | >>> c['red'] |
| 4233 | 0 |
| 4234 | >>> c['red'] += 1 |
| 4235 | >>> c['red'] |
| 4236 | 1 |
| 4237 | |
Terry Jan Reedy | b67f6e2 | 2014-12-10 18:38:19 -0500 | [diff] [blame] | 4238 | The example above shows part of the implementation of |
| 4239 | :class:`collections.Counter`. A different ``__missing__`` method is used |
| 4240 | by :class:`collections.defaultdict`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4241 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4242 | .. describe:: d[key] = value |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4243 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4244 | Set ``d[key]`` to *value*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4245 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4246 | .. describe:: del d[key] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4247 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4248 | Remove ``d[key]`` from *d*. Raises a :exc:`KeyError` if *key* is not in the |
| 4249 | map. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4250 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4251 | .. describe:: key in d |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4252 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4253 | Return ``True`` if *d* has a key *key*, else ``False``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4254 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4255 | .. describe:: key not in d |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4256 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4257 | Equivalent to ``not key in d``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4258 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 4259 | .. describe:: iter(d) |
| 4260 | |
| 4261 | Return an iterator over the keys of the dictionary. This is a shortcut |
Georg Brandl | ede6c2a | 2010-01-05 10:22:04 +0000 | [diff] [blame] | 4262 | for ``iter(d.keys())``. |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 4263 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4264 | .. method:: clear() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4265 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4266 | Remove all items from the dictionary. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4267 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4268 | .. method:: copy() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4269 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4270 | Return a shallow copy of the dictionary. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4271 | |
Andre Delfino | f06fba5 | 2018-12-23 01:14:46 -0300 | [diff] [blame] | 4272 | .. classmethod:: fromkeys(iterable[, value]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4273 | |
Andre Delfino | f06fba5 | 2018-12-23 01:14:46 -0300 | [diff] [blame] | 4274 | Create a new dictionary with keys from *iterable* and values set to *value*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4275 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4276 | :meth:`fromkeys` is a class method that returns a new dictionary. *value* |
Raymond Hettinger | da63b32 | 2019-04-28 00:22:36 -0700 | [diff] [blame] | 4277 | defaults to ``None``. All of the values refer to just a single instance, |
| 4278 | so it generally doesn't make sense for *value* to be a mutable object |
| 4279 | such as an empty list. To get distinct values, use a :ref:`dict |
| 4280 | comprehension <dict>` instead. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4281 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4282 | .. method:: get(key[, default]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4283 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4284 | Return the value for *key* if *key* is in the dictionary, else *default*. |
| 4285 | If *default* is not given, it defaults to ``None``, so that this method |
| 4286 | never raises a :exc:`KeyError`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4287 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4288 | .. method:: items() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4289 | |
Victor Stinner | 0db176f | 2012-04-16 00:16:30 +0200 | [diff] [blame] | 4290 | Return a new view of the dictionary's items (``(key, value)`` pairs). |
| 4291 | See the :ref:`documentation of view objects <dict-views>`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4292 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4293 | .. method:: keys() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4294 | |
Victor Stinner | 0db176f | 2012-04-16 00:16:30 +0200 | [diff] [blame] | 4295 | Return a new view of the dictionary's keys. See the :ref:`documentation |
| 4296 | of view objects <dict-views>`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4297 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4298 | .. method:: pop(key[, default]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4299 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4300 | If *key* is in the dictionary, remove it and return its value, else return |
| 4301 | *default*. If *default* is not given and *key* is not in the dictionary, |
| 4302 | a :exc:`KeyError` is raised. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4303 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4304 | .. method:: popitem() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4305 | |
Raymond Hettinger | 01b7d58 | 2018-07-16 17:20:15 -0700 | [diff] [blame] | 4306 | Remove and return a ``(key, value)`` pair from the dictionary. |
| 4307 | Pairs are returned in :abbr:`LIFO (last-in, first-out)` order. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4308 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4309 | :meth:`popitem` is useful to destructively iterate over a dictionary, as |
| 4310 | often used in set algorithms. If the dictionary is empty, calling |
| 4311 | :meth:`popitem` raises a :exc:`KeyError`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4312 | |
Raymond Hettinger | 01b7d58 | 2018-07-16 17:20:15 -0700 | [diff] [blame] | 4313 | .. versionchanged:: 3.7 |
Andrés Delfino | cb9c299 | 2018-07-21 19:14:56 -0300 | [diff] [blame] | 4314 | LIFO order is now guaranteed. In prior versions, :meth:`popitem` would |
| 4315 | return an arbitrary key/value pair. |
Raymond Hettinger | 01b7d58 | 2018-07-16 17:20:15 -0700 | [diff] [blame] | 4316 | |
Rémi Lapeyre | 6531bf6 | 2018-11-06 01:38:54 +0100 | [diff] [blame] | 4317 | .. describe:: reversed(d) |
| 4318 | |
Andre Delfino | d83f5bd | 2018-12-24 04:05:23 -0300 | [diff] [blame] | 4319 | Return a reverse iterator over the keys of the dictionary. This is a |
Rémi Lapeyre | 6531bf6 | 2018-11-06 01:38:54 +0100 | [diff] [blame] | 4320 | shortcut for ``reversed(d.keys())``. |
| 4321 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4322 | .. method:: setdefault(key[, default]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4323 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4324 | If *key* is in the dictionary, return its value. If not, insert *key* |
| 4325 | with a value of *default* and return *default*. *default* defaults to |
| 4326 | ``None``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4327 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4328 | .. method:: update([other]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4329 | |
Éric Araujo | 0fc86b8 | 2010-08-18 22:29:54 +0000 | [diff] [blame] | 4330 | Update the dictionary with the key/value pairs from *other*, overwriting |
| 4331 | existing keys. Return ``None``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4332 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4333 | :meth:`update` accepts either another dictionary object or an iterable of |
Georg Brandl | fda2106 | 2010-09-25 16:56:36 +0000 | [diff] [blame] | 4334 | key/value pairs (as tuples or other iterables of length two). If keyword |
Benjamin Peterson | 8719ad5 | 2009-09-11 22:24:02 +0000 | [diff] [blame] | 4335 | arguments are specified, the dictionary is then updated with those |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4336 | key/value pairs: ``d.update(red=1, blue=2)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4337 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 4338 | .. method:: values() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4339 | |
Victor Stinner | 0db176f | 2012-04-16 00:16:30 +0200 | [diff] [blame] | 4340 | Return a new view of the dictionary's values. See the |
| 4341 | :ref:`documentation of view objects <dict-views>`. |
| 4342 | |
Terry Jan Reedy | fe63c9a | 2015-06-12 16:38:57 -0400 | [diff] [blame] | 4343 | Dictionaries compare equal if and only if they have the same ``(key, |
| 4344 | value)`` pairs. Order comparisons ('<', '<=', '>=', '>') raise |
| 4345 | :exc:`TypeError`. |
Terry Jan Reedy | 6ac5cc1 | 2015-06-12 16:47:44 -0400 | [diff] [blame] | 4346 | |
Neil Schemenauer | d3ed67d | 2018-06-07 14:46:04 -0700 | [diff] [blame] | 4347 | Dictionaries preserve insertion order. Note that updating a key does not |
| 4348 | affect the order. Keys added after deletion are inserted at the end. :: |
INADA Naoki | f822549 | 2018-06-05 07:09:22 +0900 | [diff] [blame] | 4349 | |
| 4350 | >>> d = {"one": 1, "two": 2, "three": 3, "four": 4} |
| 4351 | >>> d |
| 4352 | {'one': 1, 'two': 2, 'three': 3, 'four': 4} |
| 4353 | >>> list(d) |
| 4354 | ['one', 'two', 'three', 'four'] |
| 4355 | >>> list(d.values()) |
| 4356 | [1, 2, 3, 4] |
| 4357 | >>> d["one"] = 42 |
| 4358 | >>> d |
| 4359 | {'one': 42, 'two': 2, 'three': 3, 'four': 4} |
| 4360 | >>> del d["two"] |
| 4361 | >>> d["two"] = None |
| 4362 | >>> d |
| 4363 | {'one': 42, 'three': 3, 'four': 4, 'two': None} |
| 4364 | |
| 4365 | .. versionchanged:: 3.7 |
Neil Schemenauer | d3ed67d | 2018-06-07 14:46:04 -0700 | [diff] [blame] | 4366 | Dictionary order is guaranteed to be insertion order. This behavior was |
Andrés Delfino | 7610f4f | 2018-11-12 14:24:00 -0300 | [diff] [blame] | 4367 | an implementation detail of CPython from 3.6. |
INADA Naoki | f822549 | 2018-06-05 07:09:22 +0900 | [diff] [blame] | 4368 | |
Rémi Lapeyre | 6531bf6 | 2018-11-06 01:38:54 +0100 | [diff] [blame] | 4369 | Dictionaries and dictionary views are reversible. :: |
| 4370 | |
| 4371 | >>> d = {"one": 1, "two": 2, "three": 3, "four": 4} |
| 4372 | >>> d |
| 4373 | {'one': 1, 'two': 2, 'three': 3, 'four': 4} |
| 4374 | >>> list(reversed(d)) |
| 4375 | ['four', 'three', 'two', 'one'] |
| 4376 | >>> list(reversed(d.values())) |
| 4377 | [4, 3, 2, 1] |
| 4378 | >>> list(reversed(d.items())) |
| 4379 | [('four', 4), ('three', 3), ('two', 2), ('one', 1)] |
| 4380 | |
| 4381 | .. versionchanged:: 3.8 |
| 4382 | Dictionaries are now reversible. |
| 4383 | |
| 4384 | |
Victor Stinner | 0db176f | 2012-04-16 00:16:30 +0200 | [diff] [blame] | 4385 | .. seealso:: |
| 4386 | :class:`types.MappingProxyType` can be used to create a read-only view |
| 4387 | of a :class:`dict`. |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 4388 | |
| 4389 | |
Benjamin Peterson | 44309e6 | 2008-11-22 00:41:45 +0000 | [diff] [blame] | 4390 | .. _dict-views: |
| 4391 | |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 4392 | Dictionary view objects |
| 4393 | ----------------------- |
| 4394 | |
| 4395 | The objects returned by :meth:`dict.keys`, :meth:`dict.values` and |
| 4396 | :meth:`dict.items` are *view objects*. They provide a dynamic view on the |
| 4397 | dictionary's entries, which means that when the dictionary changes, the view |
Benjamin Peterson | ce0506c | 2008-11-17 21:47:41 +0000 | [diff] [blame] | 4398 | reflects these changes. |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 4399 | |
| 4400 | Dictionary views can be iterated over to yield their respective data, and |
| 4401 | support membership tests: |
| 4402 | |
| 4403 | .. describe:: len(dictview) |
| 4404 | |
| 4405 | Return the number of entries in the dictionary. |
| 4406 | |
| 4407 | .. describe:: iter(dictview) |
| 4408 | |
| 4409 | Return an iterator over the keys, values or items (represented as tuples of |
| 4410 | ``(key, value)``) in the dictionary. |
| 4411 | |
hui shang | dfbbbf1 | 2018-04-04 12:55:05 +0800 | [diff] [blame] | 4412 | Keys and values are iterated over in insertion order. |
| 4413 | This allows the creation of ``(value, key)`` pairs |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 4414 | using :func:`zip`: ``pairs = zip(d.values(), d.keys())``. Another way to |
| 4415 | create the same list is ``pairs = [(v, k) for (k, v) in d.items()]``. |
| 4416 | |
Georg Brandl | 8126914 | 2009-05-17 08:31:29 +0000 | [diff] [blame] | 4417 | Iterating views while adding or deleting entries in the dictionary may raise |
| 4418 | a :exc:`RuntimeError` or fail to iterate over all entries. |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 4419 | |
hui shang | dfbbbf1 | 2018-04-04 12:55:05 +0800 | [diff] [blame] | 4420 | .. versionchanged:: 3.7 |
Neil Schemenauer | d3ed67d | 2018-06-07 14:46:04 -0700 | [diff] [blame] | 4421 | Dictionary order is guaranteed to be insertion order. |
hui shang | dfbbbf1 | 2018-04-04 12:55:05 +0800 | [diff] [blame] | 4422 | |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 4423 | .. describe:: x in dictview |
| 4424 | |
| 4425 | Return ``True`` if *x* is in the underlying dictionary's keys, values or |
| 4426 | items (in the latter case, *x* should be a ``(key, value)`` tuple). |
| 4427 | |
Rémi Lapeyre | 6531bf6 | 2018-11-06 01:38:54 +0100 | [diff] [blame] | 4428 | .. describe:: reversed(dictview) |
| 4429 | |
Andre Delfino | d83f5bd | 2018-12-24 04:05:23 -0300 | [diff] [blame] | 4430 | Return a reverse iterator over the keys, values or items of the dictionary. |
Rémi Lapeyre | 6531bf6 | 2018-11-06 01:38:54 +0100 | [diff] [blame] | 4431 | The view will be iterated in reverse order of the insertion. |
| 4432 | |
| 4433 | .. versionchanged:: 3.8 |
| 4434 | Dictionary views are now reversible. |
| 4435 | |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 4436 | |
Benjamin Peterson | ce0506c | 2008-11-17 21:47:41 +0000 | [diff] [blame] | 4437 | Keys views are set-like since their entries are unique and hashable. If all |
Georg Brandl | f74cf77 | 2010-10-15 16:03:02 +0000 | [diff] [blame] | 4438 | values are hashable, so that ``(key, value)`` pairs are unique and hashable, |
| 4439 | then the items view is also set-like. (Values views are not treated as set-like |
| 4440 | since the entries are generally not unique.) For set-like views, all of the |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame] | 4441 | operations defined for the abstract base class :class:`collections.abc.Set` are |
Georg Brandl | f74cf77 | 2010-10-15 16:03:02 +0000 | [diff] [blame] | 4442 | available (for example, ``==``, ``<``, or ``^``). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4443 | |
Georg Brandl | c53c966 | 2007-09-04 17:58:02 +0000 | [diff] [blame] | 4444 | An example of dictionary view usage:: |
| 4445 | |
| 4446 | >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500} |
| 4447 | >>> keys = dishes.keys() |
| 4448 | >>> values = dishes.values() |
| 4449 | |
| 4450 | >>> # iteration |
| 4451 | >>> n = 0 |
| 4452 | >>> for val in values: |
| 4453 | ... n += val |
| 4454 | >>> print(n) |
| 4455 | 504 |
| 4456 | |
hui shang | dfbbbf1 | 2018-04-04 12:55:05 +0800 | [diff] [blame] | 4457 | >>> # keys and values are iterated over in the same order (insertion order) |
Georg Brandl | c53c966 | 2007-09-04 17:58:02 +0000 | [diff] [blame] | 4458 | >>> list(keys) |
hui shang | dfbbbf1 | 2018-04-04 12:55:05 +0800 | [diff] [blame] | 4459 | ['eggs', 'sausage', 'bacon', 'spam'] |
Georg Brandl | c53c966 | 2007-09-04 17:58:02 +0000 | [diff] [blame] | 4460 | >>> list(values) |
| 4461 | [2, 1, 1, 500] |
| 4462 | |
| 4463 | >>> # view objects are dynamic and reflect dict changes |
| 4464 | >>> del dishes['eggs'] |
| 4465 | >>> del dishes['sausage'] |
| 4466 | >>> list(keys) |
hui shang | dfbbbf1 | 2018-04-04 12:55:05 +0800 | [diff] [blame] | 4467 | ['bacon', 'spam'] |
Georg Brandl | c53c966 | 2007-09-04 17:58:02 +0000 | [diff] [blame] | 4468 | |
| 4469 | >>> # set operations |
| 4470 | >>> keys & {'eggs', 'bacon', 'salad'} |
Gregory P. Smith | e838812 | 2008-09-04 04:18:09 +0000 | [diff] [blame] | 4471 | {'bacon'} |
Georg Brandl | f74cf77 | 2010-10-15 16:03:02 +0000 | [diff] [blame] | 4472 | >>> keys ^ {'sausage', 'juice'} |
Sandro Tosi | 2a8d195 | 2011-08-02 18:42:04 +0200 | [diff] [blame] | 4473 | {'juice', 'sausage', 'bacon', 'spam'} |
Georg Brandl | c53c966 | 2007-09-04 17:58:02 +0000 | [diff] [blame] | 4474 | |
| 4475 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4476 | .. _typecontextmanager: |
| 4477 | |
| 4478 | Context Manager Types |
| 4479 | ===================== |
| 4480 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4481 | .. index:: |
| 4482 | single: context manager |
| 4483 | single: context management protocol |
| 4484 | single: protocol; context management |
| 4485 | |
| 4486 | Python's :keyword:`with` statement supports the concept of a runtime context |
Antoine Pitrou | a654090 | 2010-12-12 20:09:18 +0000 | [diff] [blame] | 4487 | defined by a context manager. This is implemented using a pair of methods |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4488 | that allow user-defined classes to define a runtime context that is entered |
Antoine Pitrou | a654090 | 2010-12-12 20:09:18 +0000 | [diff] [blame] | 4489 | before the statement body is executed and exited when the statement ends: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4490 | |
| 4491 | |
| 4492 | .. method:: contextmanager.__enter__() |
| 4493 | |
| 4494 | Enter the runtime context and return either this object or another object |
| 4495 | related to the runtime context. The value returned by this method is bound to |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 4496 | the identifier in the :keyword:`!as` clause of :keyword:`with` statements using |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4497 | this context manager. |
| 4498 | |
Antoine Pitrou | 11cb961 | 2010-09-15 11:11:28 +0000 | [diff] [blame] | 4499 | An example of a context manager that returns itself is a :term:`file object`. |
| 4500 | File objects return themselves from __enter__() to allow :func:`open` to be |
| 4501 | used as the context expression in a :keyword:`with` statement. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4502 | |
| 4503 | An example of a context manager that returns a related object is the one |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 4504 | returned by :func:`decimal.localcontext`. These managers set the active |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4505 | decimal context to a copy of the original decimal context and then return the |
| 4506 | copy. This allows changes to be made to the current decimal context in the body |
| 4507 | of the :keyword:`with` statement without affecting code outside the |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 4508 | :keyword:`!with` statement. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4509 | |
| 4510 | |
| 4511 | .. method:: contextmanager.__exit__(exc_type, exc_val, exc_tb) |
| 4512 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 4513 | Exit the runtime context and return a Boolean flag indicating if any exception |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4514 | that occurred should be suppressed. If an exception occurred while executing the |
| 4515 | body of the :keyword:`with` statement, the arguments contain the exception type, |
| 4516 | value and traceback information. Otherwise, all three arguments are ``None``. |
| 4517 | |
| 4518 | Returning a true value from this method will cause the :keyword:`with` statement |
| 4519 | to suppress the exception and continue execution with the statement immediately |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 4520 | following the :keyword:`!with` statement. Otherwise the exception continues |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4521 | propagating after this method has finished executing. Exceptions that occur |
| 4522 | during execution of this method will replace any exception that occurred in the |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 4523 | body of the :keyword:`!with` statement. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4524 | |
| 4525 | The exception passed in should never be reraised explicitly - instead, this |
| 4526 | method should return a false value to indicate that the method completed |
| 4527 | successfully and does not want to suppress the raised exception. This allows |
Georg Brandl | e4196d3 | 2014-10-31 09:41:46 +0100 | [diff] [blame] | 4528 | context management code to easily detect whether or not an :meth:`__exit__` |
| 4529 | method has actually failed. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4530 | |
| 4531 | Python defines several context managers to support easy thread synchronisation, |
| 4532 | prompt closure of files or other objects, and simpler manipulation of the active |
| 4533 | decimal arithmetic context. The specific types are not treated specially beyond |
| 4534 | their implementation of the context management protocol. See the |
| 4535 | :mod:`contextlib` module for some examples. |
| 4536 | |
Antoine Pitrou | a654090 | 2010-12-12 20:09:18 +0000 | [diff] [blame] | 4537 | Python's :term:`generator`\s and the :class:`contextlib.contextmanager` decorator |
Christian Heimes | d8654cf | 2007-12-02 15:22:16 +0000 | [diff] [blame] | 4538 | provide a convenient way to implement these protocols. If a generator function is |
Antoine Pitrou | a654090 | 2010-12-12 20:09:18 +0000 | [diff] [blame] | 4539 | decorated with the :class:`contextlib.contextmanager` decorator, it will return a |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4540 | context manager implementing the necessary :meth:`__enter__` and |
| 4541 | :meth:`__exit__` methods, rather than the iterator produced by an undecorated |
| 4542 | generator function. |
| 4543 | |
| 4544 | Note that there is no specific slot for any of these methods in the type |
| 4545 | structure for Python objects in the Python/C API. Extension types wanting to |
| 4546 | define these methods must provide them as a normal Python accessible method. |
| 4547 | Compared to the overhead of setting up the runtime context, the overhead of a |
| 4548 | single class dictionary lookup is negligible. |
| 4549 | |
| 4550 | |
| 4551 | .. _typesother: |
| 4552 | |
| 4553 | Other Built-in Types |
| 4554 | ==================== |
| 4555 | |
| 4556 | The interpreter supports several other kinds of objects. Most of these support |
| 4557 | only one or two operations. |
| 4558 | |
| 4559 | |
| 4560 | .. _typesmodules: |
| 4561 | |
| 4562 | Modules |
| 4563 | ------- |
| 4564 | |
| 4565 | The only special operation on a module is attribute access: ``m.name``, where |
| 4566 | *m* is a module and *name* accesses a name defined in *m*'s symbol table. |
| 4567 | Module attributes can be assigned to. (Note that the :keyword:`import` |
| 4568 | statement is not, strictly speaking, an operation on a module object; ``import |
| 4569 | foo`` does not require a module object named *foo* to exist, rather it requires |
| 4570 | an (external) *definition* for a module named *foo* somewhere.) |
| 4571 | |
Serhiy Storchaka | 0d196ed | 2013-10-09 14:02:31 +0300 | [diff] [blame] | 4572 | A special attribute of every module is :attr:`~object.__dict__`. This is the |
| 4573 | dictionary containing the module's symbol table. Modifying this dictionary will |
| 4574 | actually change the module's symbol table, but direct assignment to the |
Martin Panter | bae5d81 | 2016-06-18 03:57:31 +0000 | [diff] [blame] | 4575 | :attr:`~object.__dict__` attribute is not possible (you can write |
Serhiy Storchaka | 0d196ed | 2013-10-09 14:02:31 +0300 | [diff] [blame] | 4576 | ``m.__dict__['a'] = 1``, which defines ``m.a`` to be ``1``, but you can't write |
Martin Panter | bae5d81 | 2016-06-18 03:57:31 +0000 | [diff] [blame] | 4577 | ``m.__dict__ = {}``). Modifying :attr:`~object.__dict__` directly is |
| 4578 | not recommended. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4579 | |
| 4580 | Modules built into the interpreter are written like this: ``<module 'sys' |
| 4581 | (built-in)>``. If loaded from a file, they are written as ``<module 'os' from |
| 4582 | '/usr/local/lib/pythonX.Y/os.pyc'>``. |
| 4583 | |
| 4584 | |
| 4585 | .. _typesobjects: |
| 4586 | |
| 4587 | Classes and Class Instances |
| 4588 | --------------------------- |
| 4589 | |
| 4590 | See :ref:`objects` and :ref:`class` for these. |
| 4591 | |
| 4592 | |
| 4593 | .. _typesfunctions: |
| 4594 | |
| 4595 | Functions |
| 4596 | --------- |
| 4597 | |
| 4598 | Function objects are created by function definitions. The only operation on a |
| 4599 | function object is to call it: ``func(argument-list)``. |
| 4600 | |
| 4601 | There are really two flavors of function objects: built-in functions and |
| 4602 | user-defined functions. Both support the same operation (to call the function), |
| 4603 | but the implementation is different, hence the different object types. |
| 4604 | |
| 4605 | See :ref:`function` for more information. |
| 4606 | |
| 4607 | |
| 4608 | .. _typesmethods: |
| 4609 | |
| 4610 | Methods |
| 4611 | ------- |
| 4612 | |
| 4613 | .. index:: object: method |
| 4614 | |
| 4615 | Methods are functions that are called using the attribute notation. There are |
| 4616 | two flavors: built-in methods (such as :meth:`append` on lists) and class |
| 4617 | instance methods. Built-in methods are described with the types that support |
| 4618 | them. |
| 4619 | |
Georg Brandl | 2e0b755 | 2007-11-27 12:43:08 +0000 | [diff] [blame] | 4620 | If you access a method (a function defined in a class namespace) through an |
| 4621 | instance, you get a special object: a :dfn:`bound method` (also called |
| 4622 | :dfn:`instance method`) object. When called, it will add the ``self`` argument |
| 4623 | to the argument list. Bound methods have two special read-only attributes: |
| 4624 | ``m.__self__`` is the object on which the method operates, and ``m.__func__`` is |
| 4625 | the function implementing the method. Calling ``m(arg-1, arg-2, ..., arg-n)`` |
| 4626 | is completely equivalent to calling ``m.__func__(m.__self__, arg-1, arg-2, ..., |
| 4627 | arg-n)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4628 | |
Georg Brandl | 2e0b755 | 2007-11-27 12:43:08 +0000 | [diff] [blame] | 4629 | Like function objects, bound method objects support getting arbitrary |
| 4630 | attributes. However, since method attributes are actually stored on the |
| 4631 | underlying function object (``meth.__func__``), setting method attributes on |
Ezio Melotti | 8b6b176 | 2012-11-09 01:08:25 +0200 | [diff] [blame] | 4632 | bound methods is disallowed. Attempting to set an attribute on a method |
| 4633 | results in an :exc:`AttributeError` being raised. In order to set a method |
| 4634 | attribute, you need to explicitly set it on the underlying function object:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4635 | |
Ezio Melotti | 8b6b176 | 2012-11-09 01:08:25 +0200 | [diff] [blame] | 4636 | >>> class C: |
| 4637 | ... def method(self): |
| 4638 | ... pass |
| 4639 | ... |
| 4640 | >>> c = C() |
| 4641 | >>> c.method.whoami = 'my name is method' # can't set on the method |
| 4642 | Traceback (most recent call last): |
| 4643 | File "<stdin>", line 1, in <module> |
| 4644 | AttributeError: 'method' object has no attribute 'whoami' |
| 4645 | >>> c.method.__func__.whoami = 'my name is method' |
| 4646 | >>> c.method.whoami |
| 4647 | 'my name is method' |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4648 | |
| 4649 | See :ref:`types` for more information. |
| 4650 | |
| 4651 | |
Tommy Beadle | e9b8403 | 2016-06-02 19:26:51 -0400 | [diff] [blame] | 4652 | .. index:: object; code, code object |
| 4653 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4654 | .. _bltin-code-objects: |
| 4655 | |
| 4656 | Code Objects |
| 4657 | ------------ |
| 4658 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4659 | .. index:: |
| 4660 | builtin: compile |
| 4661 | single: __code__ (function object attribute) |
| 4662 | |
| 4663 | Code objects are used by the implementation to represent "pseudo-compiled" |
| 4664 | executable Python code such as a function body. They differ from function |
| 4665 | objects because they don't contain a reference to their global execution |
| 4666 | environment. Code objects are returned by the built-in :func:`compile` function |
| 4667 | and can be extracted from function objects through their :attr:`__code__` |
| 4668 | attribute. See also the :mod:`code` module. |
| 4669 | |
| 4670 | .. index:: |
| 4671 | builtin: exec |
| 4672 | builtin: eval |
| 4673 | |
| 4674 | A code object can be executed or evaluated by passing it (instead of a source |
| 4675 | string) to the :func:`exec` or :func:`eval` built-in functions. |
| 4676 | |
| 4677 | See :ref:`types` for more information. |
| 4678 | |
| 4679 | |
| 4680 | .. _bltin-type-objects: |
| 4681 | |
| 4682 | Type Objects |
| 4683 | ------------ |
| 4684 | |
| 4685 | .. index:: |
| 4686 | builtin: type |
| 4687 | module: types |
| 4688 | |
| 4689 | Type objects represent the various object types. An object's type is accessed |
| 4690 | by the built-in function :func:`type`. There are no special operations on |
| 4691 | types. The standard module :mod:`types` defines names for all standard built-in |
| 4692 | types. |
| 4693 | |
Martin v. Löwis | 250ad61 | 2008-04-07 05:43:42 +0000 | [diff] [blame] | 4694 | Types are written like this: ``<class 'int'>``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4695 | |
| 4696 | |
| 4697 | .. _bltin-null-object: |
| 4698 | |
| 4699 | The Null Object |
| 4700 | --------------- |
| 4701 | |
| 4702 | This object is returned by functions that don't explicitly return a value. It |
| 4703 | supports no special operations. There is exactly one null object, named |
Benjamin Peterson | 98f2b9b | 2011-07-30 12:26:27 -0500 | [diff] [blame] | 4704 | ``None`` (a built-in name). ``type(None)()`` produces the same singleton. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4705 | |
| 4706 | It is written as ``None``. |
| 4707 | |
| 4708 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 4709 | .. index:: single: ...; ellipsis literal |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4710 | .. _bltin-ellipsis-object: |
| 4711 | |
| 4712 | The Ellipsis Object |
| 4713 | ------------------- |
| 4714 | |
Benjamin Peterson | d5a1c44 | 2012-05-14 22:09:31 -0700 | [diff] [blame] | 4715 | This object is commonly used by slicing (see :ref:`slicings`). It supports no |
| 4716 | special operations. There is exactly one ellipsis object, named |
| 4717 | :const:`Ellipsis` (a built-in name). ``type(Ellipsis)()`` produces the |
| 4718 | :const:`Ellipsis` singleton. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4719 | |
| 4720 | It is written as ``Ellipsis`` or ``...``. |
| 4721 | |
| 4722 | |
Éric Araujo | 18ddf82 | 2011-09-01 23:10:36 +0200 | [diff] [blame] | 4723 | .. _bltin-notimplemented-object: |
| 4724 | |
Benjamin Peterson | 50211fa | 2011-07-30 09:57:24 -0500 | [diff] [blame] | 4725 | The NotImplemented Object |
| 4726 | ------------------------- |
| 4727 | |
| 4728 | This object is returned from comparisons and binary operations when they are |
| 4729 | asked to operate on types they don't support. See :ref:`comparisons` for more |
Benjamin Peterson | 98f2b9b | 2011-07-30 12:26:27 -0500 | [diff] [blame] | 4730 | information. There is exactly one ``NotImplemented`` object. |
| 4731 | ``type(NotImplemented)()`` produces the singleton instance. |
Benjamin Peterson | 50211fa | 2011-07-30 09:57:24 -0500 | [diff] [blame] | 4732 | |
| 4733 | It is written as ``NotImplemented``. |
| 4734 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4735 | |
Éric Araujo | 18ddf82 | 2011-09-01 23:10:36 +0200 | [diff] [blame] | 4736 | .. _bltin-boolean-values: |
| 4737 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4738 | Boolean Values |
| 4739 | -------------- |
| 4740 | |
| 4741 | Boolean values are the two constant objects ``False`` and ``True``. They are |
| 4742 | used to represent truth values (although other values can also be considered |
| 4743 | false or true). In numeric contexts (for example when used as the argument to |
| 4744 | an arithmetic operator), they behave like the integers 0 and 1, respectively. |
Ezio Melotti | c1f26f6 | 2011-12-02 19:47:24 +0200 | [diff] [blame] | 4745 | The built-in function :func:`bool` can be used to convert any value to a |
| 4746 | Boolean, if the value can be interpreted as a truth value (see section |
| 4747 | :ref:`truth` above). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4748 | |
| 4749 | .. index:: |
| 4750 | single: False |
| 4751 | single: True |
| 4752 | pair: Boolean; values |
| 4753 | |
| 4754 | They are written as ``False`` and ``True``, respectively. |
| 4755 | |
| 4756 | |
| 4757 | .. _typesinternal: |
| 4758 | |
| 4759 | Internal Objects |
| 4760 | ---------------- |
| 4761 | |
| 4762 | See :ref:`types` for this information. It describes stack frame objects, |
| 4763 | traceback objects, and slice objects. |
| 4764 | |
| 4765 | |
| 4766 | .. _specialattrs: |
| 4767 | |
| 4768 | Special Attributes |
| 4769 | ================== |
| 4770 | |
| 4771 | The implementation adds a few special read-only attributes to several object |
| 4772 | types, where they are relevant. Some of these are not reported by the |
| 4773 | :func:`dir` built-in function. |
| 4774 | |
| 4775 | |
| 4776 | .. attribute:: object.__dict__ |
| 4777 | |
| 4778 | A dictionary or other mapping object used to store an object's (writable) |
| 4779 | attributes. |
| 4780 | |
| 4781 | |
| 4782 | .. attribute:: instance.__class__ |
| 4783 | |
| 4784 | The class to which a class instance belongs. |
| 4785 | |
| 4786 | |
| 4787 | .. attribute:: class.__bases__ |
| 4788 | |
Benjamin Peterson | 1baf465 | 2009-12-31 03:11:23 +0000 | [diff] [blame] | 4789 | The tuple of base classes of a class object. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4790 | |
| 4791 | |
Martin Panter | bae5d81 | 2016-06-18 03:57:31 +0000 | [diff] [blame] | 4792 | .. attribute:: definition.__name__ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4793 | |
Martin Panter | bae5d81 | 2016-06-18 03:57:31 +0000 | [diff] [blame] | 4794 | The name of the class, function, method, descriptor, or |
| 4795 | generator instance. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4796 | |
Georg Brandl | 7a51e58 | 2009-03-28 19:13:21 +0000 | [diff] [blame] | 4797 | |
Martin Panter | bae5d81 | 2016-06-18 03:57:31 +0000 | [diff] [blame] | 4798 | .. attribute:: definition.__qualname__ |
Antoine Pitrou | 86a36b5 | 2011-11-25 18:56:07 +0100 | [diff] [blame] | 4799 | |
Martin Panter | bae5d81 | 2016-06-18 03:57:31 +0000 | [diff] [blame] | 4800 | The :term:`qualified name` of the class, function, method, descriptor, |
| 4801 | or generator instance. |
Antoine Pitrou | 86a36b5 | 2011-11-25 18:56:07 +0100 | [diff] [blame] | 4802 | |
| 4803 | .. versionadded:: 3.3 |
| 4804 | |
| 4805 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 4806 | .. attribute:: class.__mro__ |
| 4807 | |
| 4808 | This attribute is a tuple of classes that are considered when looking for |
| 4809 | base classes during method resolution. |
| 4810 | |
| 4811 | |
| 4812 | .. method:: class.mro() |
| 4813 | |
| 4814 | This method can be overridden by a metaclass to customize the method |
| 4815 | resolution order for its instances. It is called at class instantiation, and |
Serhiy Storchaka | 0d196ed | 2013-10-09 14:02:31 +0300 | [diff] [blame] | 4816 | its result is stored in :attr:`~class.__mro__`. |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 4817 | |
| 4818 | |
Georg Brandl | 7a51e58 | 2009-03-28 19:13:21 +0000 | [diff] [blame] | 4819 | .. method:: class.__subclasses__ |
| 4820 | |
Florent Xicluna | 74e6495 | 2011-10-28 11:21:19 +0200 | [diff] [blame] | 4821 | Each class keeps a list of weak references to its immediate subclasses. This |
| 4822 | method returns a list of all those references still alive. |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 4823 | Example:: |
Georg Brandl | 7a51e58 | 2009-03-28 19:13:21 +0000 | [diff] [blame] | 4824 | |
| 4825 | >>> int.__subclasses__() |
Florent Xicluna | 74e6495 | 2011-10-28 11:21:19 +0200 | [diff] [blame] | 4826 | [<class 'bool'>] |
Georg Brandl | 7a51e58 | 2009-03-28 19:13:21 +0000 | [diff] [blame] | 4827 | |
| 4828 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4829 | .. rubric:: Footnotes |
| 4830 | |
Ezio Melotti | 0656a56 | 2011-08-15 14:27:19 +0300 | [diff] [blame] | 4831 | .. [1] Additional information on these special methods may be found in the Python |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4832 | Reference Manual (:ref:`customization`). |
| 4833 | |
Ezio Melotti | 0656a56 | 2011-08-15 14:27:19 +0300 | [diff] [blame] | 4834 | .. [2] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4835 | similarly for tuples. |
| 4836 | |
Ezio Melotti | 0656a56 | 2011-08-15 14:27:19 +0300 | [diff] [blame] | 4837 | .. [3] They must have since the parser can't tell the type of the operands. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4838 | |
Ezio Melotti | 0656a56 | 2011-08-15 14:27:19 +0300 | [diff] [blame] | 4839 | .. [4] Cased characters are those with general category property being one of |
| 4840 | "Lu" (Letter, uppercase), "Ll" (Letter, lowercase), or "Lt" (Letter, titlecase). |
| 4841 | |
| 4842 | .. [5] To format only a tuple you should therefore provide a singleton tuple whose only |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 4843 | element is the tuple to be formatted. |