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 | |
| 15 | The principal built-in types are numerics, sequences, mappings, files, classes, |
| 16 | instances and exceptions. |
| 17 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 18 | Some operations are supported by several object types; in particular, |
| 19 | practically all objects can be compared, tested for truth value, and converted |
| 20 | to a string (with the :func:`repr` function or the slightly different |
| 21 | :func:`str` function). The latter function is implicitly used when an object is |
| 22 | written by the :func:`print` function. |
| 23 | |
| 24 | |
| 25 | .. _truth: |
| 26 | |
| 27 | Truth Value Testing |
| 28 | =================== |
| 29 | |
| 30 | .. index:: |
| 31 | statement: if |
| 32 | statement: while |
| 33 | pair: truth; value |
| 34 | pair: Boolean; operations |
| 35 | single: false |
| 36 | |
| 37 | Any object can be tested for truth value, for use in an :keyword:`if` or |
| 38 | :keyword:`while` condition or as operand of the Boolean operations below. The |
| 39 | following values are considered false: |
| 40 | |
| 41 | .. index:: single: None (Built-in object) |
| 42 | |
| 43 | * ``None`` |
| 44 | |
| 45 | .. index:: single: False (Built-in object) |
| 46 | |
| 47 | * ``False`` |
| 48 | |
Mark Summerfield | bbfd71d | 2008-07-01 15:50:04 +0000 | [diff] [blame] | 49 | * zero of any numeric type, for example, ``0``, ``0.0``, ``0j``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 50 | |
| 51 | * any empty sequence, for example, ``''``, ``()``, ``[]``. |
| 52 | |
| 53 | * any empty mapping, for example, ``{}``. |
| 54 | |
| 55 | * instances of user-defined classes, if the class defines a :meth:`__bool__` or |
| 56 | :meth:`__len__` method, when that method returns the integer zero or |
| 57 | :class:`bool` value ``False``. [#]_ |
| 58 | |
| 59 | .. index:: single: true |
| 60 | |
| 61 | All other values are considered true --- so objects of many types are always |
| 62 | true. |
| 63 | |
| 64 | .. index:: |
| 65 | operator: or |
| 66 | operator: and |
| 67 | single: False |
| 68 | single: True |
| 69 | |
| 70 | Operations and built-in functions that have a Boolean result always return ``0`` |
| 71 | or ``False`` for false and ``1`` or ``True`` for true, unless otherwise stated. |
| 72 | (Important exception: the Boolean operations ``or`` and ``and`` always return |
| 73 | one of their operands.) |
| 74 | |
| 75 | |
| 76 | .. _boolean: |
| 77 | |
| 78 | Boolean Operations --- :keyword:`and`, :keyword:`or`, :keyword:`not` |
| 79 | ==================================================================== |
| 80 | |
| 81 | .. index:: pair: Boolean; operations |
| 82 | |
| 83 | These are the Boolean operations, ordered by ascending priority: |
| 84 | |
| 85 | +-------------+---------------------------------+-------+ |
| 86 | | Operation | Result | Notes | |
| 87 | +=============+=================================+=======+ |
| 88 | | ``x or y`` | if *x* is false, then *y*, else | \(1) | |
| 89 | | | *x* | | |
| 90 | +-------------+---------------------------------+-------+ |
| 91 | | ``x and y`` | if *x* is false, then *x*, else | \(2) | |
| 92 | | | *y* | | |
| 93 | +-------------+---------------------------------+-------+ |
| 94 | | ``not x`` | if *x* is false, then ``True``, | \(3) | |
| 95 | | | else ``False`` | | |
| 96 | +-------------+---------------------------------+-------+ |
| 97 | |
| 98 | .. index:: |
| 99 | operator: and |
| 100 | operator: or |
| 101 | operator: not |
| 102 | |
| 103 | Notes: |
| 104 | |
| 105 | (1) |
| 106 | This is a short-circuit operator, so it only evaluates the second |
| 107 | argument if the first one is :const:`False`. |
| 108 | |
| 109 | (2) |
| 110 | This is a short-circuit operator, so it only evaluates the second |
| 111 | argument if the first one is :const:`True`. |
| 112 | |
| 113 | (3) |
| 114 | ``not`` has a lower priority than non-Boolean operators, so ``not a == b`` is |
| 115 | interpreted as ``not (a == b)``, and ``a == not b`` is a syntax error. |
| 116 | |
| 117 | |
| 118 | .. _stdcomparisons: |
| 119 | |
| 120 | Comparisons |
| 121 | =========== |
| 122 | |
| 123 | .. index:: pair: chaining; comparisons |
| 124 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 125 | There are eight comparison operations in Python. They all have the same |
| 126 | priority (which is higher than that of the Boolean operations). Comparisons can |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 127 | be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and |
| 128 | y <= z``, except that *y* is evaluated only once (but in both cases *z* is not |
| 129 | evaluated at all when ``x < y`` is found to be false). |
| 130 | |
Georg Brandl | 81ac1ce | 2007-08-31 17:17:17 +0000 | [diff] [blame] | 131 | .. index:: |
| 132 | pair: operator; comparison |
| 133 | operator: == |
| 134 | operator: < |
| 135 | operator: > |
| 136 | operator: <= |
| 137 | operator: >= |
| 138 | operator: != |
| 139 | operator: is |
| 140 | operator: is not |
| 141 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 142 | This table summarizes the comparison operations: |
| 143 | |
Georg Brandl | fd85516 | 2008-01-07 09:13:03 +0000 | [diff] [blame] | 144 | +------------+-------------------------+ |
| 145 | | Operation | Meaning | |
| 146 | +============+=========================+ |
| 147 | | ``<`` | strictly less than | |
| 148 | +------------+-------------------------+ |
| 149 | | ``<=`` | less than or equal | |
| 150 | +------------+-------------------------+ |
| 151 | | ``>`` | strictly greater than | |
| 152 | +------------+-------------------------+ |
| 153 | | ``>=`` | greater than or equal | |
| 154 | +------------+-------------------------+ |
| 155 | | ``==`` | equal | |
| 156 | +------------+-------------------------+ |
| 157 | | ``!=`` | not equal | |
| 158 | +------------+-------------------------+ |
| 159 | | ``is`` | object identity | |
| 160 | +------------+-------------------------+ |
| 161 | | ``is not`` | negated object identity | |
| 162 | +------------+-------------------------+ |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 163 | |
| 164 | .. index:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 165 | pair: object; numeric |
| 166 | pair: objects; comparing |
| 167 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 168 | Objects of different types, except different numeric types, never compare equal. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 169 | Furthermore, some types (for example, file objects) support only a degenerate |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 170 | notion of comparison where any two objects of that type are unequal. The ``<``, |
| 171 | ``<=``, ``>`` and ``>=`` operators will raise a :exc:`TypeError` exception when |
| 172 | any operand is a complex number, the objects are of different types that cannot |
| 173 | be compared, or other cases where there is no defined ordering. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 174 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 175 | .. index:: |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 176 | single: __eq__() (instance method) |
| 177 | single: __ne__() (instance method) |
| 178 | single: __lt__() (instance method) |
| 179 | single: __le__() (instance method) |
| 180 | single: __gt__() (instance method) |
| 181 | single: __ge__() (instance method) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 182 | |
Georg Brandl | 05f5ab7 | 2008-09-24 09:11:47 +0000 | [diff] [blame] | 183 | Non-identical instances of a class normally compare as non-equal unless the |
| 184 | class defines the :meth:`__eq__` method. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 185 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 186 | Instances of a class cannot be ordered with respect to other instances of the |
| 187 | same class, or other types of object, unless the class defines enough of the |
Georg Brandl | 05f5ab7 | 2008-09-24 09:11:47 +0000 | [diff] [blame] | 188 | methods :meth:`__lt__`, :meth:`__le__`, :meth:`__gt__`, and :meth:`__ge__` (in |
| 189 | general, :meth:`__lt__` and :meth:`__eq__` are sufficient, if you want the |
| 190 | conventional meanings of the comparison operators). |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 191 | |
| 192 | The behavior of the :keyword:`is` and :keyword:`is not` operators cannot be |
| 193 | customized; also they can be applied to any two objects and never raise an |
| 194 | exception. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 195 | |
| 196 | .. index:: |
| 197 | operator: in |
| 198 | operator: not in |
| 199 | |
| 200 | Two more operations with the same syntactic priority, ``in`` and ``not in``, are |
| 201 | supported only by sequence types (below). |
| 202 | |
| 203 | |
| 204 | .. _typesnumeric: |
| 205 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 206 | Numeric Types --- :class:`int`, :class:`float`, :class:`complex` |
| 207 | ================================================================ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 208 | |
| 209 | .. index:: |
| 210 | object: numeric |
| 211 | object: Boolean |
| 212 | object: integer |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 213 | object: floating point |
| 214 | object: complex number |
| 215 | pair: C; language |
| 216 | |
Mark Summerfield | bbfd71d | 2008-07-01 15:50:04 +0000 | [diff] [blame] | 217 | There are three distinct numeric types: :dfn:`integers`, :dfn:`floating |
| 218 | point numbers`, and :dfn:`complex numbers`. In addition, Booleans are a |
| 219 | subtype of integers. Integers have unlimited precision. Floating point |
| 220 | numbers are implemented using :ctype:`double` in C---all bets on their |
| 221 | precision are off unless you happen to know the machine you are working |
| 222 | with. Complex numbers have a real and imaginary part, which are each |
| 223 | implemented using :ctype:`double` in C. To extract these parts from a |
| 224 | complex number *z*, use ``z.real`` and ``z.imag``. (The standard library |
| 225 | includes additional numeric types, :mod:`fractions` that hold rationals, |
| 226 | and :mod:`decimal` that hold floating-point numbers with user-definable |
| 227 | precision.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 228 | |
| 229 | .. index:: |
| 230 | pair: numeric; literals |
| 231 | pair: integer; literals |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 232 | pair: floating point; literals |
| 233 | pair: complex number; literals |
| 234 | pair: hexadecimal; literals |
| 235 | pair: octal; literals |
Neal Norwitz | 1d2aef5 | 2007-10-02 07:26:14 +0000 | [diff] [blame] | 236 | pair: binary; literals |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 237 | |
| 238 | 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] | 239 | and operators. Unadorned integer literals (including hex, octal and binary |
| 240 | numbers) yield integers. Numeric literals containing a decimal point or an |
| 241 | exponent sign yield floating point numbers. Appending ``'j'`` or ``'J'`` to a |
| 242 | numeric literal yields an imaginary number (a complex number with a zero real |
| 243 | part) which you can add to an integer or float to get a complex number with real |
| 244 | and imaginary parts. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 245 | |
| 246 | .. index:: |
| 247 | single: arithmetic |
| 248 | builtin: int |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 249 | builtin: float |
| 250 | builtin: complex |
| 251 | |
| 252 | Python fully supports mixed arithmetic: when a binary arithmetic operator has |
| 253 | operands of different numeric types, the operand with the "narrower" type is |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 254 | widened to that of the other, where integer is narrower than floating point, |
| 255 | which is narrower than complex. Comparisons between numbers of mixed type use |
| 256 | the same rule. [#]_ The constructors :func:`int`, :func:`float`, and |
| 257 | :func:`complex` can be used to produce numbers of a specific type. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 258 | |
| 259 | All numeric types (except complex) support the following operations, sorted by |
| 260 | ascending priority (operations in the same box have the same priority; all |
| 261 | numeric operations have a higher priority than comparison operations): |
| 262 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 263 | +---------------------+---------------------------------+-------+--------------------+ |
| 264 | | Operation | Result | Notes | Full documentation | |
Neal Norwitz | 1d2aef5 | 2007-10-02 07:26:14 +0000 | [diff] [blame] | 265 | +=====================+=================================+=======+====================+ |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 266 | | ``x + y`` | sum of *x* and *y* | | | |
| 267 | +---------------------+---------------------------------+-------+--------------------+ |
| 268 | | ``x - y`` | difference of *x* and *y* | | | |
| 269 | +---------------------+---------------------------------+-------+--------------------+ |
| 270 | | ``x * y`` | product of *x* and *y* | | | |
| 271 | +---------------------+---------------------------------+-------+--------------------+ |
| 272 | | ``x / y`` | quotient of *x* and *y* | | | |
| 273 | +---------------------+---------------------------------+-------+--------------------+ |
| 274 | | ``x // y`` | floored quotient of *x* and | \(1) | | |
| 275 | | | *y* | | | |
| 276 | +---------------------+---------------------------------+-------+--------------------+ |
| 277 | | ``x % y`` | remainder of ``x / y`` | \(2) | | |
| 278 | +---------------------+---------------------------------+-------+--------------------+ |
| 279 | | ``-x`` | *x* negated | | | |
| 280 | +---------------------+---------------------------------+-------+--------------------+ |
| 281 | | ``+x`` | *x* unchanged | | | |
| 282 | +---------------------+---------------------------------+-------+--------------------+ |
| 283 | | ``abs(x)`` | absolute value or magnitude of | | :func:`abs` | |
| 284 | | | *x* | | | |
| 285 | +---------------------+---------------------------------+-------+--------------------+ |
| 286 | | ``int(x)`` | *x* converted to integer | \(3) | :func:`int` | |
| 287 | +---------------------+---------------------------------+-------+--------------------+ |
Georg Brandl | 74f3669 | 2008-01-06 17:39:49 +0000 | [diff] [blame] | 288 | | ``float(x)`` | *x* converted to floating point | \(4) | :func:`float` | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 289 | +---------------------+---------------------------------+-------+--------------------+ |
| 290 | | ``complex(re, im)`` | a complex number with real part | | :func:`complex` | |
| 291 | | | *re*, imaginary part *im*. | | | |
| 292 | | | *im* defaults to zero. | | | |
| 293 | +---------------------+---------------------------------+-------+--------------------+ |
| 294 | | ``c.conjugate()`` | conjugate of the complex number | | | |
| 295 | | | *c* | | | |
| 296 | +---------------------+---------------------------------+-------+--------------------+ |
| 297 | | ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | \(2) | :func:`divmod` | |
| 298 | +---------------------+---------------------------------+-------+--------------------+ |
Georg Brandl | 60fe2f1 | 2008-01-07 09:16:46 +0000 | [diff] [blame] | 299 | | ``pow(x, y)`` | *x* to the power *y* | \(5) | :func:`pow` | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 300 | +---------------------+---------------------------------+-------+--------------------+ |
Georg Brandl | 60fe2f1 | 2008-01-07 09:16:46 +0000 | [diff] [blame] | 301 | | ``x ** y`` | *x* to the power *y* | \(5) | | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 302 | +---------------------+---------------------------------+-------+--------------------+ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 303 | |
| 304 | .. index:: |
| 305 | triple: operations on; numeric; types |
| 306 | single: conjugate() (complex number method) |
| 307 | |
| 308 | Notes: |
| 309 | |
| 310 | (1) |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 311 | Also referred to as integer division. The resultant value is a whole |
| 312 | integer, though the result's type is not necessarily int. The result is |
| 313 | always rounded towards minus infinity: ``1//2`` is ``0``, ``(-1)//2`` is |
| 314 | ``-1``, ``1//(-2)`` is ``-1``, and ``(-1)//(-2)`` is ``0``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 315 | |
| 316 | (2) |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 317 | Not for complex numbers. Instead convert to floats using :func:`abs` if |
| 318 | appropriate. |
| 319 | |
| 320 | (3) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 321 | .. index:: |
| 322 | module: math |
| 323 | single: floor() (in module math) |
| 324 | single: ceil() (in module math) |
| 325 | pair: numeric; conversions |
| 326 | pair: C; language |
| 327 | |
Georg Brandl | ba956ae | 2007-11-29 17:24:34 +0000 | [diff] [blame] | 328 | Conversion from floating point to integer may round or truncate |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 329 | as in C; see functions :func:`floor` and :func:`ceil` in the :mod:`math` module |
| 330 | for well-defined conversions. |
| 331 | |
Georg Brandl | 74f3669 | 2008-01-06 17:39:49 +0000 | [diff] [blame] | 332 | (4) |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 333 | float also accepts the strings "nan" and "inf" with an optional prefix "+" |
| 334 | or "-" for Not a Number (NaN) and positive or negative infinity. |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 335 | |
Georg Brandl | 74f3669 | 2008-01-06 17:39:49 +0000 | [diff] [blame] | 336 | (5) |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 337 | Python defines ``pow(0, 0)`` and ``0 ** 0`` to be ``1``, as is common for |
| 338 | programming languages. |
| 339 | |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 340 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 341 | |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 342 | All :class:`numbers.Real` types (:class:`int` and |
| 343 | :class:`float`) also include the following operations: |
| 344 | |
| 345 | +--------------------+--------------------------------+--------+ |
| 346 | | Operation | Result | Notes | |
| 347 | +====================+================================+========+ |
| 348 | | ``trunc(x)`` | *x* truncated to Integral | | |
| 349 | +--------------------+--------------------------------+--------+ |
| 350 | | ``round(x[, n])`` | *x* rounded to n digits, | | |
| 351 | | | rounding half to even. If n is | | |
| 352 | | | omitted, it defaults to 0. | | |
| 353 | +--------------------+--------------------------------+--------+ |
| 354 | | ``math.floor(x)`` | the greatest Integral <= *x* | | |
| 355 | +--------------------+--------------------------------+--------+ |
| 356 | | ``math.ceil(x)`` | the least Integral >= *x* | | |
| 357 | +--------------------+--------------------------------+--------+ |
| 358 | |
Mark Summerfield | bbfd71d | 2008-07-01 15:50:04 +0000 | [diff] [blame] | 359 | For additional numeric operations see the :mod:`math` and :mod:`cmath` |
| 360 | modules. |
| 361 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 362 | .. XXXJH exceptions: overflow (when? what operations?) zerodivision |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 363 | |
| 364 | |
| 365 | .. _bitstring-ops: |
| 366 | |
| 367 | Bit-string Operations on Integer Types |
| 368 | -------------------------------------- |
| 369 | |
| 370 | .. _bit-string-operations: |
| 371 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 372 | Integers support additional operations that make sense only for bit-strings. |
| 373 | Negative numbers are treated as their 2's complement value (this assumes a |
| 374 | sufficiently large number of bits that no overflow occurs during the operation). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 375 | |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 376 | 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] | 377 | operations and higher than the comparisons; the unary operation ``~`` has the |
| 378 | same priority as the other unary numeric operations (``+`` and ``-``). |
| 379 | |
| 380 | This table lists the bit-string operations sorted in ascending priority |
| 381 | (operations in the same box have the same priority): |
| 382 | |
| 383 | +------------+--------------------------------+----------+ |
| 384 | | Operation | Result | Notes | |
| 385 | +============+================================+==========+ |
| 386 | | ``x | y`` | bitwise :dfn:`or` of *x* and | | |
| 387 | | | *y* | | |
| 388 | +------------+--------------------------------+----------+ |
| 389 | | ``x ^ y`` | bitwise :dfn:`exclusive or` of | | |
| 390 | | | *x* and *y* | | |
| 391 | +------------+--------------------------------+----------+ |
| 392 | | ``x & y`` | bitwise :dfn:`and` of *x* and | | |
| 393 | | | *y* | | |
| 394 | +------------+--------------------------------+----------+ |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 395 | | ``x << n`` | *x* shifted left by *n* bits | (1)(2) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 396 | +------------+--------------------------------+----------+ |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 397 | | ``x >> n`` | *x* shifted right by *n* bits | (1)(3) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 398 | +------------+--------------------------------+----------+ |
| 399 | | ``~x`` | the bits of *x* inverted | | |
| 400 | +------------+--------------------------------+----------+ |
| 401 | |
| 402 | .. index:: |
| 403 | triple: operations on; integer; types |
| 404 | pair: bit-string; operations |
| 405 | pair: shifting; operations |
| 406 | pair: masking; operations |
| 407 | |
| 408 | Notes: |
| 409 | |
| 410 | (1) |
| 411 | Negative shift counts are illegal and cause a :exc:`ValueError` to be raised. |
| 412 | |
| 413 | (2) |
| 414 | A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)`` |
| 415 | without overflow check. |
| 416 | |
| 417 | (3) |
| 418 | A right shift by *n* bits is equivalent to division by ``pow(2, n)`` without |
| 419 | overflow check. |
| 420 | |
| 421 | |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame^] | 422 | Additional Methods on Integer Types |
| 423 | ----------------------------------- |
| 424 | |
| 425 | .. method:: int.bit_length() |
| 426 | |
| 427 | For any integer ``x``, ``x.bit_length()`` returns the number of |
| 428 | bits necessary to represent ``x`` in binary, excluding the sign |
| 429 | and any leading zeros:: |
| 430 | |
| 431 | >>> n = 37 |
| 432 | >>> bin(n) |
| 433 | '0b100101' |
| 434 | >>> n.bit_length() |
| 435 | 6 |
| 436 | >>> n = -0b00011010 |
| 437 | >>> n.bit_length() |
| 438 | 5 |
| 439 | |
| 440 | More precisely, if ``x`` is nonzero then ``x.bit_length()`` is the |
| 441 | unique positive integer ``k`` such that ``2**(k-1) <= abs(x) < |
| 442 | 2**k``. Equivalently, ``x.bit_length()`` is equal to ``1 + |
| 443 | floor(log(x, 2))`` [#]_ . If ``x`` is zero then ``x.bit_length()`` |
| 444 | gives ``0``. |
| 445 | |
| 446 | Equivalent to:: |
| 447 | |
| 448 | def bit_length(self): |
| 449 | 'Number of bits necessary to represent self in binary.' |
| 450 | return len(bin(self).lstrip('-0b')) |
| 451 | |
| 452 | |
| 453 | .. versionadded:: 3.1 |
| 454 | |
| 455 | |
Mark Dickinson | 65fe25e | 2008-07-16 11:30:51 +0000 | [diff] [blame] | 456 | Additional Methods on Float |
| 457 | --------------------------- |
| 458 | |
Benjamin Peterson | d7b0328 | 2008-09-13 15:58:53 +0000 | [diff] [blame] | 459 | The float type has some additional methods. |
| 460 | |
| 461 | .. method:: float.as_integer_ratio() |
| 462 | |
| 463 | Return a pair of integers whose ratio is exactly equal to the |
| 464 | original float and with a positive denominator. Raises |
| 465 | :exc:`OverflowError` on infinities and a :exc:`ValueError` on |
| 466 | NaNs. |
| 467 | |
| 468 | .. versionadded:: 2.6 |
| 469 | |
| 470 | Two methods support conversion to |
Mark Dickinson | 65fe25e | 2008-07-16 11:30:51 +0000 | [diff] [blame] | 471 | and from hexadecimal strings. Since Python's floats are stored |
| 472 | internally as binary numbers, converting a float to or from a |
| 473 | *decimal* string usually involves a small rounding error. In |
| 474 | contrast, hexadecimal strings allow exact representation and |
| 475 | specification of floating-point numbers. This can be useful when |
| 476 | debugging, and in numerical work. |
| 477 | |
| 478 | |
| 479 | .. method:: float.hex() |
| 480 | |
| 481 | Return a representation of a floating-point number as a hexadecimal |
| 482 | string. For finite floating-point numbers, this representation |
| 483 | will always include a leading ``0x`` and a trailing ``p`` and |
| 484 | exponent. |
| 485 | |
| 486 | |
| 487 | .. method:: float.fromhex(s) |
| 488 | |
| 489 | Class method to return the float represented by a hexadecimal |
| 490 | string *s*. The string *s* may have leading and trailing |
| 491 | whitespace. |
| 492 | |
| 493 | |
| 494 | Note that :meth:`float.hex` is an instance method, while |
| 495 | :meth:`float.fromhex` is a class method. |
| 496 | |
| 497 | A hexadecimal string takes the form:: |
| 498 | |
| 499 | [sign] ['0x'] integer ['.' fraction] ['p' exponent] |
| 500 | |
| 501 | where the optional ``sign`` may by either ``+`` or ``-``, ``integer`` |
| 502 | and ``fraction`` are strings of hexadecimal digits, and ``exponent`` |
| 503 | is a decimal integer with an optional leading sign. Case is not |
| 504 | significant, and there must be at least one hexadecimal digit in |
| 505 | either the integer or the fraction. This syntax is similar to the |
| 506 | syntax specified in section 6.4.4.2 of the C99 standard, and also to |
| 507 | the syntax used in Java 1.5 onwards. In particular, the output of |
| 508 | :meth:`float.hex` is usable as a hexadecimal floating-point literal in |
| 509 | C or Java code, and hexadecimal strings produced by C's ``%a`` format |
| 510 | character or Java's ``Double.toHexString`` are accepted by |
| 511 | :meth:`float.fromhex`. |
| 512 | |
| 513 | |
| 514 | Note that the exponent is written in decimal rather than hexadecimal, |
| 515 | and that it gives the power of 2 by which to multiply the coefficient. |
| 516 | For example, the hexadecimal string ``0x3.a7p10`` represents the |
| 517 | floating-point number ``(3 + 10./16 + 7./16**2) * 2.0**10``, or |
| 518 | ``3740.0``:: |
| 519 | |
| 520 | >>> float.fromhex('0x3.a7p10') |
| 521 | 3740.0 |
| 522 | |
| 523 | |
| 524 | Applying the reverse conversion to ``3740.0`` gives a different |
| 525 | hexadecimal string representing the same number:: |
| 526 | |
| 527 | >>> float.hex(3740.0) |
| 528 | '0x1.d380000000000p+11' |
| 529 | |
| 530 | |
Georg Brandl | 6ea420b | 2008-07-16 12:58:29 +0000 | [diff] [blame] | 531 | .. _typeiter: |
| 532 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 533 | Iterator Types |
| 534 | ============== |
| 535 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 536 | .. index:: |
| 537 | single: iterator protocol |
| 538 | single: protocol; iterator |
| 539 | single: sequence; iteration |
| 540 | single: container; iteration over |
| 541 | |
| 542 | Python supports a concept of iteration over containers. This is implemented |
| 543 | using two distinct methods; these are used to allow user-defined classes to |
| 544 | support iteration. Sequences, described below in more detail, always support |
| 545 | the iteration methods. |
| 546 | |
| 547 | One method needs to be defined for container objects to provide iteration |
| 548 | support: |
| 549 | |
Christian Heimes | 790c823 | 2008-01-07 21:14:23 +0000 | [diff] [blame] | 550 | .. XXX duplicated in reference/datamodel! |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 551 | |
Christian Heimes | 790c823 | 2008-01-07 21:14:23 +0000 | [diff] [blame] | 552 | .. method:: container.__iter__() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 553 | |
| 554 | Return an iterator object. The object is required to support the iterator |
| 555 | protocol described below. If a container supports different types of |
| 556 | iteration, additional methods can be provided to specifically request |
| 557 | iterators for those iteration types. (An example of an object supporting |
| 558 | multiple forms of iteration would be a tree structure which supports both |
| 559 | breadth-first and depth-first traversal.) This method corresponds to the |
| 560 | :attr:`tp_iter` slot of the type structure for Python objects in the Python/C |
| 561 | API. |
| 562 | |
| 563 | The iterator objects themselves are required to support the following two |
| 564 | methods, which together form the :dfn:`iterator protocol`: |
| 565 | |
| 566 | |
| 567 | .. method:: iterator.__iter__() |
| 568 | |
| 569 | Return the iterator object itself. This is required to allow both containers |
| 570 | and iterators to be used with the :keyword:`for` and :keyword:`in` statements. |
| 571 | This method corresponds to the :attr:`tp_iter` slot of the type structure for |
| 572 | Python objects in the Python/C API. |
| 573 | |
| 574 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 575 | .. method:: iterator.__next__() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 576 | |
| 577 | Return the next item from the container. If there are no further items, raise |
| 578 | the :exc:`StopIteration` exception. This method corresponds to the |
| 579 | :attr:`tp_iternext` slot of the type structure for Python objects in the |
| 580 | Python/C API. |
| 581 | |
| 582 | Python defines several iterator objects to support iteration over general and |
| 583 | specific sequence types, dictionaries, and other more specialized forms. The |
| 584 | specific types are not important beyond their implementation of the iterator |
| 585 | protocol. |
| 586 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 587 | Once an iterator's :meth:`__next__` method raises :exc:`StopIteration`, it must |
| 588 | continue to do so on subsequent calls. Implementations that do not obey this |
| 589 | property are deemed broken. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 590 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 591 | Python's :term:`generator`\s provide a convenient way to implement the iterator |
| 592 | protocol. If a container object's :meth:`__iter__` method is implemented as a |
| 593 | generator, it will automatically return an iterator object (technically, a |
| 594 | generator object) supplying the :meth:`__iter__` and :meth:`__next__` methods. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 595 | |
| 596 | |
| 597 | .. _typesseq: |
| 598 | |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 599 | Sequence Types --- :class:`str`, :class:`bytes`, :class:`bytearray`, :class:`list`, :class:`tuple`, :class:`range` |
| 600 | ================================================================================================================== |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 601 | |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 602 | There are five sequence types: strings, byte sequences, byte arrays, lists, |
| 603 | tuples, and range objects. (For other containers see the built-in |
| 604 | :class:`dict`, :class:`list`, :class:`set`, and :class:`tuple` classes, and the |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 605 | :mod:`collections` module.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 606 | |
| 607 | .. index:: |
| 608 | object: sequence |
| 609 | object: string |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 610 | object: bytes |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 611 | object: buffer |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 612 | object: tuple |
| 613 | object: list |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 614 | object: range |
| 615 | |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 616 | Strings contain Unicode characters. Their literals are written in single or |
| 617 | double quotes: ``'xyzzy'``, ``"frobozz"``. See :ref:`strings` for more about |
| 618 | string literals. In addition to the functionality described here, there are |
| 619 | also string-specific methods described in the :ref:`string-methods` section. |
| 620 | |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 621 | Bytes and bytearray objects contain single bytes -- the former is immutable |
Georg Brandl | 18da8f0 | 2008-07-01 20:08:02 +0000 | [diff] [blame] | 622 | while the latter is a mutable sequence. Bytes objects can be constructed the |
| 623 | constructor, :func:`bytes`, and from literals; use a ``b`` prefix with normal |
| 624 | string syntax: ``b'xyzzy'``. To construct byte arrays, use the |
| 625 | :func:`bytearray` function. |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 626 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 627 | .. warning:: |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 628 | |
| 629 | While string objects are sequences of characters (represented by strings of |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 630 | length 1), bytes and bytearray objects are sequences of *integers* (between 0 |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 631 | and 255), representing the ASCII value of single bytes. That means that for |
Georg Brandl | 18da8f0 | 2008-07-01 20:08:02 +0000 | [diff] [blame] | 632 | a bytes or bytearray object *b*, ``b[0]`` will be an integer, while |
| 633 | ``b[0:1]`` will be a bytes or bytearray object of length 1. The |
| 634 | representation of bytes objects uses the literal format (``b'...'``) since it |
| 635 | is generally more useful than e.g. ``bytes([50, 19, 100])``. You can always |
| 636 | convert a bytes object into a list of integers using ``list(b)``. |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 637 | |
Georg Brandl | 2326a79 | 2007-09-01 12:08:51 +0000 | [diff] [blame] | 638 | Also, while in previous Python versions, byte strings and Unicode strings |
| 639 | could be exchanged for each other rather freely (barring encoding issues), |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 640 | strings and bytes are now completely separate concepts. There's no implicit |
| 641 | en-/decoding if you pass and object of the wrong type. A string always |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 642 | compares unequal to a bytes or bytearray object. |
Georg Brandl | 2326a79 | 2007-09-01 12:08:51 +0000 | [diff] [blame] | 643 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 644 | Lists are constructed with square brackets, separating items with commas: ``[a, |
| 645 | b, c]``. Tuples are constructed by the comma operator (not within square |
| 646 | brackets), with or without enclosing parentheses, but an empty tuple must have |
| 647 | the enclosing parentheses, such as ``a, b, c`` or ``()``. A single item tuple |
| 648 | must have a trailing comma, such as ``(d,)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 649 | |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 650 | Objects of type range are created using the :func:`range` function. They don't |
| 651 | support slicing, concatenation or repetition, and using ``in``, ``not in``, |
| 652 | :func:`min` or :func:`max` on them is inefficient. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 653 | |
| 654 | Most sequence types support the following operations. The ``in`` and ``not in`` |
| 655 | operations have the same priorities as the comparison operations. The ``+`` and |
| 656 | ``*`` operations have the same priority as the corresponding numeric operations. |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 657 | [#]_ Additional methods are provided for :ref:`typesseq-mutable`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 658 | |
| 659 | This table lists the sequence operations sorted in ascending priority |
| 660 | (operations in the same box have the same priority). In the table, *s* and *t* |
| 661 | are sequences of the same type; *n*, *i* and *j* are integers: |
| 662 | |
| 663 | +------------------+--------------------------------+----------+ |
| 664 | | Operation | Result | Notes | |
| 665 | +==================+================================+==========+ |
| 666 | | ``x in s`` | ``True`` if an item of *s* is | \(1) | |
| 667 | | | equal to *x*, else ``False`` | | |
| 668 | +------------------+--------------------------------+----------+ |
| 669 | | ``x not in s`` | ``False`` if an item of *s* is | \(1) | |
| 670 | | | equal to *x*, else ``True`` | | |
| 671 | +------------------+--------------------------------+----------+ |
| 672 | | ``s + t`` | the concatenation of *s* and | \(6) | |
| 673 | | | *t* | | |
| 674 | +------------------+--------------------------------+----------+ |
| 675 | | ``s * n, n * s`` | *n* shallow copies of *s* | \(2) | |
| 676 | | | concatenated | | |
| 677 | +------------------+--------------------------------+----------+ |
| 678 | | ``s[i]`` | *i*'th item of *s*, origin 0 | \(3) | |
| 679 | +------------------+--------------------------------+----------+ |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 680 | | ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 681 | +------------------+--------------------------------+----------+ |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 682 | | ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 683 | | | with step *k* | | |
| 684 | +------------------+--------------------------------+----------+ |
| 685 | | ``len(s)`` | length of *s* | | |
| 686 | +------------------+--------------------------------+----------+ |
| 687 | | ``min(s)`` | smallest item of *s* | | |
| 688 | +------------------+--------------------------------+----------+ |
| 689 | | ``max(s)`` | largest item of *s* | | |
| 690 | +------------------+--------------------------------+----------+ |
| 691 | |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 692 | Sequence types also support comparisons. In particular, tuples and lists are |
| 693 | compared lexicographically by comparing corresponding elements. This means that |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 694 | to compare equal, every element must compare equal and the two sequences must be |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 695 | of the same type and have the same length. (For full details see |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 696 | :ref:`comparisons` in the language reference.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 697 | |
| 698 | .. index:: |
| 699 | triple: operations on; sequence; types |
| 700 | builtin: len |
| 701 | builtin: min |
| 702 | builtin: max |
| 703 | pair: concatenation; operation |
| 704 | pair: repetition; operation |
| 705 | pair: subscript; operation |
| 706 | pair: slice; operation |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 707 | operator: in |
| 708 | operator: not in |
| 709 | |
| 710 | Notes: |
| 711 | |
| 712 | (1) |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 713 | When *s* is a string object, the ``in`` and ``not in`` operations act like a |
| 714 | substring test. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 715 | |
| 716 | (2) |
| 717 | Values of *n* less than ``0`` are treated as ``0`` (which yields an empty |
| 718 | sequence of the same type as *s*). Note also that the copies are shallow; |
| 719 | nested structures are not copied. This often haunts new Python programmers; |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 720 | consider: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 721 | |
| 722 | >>> lists = [[]] * 3 |
| 723 | >>> lists |
| 724 | [[], [], []] |
| 725 | >>> lists[0].append(3) |
| 726 | >>> lists |
| 727 | [[3], [3], [3]] |
| 728 | |
| 729 | What has happened is that ``[[]]`` is a one-element list containing an empty |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 730 | list, so all three elements of ``[[]] * 3`` are (pointers to) this single empty |
| 731 | list. Modifying any of the elements of ``lists`` modifies this single list. |
| 732 | You can create a list of different lists this way: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 733 | |
| 734 | >>> lists = [[] for i in range(3)] |
| 735 | >>> lists[0].append(3) |
| 736 | >>> lists[1].append(5) |
| 737 | >>> lists[2].append(7) |
| 738 | >>> lists |
| 739 | [[3], [5], [7]] |
| 740 | |
| 741 | (3) |
| 742 | If *i* or *j* is negative, the index is relative to the end of the string: |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 743 | ``len(s) + i`` or ``len(s) + j`` is substituted. But note that ``-0`` is |
| 744 | still ``0``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 745 | |
| 746 | (4) |
| 747 | The slice of *s* from *i* to *j* is defined as the sequence of items with index |
| 748 | *k* such that ``i <= k < j``. If *i* or *j* is greater than ``len(s)``, use |
| 749 | ``len(s)``. If *i* is omitted or ``None``, use ``0``. If *j* is omitted or |
| 750 | ``None``, use ``len(s)``. If *i* is greater than or equal to *j*, the slice is |
| 751 | empty. |
| 752 | |
| 753 | (5) |
| 754 | 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] | 755 | 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] | 756 | the indices are ``i``, ``i+k``, ``i+2*k``, ``i+3*k`` and so on, stopping when |
| 757 | *j* is reached (but never including *j*). If *i* or *j* is greater than |
| 758 | ``len(s)``, use ``len(s)``. If *i* or *j* are omitted or ``None``, they become |
| 759 | "end" values (which end depends on the sign of *k*). Note, *k* cannot be zero. |
| 760 | If *k* is ``None``, it is treated like ``1``. |
| 761 | |
| 762 | (6) |
| 763 | If *s* and *t* are both strings, some Python implementations such as CPython can |
| 764 | usually perform an in-place optimization for assignments of the form ``s=s+t`` |
| 765 | or ``s+=t``. When applicable, this optimization makes quadratic run-time much |
| 766 | less likely. This optimization is both version and implementation dependent. |
| 767 | For performance sensitive code, it is preferable to use the :meth:`str.join` |
| 768 | method which assures consistent linear concatenation performance across versions |
| 769 | and implementations. |
| 770 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 771 | |
| 772 | .. _string-methods: |
| 773 | |
| 774 | String Methods |
| 775 | -------------- |
| 776 | |
| 777 | .. index:: pair: string; methods |
| 778 | |
Thomas Wouters | 8ce81f7 | 2007-09-20 18:22:40 +0000 | [diff] [blame] | 779 | String objects support the methods listed below. Note that none of these |
| 780 | methods take keyword arguments. |
| 781 | |
| 782 | In addition, Python's strings support the sequence type methods described in |
| 783 | the :ref:`typesseq` section. To output formatted strings, see the |
| 784 | :ref:`string-formatting` section. Also, see the :mod:`re` module for string |
| 785 | functions based on regular expressions. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 786 | |
| 787 | .. method:: str.capitalize() |
| 788 | |
| 789 | Return a copy of the string with only its first character capitalized. |
| 790 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 791 | |
| 792 | .. method:: str.center(width[, fillchar]) |
| 793 | |
| 794 | Return centered in a string of length *width*. Padding is done using the |
| 795 | specified *fillchar* (default is a space). |
| 796 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 797 | |
| 798 | .. method:: str.count(sub[, start[, end]]) |
| 799 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 800 | Return the number of occurrences of substring *sub* in the range [*start*, |
| 801 | *end*]. Optional arguments *start* and *end* are interpreted as in slice |
| 802 | notation. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 803 | |
| 804 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 805 | .. method:: str.encode([encoding[, errors]]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 806 | |
| 807 | Return an encoded version of the string. Default encoding is the current |
| 808 | default string encoding. *errors* may be given to set a different error |
| 809 | handling scheme. The default for *errors* is ``'strict'``, meaning that |
| 810 | encoding errors raise a :exc:`UnicodeError`. Other possible values are |
| 811 | ``'ignore'``, ``'replace'``, ``'xmlcharrefreplace'``, ``'backslashreplace'`` and |
| 812 | any other name registered via :func:`codecs.register_error`, see section |
| 813 | :ref:`codec-base-classes`. For a list of possible encodings, see section |
| 814 | :ref:`standard-encodings`. |
| 815 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 816 | |
| 817 | .. method:: str.endswith(suffix[, start[, end]]) |
| 818 | |
| 819 | Return ``True`` if the string ends with the specified *suffix*, otherwise return |
| 820 | ``False``. *suffix* can also be a tuple of suffixes to look for. With optional |
| 821 | *start*, test beginning at that position. With optional *end*, stop comparing |
| 822 | at that position. |
| 823 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 824 | |
| 825 | .. method:: str.expandtabs([tabsize]) |
| 826 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 827 | Return a copy of the string where all tab characters are replaced by one or |
| 828 | more spaces, depending on the current column and the given tab size. The |
| 829 | column number is reset to zero after each newline occurring in the string. |
| 830 | If *tabsize* is not given, a tab size of ``8`` characters is assumed. This |
| 831 | doesn't understand other non-printing characters or escape sequences. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 832 | |
| 833 | |
| 834 | .. method:: str.find(sub[, start[, end]]) |
| 835 | |
| 836 | Return the lowest index in the string where substring *sub* is found, such that |
| 837 | *sub* is contained in the range [*start*, *end*]. Optional arguments *start* |
| 838 | and *end* are interpreted as in slice notation. Return ``-1`` if *sub* is not |
| 839 | found. |
| 840 | |
| 841 | |
Georg Brandl | 1c502b5 | 2008-05-12 16:50:12 +0000 | [diff] [blame] | 842 | .. method:: str.format(format_string, *args, **kwargs) |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 843 | |
| 844 | Perform a string formatting operation. The *format_string* argument can |
| 845 | contain literal text or replacement fields delimited by braces ``{}``. Each |
| 846 | replacement field contains either the numeric index of a positional argument, |
| 847 | or the name of a keyword argument. Returns a copy of *format_string* where |
| 848 | each replacement field is replaced with the string value of the corresponding |
| 849 | argument. |
| 850 | |
| 851 | >>> "The sum of 1 + 2 is {0}".format(1+2) |
| 852 | 'The sum of 1 + 2 is 3' |
| 853 | |
| 854 | See :ref:`formatstrings` for a description of the various formatting options |
| 855 | that can be specified in format strings. |
| 856 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 857 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 858 | .. method:: str.index(sub[, start[, end]]) |
| 859 | |
| 860 | Like :meth:`find`, but raise :exc:`ValueError` when the substring is not found. |
| 861 | |
| 862 | |
| 863 | .. method:: str.isalnum() |
| 864 | |
| 865 | Return true if all characters in the string are alphanumeric and there is at |
| 866 | least one character, false otherwise. |
| 867 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 868 | |
| 869 | .. method:: str.isalpha() |
| 870 | |
| 871 | Return true if all characters in the string are alphabetic and there is at least |
| 872 | one character, false otherwise. |
| 873 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 874 | |
Mark Summerfield | bbfd71d | 2008-07-01 15:50:04 +0000 | [diff] [blame] | 875 | .. method:: str.isdecimal() |
| 876 | |
| 877 | Return true if all characters in the string are decimal |
| 878 | characters and there is at least one character, false |
| 879 | otherwise. Decimal characters include digit characters, and all characters |
| 880 | that that can be used to form decimal-radix numbers, e.g. U+0660, |
| 881 | ARABIC-INDIC DIGIT ZERO. |
| 882 | |
| 883 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 884 | .. method:: str.isdigit() |
| 885 | |
| 886 | Return true if all characters in the string are digits and there is at least one |
| 887 | character, false otherwise. |
| 888 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 889 | |
| 890 | .. method:: str.isidentifier() |
| 891 | |
| 892 | 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] | 893 | definition, section :ref:`identifiers`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 894 | |
| 895 | |
| 896 | .. method:: str.islower() |
| 897 | |
| 898 | Return true if all cased characters in the string are lowercase and there is at |
| 899 | least one cased character, false otherwise. |
| 900 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 901 | |
Mark Summerfield | bbfd71d | 2008-07-01 15:50:04 +0000 | [diff] [blame] | 902 | .. method:: str.isnumeric() |
| 903 | |
| 904 | Return true if all characters in the string are numeric |
| 905 | characters, and there is at least one character, false |
| 906 | otherwise. Numeric characters include digit characters, and all characters |
| 907 | that have the Unicode numeric value property, e.g. U+2155, |
| 908 | VULGAR FRACTION ONE FIFTH. |
| 909 | |
| 910 | |
Georg Brandl | 559e5d7 | 2008-06-11 18:37:52 +0000 | [diff] [blame] | 911 | .. method:: str.isprintable() |
| 912 | |
| 913 | Return true if all characters in the string are printable or the string is |
| 914 | empty, false otherwise. Nonprintable characters are those characters defined |
| 915 | in the Unicode character database as "Other" or "Separator", excepting the |
| 916 | ASCII space (0x20) which is considered printable. (Note that printable |
| 917 | characters in this context are those which should not be escaped when |
| 918 | :func:`repr` is invoked on a string. It has no bearing on the handling of |
| 919 | strings written to :data:`sys.stdout` or :data:`sys.stderr`.) |
| 920 | |
| 921 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 922 | .. method:: str.isspace() |
| 923 | |
| 924 | Return true if there are only whitespace characters in the string and there is |
| 925 | at least one character, false otherwise. |
| 926 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 927 | |
| 928 | .. method:: str.istitle() |
| 929 | |
| 930 | Return true if the string is a titlecased string and there is at least one |
| 931 | character, for example uppercase characters may only follow uncased characters |
| 932 | and lowercase characters only cased ones. Return false otherwise. |
| 933 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 934 | |
| 935 | .. method:: str.isupper() |
| 936 | |
| 937 | Return true if all cased characters in the string are uppercase and there is at |
| 938 | least one cased character, false otherwise. |
| 939 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 940 | |
| 941 | .. method:: str.join(seq) |
| 942 | |
Georg Brandl | 07431a3 | 2008-08-02 16:34:27 +0000 | [diff] [blame] | 943 | Return a string which is the concatenation of the strings in the sequence |
| 944 | *seq*. A :exc:`TypeError` will be raised if there are any non-string values |
| 945 | in *seq*, including :class:`bytes` objects. The separator between elements |
| 946 | is the string providing this method. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 947 | |
| 948 | |
| 949 | .. method:: str.ljust(width[, fillchar]) |
| 950 | |
| 951 | Return the string left justified in a string of length *width*. Padding is done |
| 952 | using the specified *fillchar* (default is a space). The original string is |
| 953 | returned if *width* is less than ``len(s)``. |
| 954 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 955 | |
| 956 | .. method:: str.lower() |
| 957 | |
| 958 | Return a copy of the string converted to lowercase. |
| 959 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 960 | |
| 961 | .. method:: str.lstrip([chars]) |
| 962 | |
| 963 | Return a copy of the string with leading characters removed. The *chars* |
| 964 | argument is a string specifying the set of characters to be removed. If omitted |
| 965 | or ``None``, the *chars* argument defaults to removing whitespace. The *chars* |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 966 | 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] | 967 | |
| 968 | >>> ' spacious '.lstrip() |
| 969 | 'spacious ' |
| 970 | >>> 'www.example.com'.lstrip('cmowz.') |
| 971 | 'example.com' |
| 972 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 973 | |
Georg Brandl | ceee077 | 2007-11-27 23:48:05 +0000 | [diff] [blame] | 974 | .. method:: str.maketrans(x[, y[, z]]) |
| 975 | |
| 976 | This static method returns a translation table usable for :meth:`str.translate`. |
| 977 | |
| 978 | If there is only one argument, it must be a dictionary mapping Unicode |
| 979 | ordinals (integers) or characters (strings of length 1) to Unicode ordinals, |
| 980 | strings (of arbitrary lengths) or None. Character keys will then be |
| 981 | converted to ordinals. |
| 982 | |
| 983 | If there are two arguments, they must be strings of equal length, and in the |
| 984 | resulting dictionary, each character in x will be mapped to the character at |
| 985 | the same position in y. If there is a third argument, it must be a string, |
| 986 | whose characters will be mapped to None in the result. |
| 987 | |
| 988 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 989 | .. method:: str.partition(sep) |
| 990 | |
| 991 | Split the string at the first occurrence of *sep*, and return a 3-tuple |
| 992 | containing the part before the separator, the separator itself, and the part |
| 993 | after the separator. If the separator is not found, return a 3-tuple containing |
| 994 | the string itself, followed by two empty strings. |
| 995 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 996 | |
| 997 | .. method:: str.replace(old, new[, count]) |
| 998 | |
| 999 | Return a copy of the string with all occurrences of substring *old* replaced by |
| 1000 | *new*. If the optional argument *count* is given, only the first *count* |
| 1001 | occurrences are replaced. |
| 1002 | |
| 1003 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1004 | .. method:: str.rfind(sub[, start[, end]]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1005 | |
| 1006 | Return the highest index in the string where substring *sub* is found, such that |
| 1007 | *sub* is contained within s[start,end]. Optional arguments *start* and *end* |
| 1008 | are interpreted as in slice notation. Return ``-1`` on failure. |
| 1009 | |
| 1010 | |
| 1011 | .. method:: str.rindex(sub[, start[, end]]) |
| 1012 | |
| 1013 | Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not |
| 1014 | found. |
| 1015 | |
| 1016 | |
| 1017 | .. method:: str.rjust(width[, fillchar]) |
| 1018 | |
| 1019 | Return the string right justified in a string of length *width*. Padding is done |
| 1020 | using the specified *fillchar* (default is a space). The original string is |
| 1021 | returned if *width* is less than ``len(s)``. |
| 1022 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1023 | |
| 1024 | .. method:: str.rpartition(sep) |
| 1025 | |
| 1026 | Split the string at the last occurrence of *sep*, and return a 3-tuple |
| 1027 | containing the part before the separator, the separator itself, and the part |
| 1028 | after the separator. If the separator is not found, return a 3-tuple containing |
| 1029 | two empty strings, followed by the string itself. |
| 1030 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1031 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1032 | .. method:: str.rsplit([sep[, maxsplit]]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1033 | |
| 1034 | Return a list of the words in the string, using *sep* as the delimiter string. |
| 1035 | If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost* |
| 1036 | ones. If *sep* is not specified or ``None``, any whitespace string is a |
| 1037 | separator. Except for splitting from the right, :meth:`rsplit` behaves like |
| 1038 | :meth:`split` which is described in detail below. |
| 1039 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1040 | |
| 1041 | .. method:: str.rstrip([chars]) |
| 1042 | |
| 1043 | Return a copy of the string with trailing characters removed. The *chars* |
| 1044 | argument is a string specifying the set of characters to be removed. If omitted |
| 1045 | or ``None``, the *chars* argument defaults to removing whitespace. The *chars* |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 1046 | 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] | 1047 | |
| 1048 | >>> ' spacious '.rstrip() |
| 1049 | ' spacious' |
| 1050 | >>> 'mississippi'.rstrip('ipz') |
| 1051 | 'mississ' |
| 1052 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1053 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1054 | .. method:: str.split([sep[, maxsplit]]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1055 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1056 | Return a list of the words in the string, using *sep* as the delimiter |
| 1057 | string. If *maxsplit* is given, at most *maxsplit* splits are done (thus, |
| 1058 | the list will have at most ``maxsplit+1`` elements). If *maxsplit* is not |
| 1059 | specified, then there is no limit on the number of splits (all possible |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 1060 | splits are made). |
| 1061 | |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 1062 | If *sep* is given, consecutive delimiters are not grouped together and are |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1063 | deemed to delimit empty strings (for example, ``'1,,2'.split(',')`` returns |
| 1064 | ``['1', '', '2']``). The *sep* argument may consist of multiple characters |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 1065 | (for example, ``'1<>2<>3'.split('<>')`` returns ``['1', '2', '3']``). |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1066 | Splitting an empty string with a specified separator returns ``['']``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1067 | |
| 1068 | 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] | 1069 | applied: runs of consecutive whitespace are regarded as a single separator, |
| 1070 | and the result will contain no empty strings at the start or end if the |
| 1071 | string has leading or trailing whitespace. Consequently, splitting an empty |
| 1072 | string or a string consisting of just whitespace with a ``None`` separator |
| 1073 | returns ``[]``. |
| 1074 | |
| 1075 | For example, ``' 1 2 3 '.split()`` returns ``['1', '2', '3']``, and |
| 1076 | ``' 1 2 3 '.split(None, 1)`` returns ``['1', '2 3 ']``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1077 | |
| 1078 | |
| 1079 | .. method:: str.splitlines([keepends]) |
| 1080 | |
| 1081 | Return a list of the lines in the string, breaking at line boundaries. Line |
| 1082 | breaks are not included in the resulting list unless *keepends* is given and |
| 1083 | true. |
| 1084 | |
| 1085 | |
| 1086 | .. method:: str.startswith(prefix[, start[, end]]) |
| 1087 | |
| 1088 | Return ``True`` if string starts with the *prefix*, otherwise return ``False``. |
| 1089 | *prefix* can also be a tuple of prefixes to look for. With optional *start*, |
| 1090 | test string beginning at that position. With optional *end*, stop comparing |
| 1091 | string at that position. |
| 1092 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1093 | |
| 1094 | .. method:: str.strip([chars]) |
| 1095 | |
| 1096 | Return a copy of the string with the leading and trailing characters removed. |
| 1097 | The *chars* argument is a string specifying the set of characters to be removed. |
| 1098 | If omitted or ``None``, the *chars* argument defaults to removing whitespace. |
| 1099 | The *chars* argument is not a prefix or suffix; rather, all combinations of its |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 1100 | values are stripped: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1101 | |
| 1102 | >>> ' spacious '.strip() |
| 1103 | 'spacious' |
| 1104 | >>> 'www.example.com'.strip('cmowz.') |
| 1105 | 'example' |
| 1106 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1107 | |
| 1108 | .. method:: str.swapcase() |
| 1109 | |
| 1110 | Return a copy of the string with uppercase characters converted to lowercase and |
| 1111 | vice versa. |
| 1112 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1113 | |
| 1114 | .. method:: str.title() |
| 1115 | |
| 1116 | Return a titlecased version of the string: words start with uppercase |
| 1117 | characters, all remaining cased characters are lowercase. |
| 1118 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1119 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1120 | .. method:: str.translate(map) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1121 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1122 | Return a copy of the *s* where all characters have been mapped through the |
Georg Brandl | ceee077 | 2007-11-27 23:48:05 +0000 | [diff] [blame] | 1123 | *map* which must be a dictionary of Unicode ordinals(integers) to Unicode |
| 1124 | ordinals, strings or ``None``. Unmapped characters are left untouched. |
| 1125 | Characters mapped to ``None`` are deleted. |
| 1126 | |
Benjamin Peterson | d9c03e0 | 2008-12-13 03:03:41 +0000 | [diff] [blame] | 1127 | You can use :meth:`str.maketrans` to create a translation table. For string |
| 1128 | objects, set the *table* argument to ``None`` for translations that only |
| 1129 | delete characters: |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 1130 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1131 | .. note:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1132 | |
Georg Brandl | ceee077 | 2007-11-27 23:48:05 +0000 | [diff] [blame] | 1133 | An even more flexible approach is to create a custom character mapping |
| 1134 | codec using the :mod:`codecs` module (see :mod:`encodings.cp1251` for an |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1135 | example). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1136 | |
| 1137 | |
| 1138 | .. method:: str.upper() |
| 1139 | |
| 1140 | Return a copy of the string converted to uppercase. |
| 1141 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1142 | |
| 1143 | .. method:: str.zfill(width) |
| 1144 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 1145 | Return the numeric string left filled with zeros in a string of length |
| 1146 | *width*. A sign prefix is handled correctly. The original string is |
| 1147 | returned if *width* is less than ``len(s)``. |
Christian Heimes | b186d00 | 2008-03-18 15:15:01 +0000 | [diff] [blame] | 1148 | |
| 1149 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1150 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1151 | .. _old-string-formatting: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1152 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1153 | Old String Formatting Operations |
| 1154 | -------------------------------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1155 | |
| 1156 | .. index:: |
| 1157 | single: formatting, string (%) |
| 1158 | single: interpolation, string (%) |
| 1159 | single: string; formatting |
| 1160 | single: string; interpolation |
| 1161 | single: printf-style formatting |
| 1162 | single: sprintf-style formatting |
| 1163 | single: % formatting |
| 1164 | single: % interpolation |
| 1165 | |
Georg Brandl | 81ac1ce | 2007-08-31 17:17:17 +0000 | [diff] [blame] | 1166 | .. XXX is the note enough? |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1167 | |
| 1168 | .. note:: |
| 1169 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1170 | The formatting operations described here are obsolete and may go away in future |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1171 | versions of Python. Use the new :ref:`string-formatting` in new code. |
| 1172 | |
| 1173 | String objects have one unique built-in operation: the ``%`` operator (modulo). |
| 1174 | This is also known as the string *formatting* or *interpolation* operator. |
| 1175 | Given ``format % values`` (where *format* is a string), ``%`` conversion |
| 1176 | specifications in *format* are replaced with zero or more elements of *values*. |
| 1177 | The effect is similar to the using :cfunc:`sprintf` in the C language. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1178 | |
| 1179 | If *format* requires a single argument, *values* may be a single non-tuple |
| 1180 | object. [#]_ Otherwise, *values* must be a tuple with exactly the number of |
| 1181 | items specified by the format string, or a single mapping object (for example, a |
| 1182 | dictionary). |
| 1183 | |
| 1184 | A conversion specifier contains two or more characters and has the following |
| 1185 | components, which must occur in this order: |
| 1186 | |
| 1187 | #. The ``'%'`` character, which marks the start of the specifier. |
| 1188 | |
| 1189 | #. Mapping key (optional), consisting of a parenthesised sequence of characters |
| 1190 | (for example, ``(somename)``). |
| 1191 | |
| 1192 | #. Conversion flags (optional), which affect the result of some conversion |
| 1193 | types. |
| 1194 | |
| 1195 | #. Minimum field width (optional). If specified as an ``'*'`` (asterisk), the |
| 1196 | actual width is read from the next element of the tuple in *values*, and the |
| 1197 | object to convert comes after the minimum field width and optional precision. |
| 1198 | |
| 1199 | #. Precision (optional), given as a ``'.'`` (dot) followed by the precision. If |
| 1200 | specified as ``'*'`` (an asterisk), the actual width is read from the next |
| 1201 | element of the tuple in *values*, and the value to convert comes after the |
| 1202 | precision. |
| 1203 | |
| 1204 | #. Length modifier (optional). |
| 1205 | |
| 1206 | #. Conversion type. |
| 1207 | |
| 1208 | When the right argument is a dictionary (or other mapping type), then the |
| 1209 | formats in the string *must* include a parenthesised mapping key into that |
| 1210 | dictionary inserted immediately after the ``'%'`` character. The mapping key |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 1211 | selects the value to be formatted from the mapping. For example: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1212 | |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 1213 | |
| 1214 | >>> print('%(language)s has %(#)03d quote types.' % \ |
| 1215 | ... {'language': "Python", "#": 2}) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1216 | Python has 002 quote types. |
| 1217 | |
| 1218 | In this case no ``*`` specifiers may occur in a format (since they require a |
| 1219 | sequential parameter list). |
| 1220 | |
| 1221 | The conversion flag characters are: |
| 1222 | |
| 1223 | +---------+---------------------------------------------------------------------+ |
| 1224 | | Flag | Meaning | |
| 1225 | +=========+=====================================================================+ |
| 1226 | | ``'#'`` | The value conversion will use the "alternate form" (where defined | |
| 1227 | | | below). | |
| 1228 | +---------+---------------------------------------------------------------------+ |
| 1229 | | ``'0'`` | The conversion will be zero padded for numeric values. | |
| 1230 | +---------+---------------------------------------------------------------------+ |
| 1231 | | ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` | |
| 1232 | | | conversion if both are given). | |
| 1233 | +---------+---------------------------------------------------------------------+ |
| 1234 | | ``' '`` | (a space) A blank should be left before a positive number (or empty | |
| 1235 | | | string) produced by a signed conversion. | |
| 1236 | +---------+---------------------------------------------------------------------+ |
| 1237 | | ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion | |
| 1238 | | | (overrides a "space" flag). | |
| 1239 | +---------+---------------------------------------------------------------------+ |
| 1240 | |
| 1241 | 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] | 1242 | 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] | 1243 | |
| 1244 | The conversion types are: |
| 1245 | |
| 1246 | +------------+-----------------------------------------------------+-------+ |
| 1247 | | Conversion | Meaning | Notes | |
| 1248 | +============+=====================================================+=======+ |
| 1249 | | ``'d'`` | Signed integer decimal. | | |
| 1250 | +------------+-----------------------------------------------------+-------+ |
| 1251 | | ``'i'`` | Signed integer decimal. | | |
| 1252 | +------------+-----------------------------------------------------+-------+ |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 1253 | | ``'o'`` | Signed octal value. | \(1) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1254 | +------------+-----------------------------------------------------+-------+ |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 1255 | | ``'u'`` | Obselete type -- it is identical to ``'d'``. | \(7) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1256 | +------------+-----------------------------------------------------+-------+ |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 1257 | | ``'x'`` | Signed hexadecimal (lowercase). | \(2) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1258 | +------------+-----------------------------------------------------+-------+ |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 1259 | | ``'X'`` | Signed hexadecimal (uppercase). | \(2) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1260 | +------------+-----------------------------------------------------+-------+ |
| 1261 | | ``'e'`` | Floating point exponential format (lowercase). | \(3) | |
| 1262 | +------------+-----------------------------------------------------+-------+ |
| 1263 | | ``'E'`` | Floating point exponential format (uppercase). | \(3) | |
| 1264 | +------------+-----------------------------------------------------+-------+ |
Eric Smith | 22b85b3 | 2008-07-17 19:18:29 +0000 | [diff] [blame] | 1265 | | ``'f'`` | Floating point decimal format. | \(3) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1266 | +------------+-----------------------------------------------------+-------+ |
Eric Smith | 22b85b3 | 2008-07-17 19:18:29 +0000 | [diff] [blame] | 1267 | | ``'F'`` | Floating point decimal format. | \(3) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1268 | +------------+-----------------------------------------------------+-------+ |
Christian Heimes | 8dc226f | 2008-05-06 23:45:46 +0000 | [diff] [blame] | 1269 | | ``'g'`` | Floating point format. Uses lowercase exponential | \(4) | |
| 1270 | | | format if exponent is less than -4 or not less than | | |
| 1271 | | | precision, decimal format otherwise. | | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1272 | +------------+-----------------------------------------------------+-------+ |
Christian Heimes | 8dc226f | 2008-05-06 23:45:46 +0000 | [diff] [blame] | 1273 | | ``'G'`` | Floating point format. Uses uppercase exponential | \(4) | |
| 1274 | | | format if exponent is less than -4 or not less than | | |
| 1275 | | | precision, decimal format otherwise. | | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1276 | +------------+-----------------------------------------------------+-------+ |
| 1277 | | ``'c'`` | Single character (accepts integer or single | | |
| 1278 | | | character string). | | |
| 1279 | +------------+-----------------------------------------------------+-------+ |
| 1280 | | ``'r'`` | String (converts any python object using | \(5) | |
| 1281 | | | :func:`repr`). | | |
| 1282 | +------------+-----------------------------------------------------+-------+ |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1283 | | ``'s'`` | String (converts any python object using | | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1284 | | | :func:`str`). | | |
| 1285 | +------------+-----------------------------------------------------+-------+ |
| 1286 | | ``'%'`` | No argument is converted, results in a ``'%'`` | | |
| 1287 | | | character in the result. | | |
| 1288 | +------------+-----------------------------------------------------+-------+ |
| 1289 | |
| 1290 | Notes: |
| 1291 | |
| 1292 | (1) |
| 1293 | The alternate form causes a leading zero (``'0'``) to be inserted between |
| 1294 | left-hand padding and the formatting of the number if the leading character |
| 1295 | of the result is not already a zero. |
| 1296 | |
| 1297 | (2) |
| 1298 | The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether |
| 1299 | the ``'x'`` or ``'X'`` format was used) to be inserted between left-hand padding |
| 1300 | and the formatting of the number if the leading character of the result is not |
| 1301 | already a zero. |
| 1302 | |
| 1303 | (3) |
| 1304 | The alternate form causes the result to always contain a decimal point, even if |
| 1305 | no digits follow it. |
| 1306 | |
| 1307 | The precision determines the number of digits after the decimal point and |
| 1308 | defaults to 6. |
| 1309 | |
| 1310 | (4) |
| 1311 | The alternate form causes the result to always contain a decimal point, and |
| 1312 | trailing zeroes are not removed as they would otherwise be. |
| 1313 | |
| 1314 | The precision determines the number of significant digits before and after the |
| 1315 | decimal point and defaults to 6. |
| 1316 | |
| 1317 | (5) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1318 | The precision determines the maximal number of characters used. |
| 1319 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1320 | |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 1321 | (7) |
| 1322 | See :pep:`237`. |
| 1323 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1324 | Since Python strings have an explicit length, ``%s`` conversions do not assume |
| 1325 | that ``'\0'`` is the end of the string. |
| 1326 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 1327 | .. XXX Examples? |
| 1328 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1329 | For safety reasons, floating point precisions are clipped to 50; ``%f`` |
| 1330 | conversions for numbers whose absolute value is over 1e25 are replaced by ``%g`` |
| 1331 | conversions. [#]_ All other errors raise exceptions. |
| 1332 | |
| 1333 | .. index:: |
| 1334 | module: string |
| 1335 | module: re |
| 1336 | |
| 1337 | Additional string operations are defined in standard modules :mod:`string` and |
| 1338 | :mod:`re`. |
| 1339 | |
| 1340 | |
| 1341 | .. _typesseq-range: |
| 1342 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 1343 | Range Type |
| 1344 | ---------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1345 | |
| 1346 | .. index:: object: range |
| 1347 | |
| 1348 | The :class:`range` type is an immutable sequence which is commonly used for |
| 1349 | looping. The advantage of the :class:`range` type is that an :class:`range` |
| 1350 | object will always take the same amount of memory, no matter the size of the |
| 1351 | range it represents. There are no consistent performance advantages. |
| 1352 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 1353 | Range objects have very little behavior: they only support indexing, iteration, |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1354 | and the :func:`len` function. |
| 1355 | |
| 1356 | |
| 1357 | .. _typesseq-mutable: |
| 1358 | |
| 1359 | Mutable Sequence Types |
| 1360 | ---------------------- |
| 1361 | |
| 1362 | .. index:: |
| 1363 | triple: mutable; sequence; types |
| 1364 | object: list |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 1365 | object: bytearray |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1366 | |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 1367 | List and bytearray objects support additional operations that allow in-place |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1368 | modification of the object. Other mutable sequence types (when added to the |
| 1369 | language) should also support these operations. Strings and tuples are |
| 1370 | immutable sequence types: such objects cannot be modified once created. The |
| 1371 | following operations are defined on mutable sequence types (where *x* is an |
| 1372 | arbitrary object). |
| 1373 | |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 1374 | Note that while lists allow their items to be of any type, bytearray object |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1375 | "items" are all integers in the range 0 <= x < 256. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1376 | |
| 1377 | +------------------------------+--------------------------------+---------------------+ |
| 1378 | | Operation | Result | Notes | |
| 1379 | +==============================+================================+=====================+ |
| 1380 | | ``s[i] = x`` | item *i* of *s* is replaced by | | |
| 1381 | | | *x* | | |
| 1382 | +------------------------------+--------------------------------+---------------------+ |
| 1383 | | ``s[i:j] = t`` | slice of *s* from *i* to *j* | | |
| 1384 | | | is replaced by the contents of | | |
| 1385 | | | the iterable *t* | | |
| 1386 | +------------------------------+--------------------------------+---------------------+ |
| 1387 | | ``del s[i:j]`` | same as ``s[i:j] = []`` | | |
| 1388 | +------------------------------+--------------------------------+---------------------+ |
| 1389 | | ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` | \(1) | |
| 1390 | | | are replaced by those of *t* | | |
| 1391 | +------------------------------+--------------------------------+---------------------+ |
| 1392 | | ``del s[i:j:k]`` | removes the elements of | | |
| 1393 | | | ``s[i:j:k]`` from the list | | |
| 1394 | +------------------------------+--------------------------------+---------------------+ |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1395 | | ``s.append(x)`` | same as ``s[len(s):len(s)] = | | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1396 | | | [x]`` | | |
| 1397 | +------------------------------+--------------------------------+---------------------+ |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1398 | | ``s.extend(x)`` | same as ``s[len(s):len(s)] = | \(2) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1399 | | | x`` | | |
| 1400 | +------------------------------+--------------------------------+---------------------+ |
| 1401 | | ``s.count(x)`` | return number of *i*'s for | | |
| 1402 | | | which ``s[i] == x`` | | |
| 1403 | +------------------------------+--------------------------------+---------------------+ |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1404 | | ``s.index(x[, i[, j]])`` | return smallest *k* such that | \(3) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1405 | | | ``s[k] == x`` and ``i <= k < | | |
| 1406 | | | j`` | | |
| 1407 | +------------------------------+--------------------------------+---------------------+ |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1408 | | ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | \(4) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1409 | +------------------------------+--------------------------------+---------------------+ |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1410 | | ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | \(5) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1411 | | | return x`` | | |
| 1412 | +------------------------------+--------------------------------+---------------------+ |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1413 | | ``s.remove(x)`` | same as ``del s[s.index(x)]`` | \(3) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1414 | +------------------------------+--------------------------------+---------------------+ |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1415 | | ``s.reverse()`` | reverses the items of *s* in | \(6) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1416 | | | place | | |
| 1417 | +------------------------------+--------------------------------+---------------------+ |
Raymond Hettinger | 7f73295 | 2008-02-14 13:34:38 +0000 | [diff] [blame] | 1418 | | ``s.sort([key[, reverse]])`` | sort the items of *s* in place | (6), (7), (8) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1419 | +------------------------------+--------------------------------+---------------------+ |
| 1420 | |
| 1421 | .. index:: |
| 1422 | triple: operations on; sequence; types |
| 1423 | triple: operations on; list; type |
| 1424 | pair: subscript; assignment |
| 1425 | pair: slice; assignment |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1426 | statement: del |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1427 | single: append() (sequence method) |
| 1428 | single: extend() (sequence method) |
| 1429 | single: count() (sequence method) |
| 1430 | single: index() (sequence method) |
| 1431 | single: insert() (sequence method) |
| 1432 | single: pop() (sequence method) |
| 1433 | single: remove() (sequence method) |
| 1434 | single: reverse() (sequence method) |
| 1435 | single: sort() (sequence method) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1436 | |
| 1437 | Notes: |
| 1438 | |
| 1439 | (1) |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1440 | *t* must have the same length as the slice it is replacing. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1441 | |
| 1442 | (2) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1443 | *x* can be any iterable object. |
| 1444 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1445 | (3) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1446 | Raises :exc:`ValueError` when *x* is not found in *s*. When a negative index is |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1447 | passed as the second or third parameter to the :meth:`index` method, the sequence |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1448 | length is added, as for slice indices. If it is still negative, it is truncated |
| 1449 | to zero, as for slice indices. |
| 1450 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1451 | (4) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1452 | When a negative index is passed as the first parameter to the :meth:`insert` |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1453 | method, the sequence length is added, as for slice indices. If it is still |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1454 | negative, it is truncated to zero, as for slice indices. |
| 1455 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1456 | (5) |
| 1457 | The optional argument *i* defaults to ``-1``, so that by default the last |
| 1458 | item is removed and returned. |
| 1459 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1460 | (6) |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1461 | The :meth:`sort` and :meth:`reverse` methods modify the sequence in place for |
| 1462 | economy of space when sorting or reversing a large sequence. To remind you |
| 1463 | that they operate by side effect, they don't return the sorted or reversed |
| 1464 | sequence. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1465 | |
| 1466 | (7) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1467 | The :meth:`sort` method takes optional arguments for controlling the |
Raymond Hettinger | 7f73295 | 2008-02-14 13:34:38 +0000 | [diff] [blame] | 1468 | comparisons. Each must be specified as a keyword argument. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1469 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1470 | *key* specifies a function of one argument that is used to extract a comparison |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 1471 | key from each list element: ``key=str.lower``. The default value is ``None``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1472 | |
| 1473 | *reverse* is a boolean value. If set to ``True``, then the list elements are |
| 1474 | sorted as if each comparison were reversed. |
| 1475 | |
Raymond Hettinger | 7116186 | 2008-02-14 13:32:18 +0000 | [diff] [blame] | 1476 | The :meth:`sort` method is guaranteed to be stable. A |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1477 | sort is stable if it guarantees not to change the relative order of elements |
| 1478 | that compare equal --- this is helpful for sorting in multiple passes (for |
| 1479 | example, sort by department, then by salary grade). |
| 1480 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1481 | While a list is being sorted, the effect of attempting to mutate, or even |
Raymond Hettinger | 7116186 | 2008-02-14 13:32:18 +0000 | [diff] [blame] | 1482 | inspect, the list is undefined. The C implementation |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1483 | makes the list appear empty for the duration, and raises :exc:`ValueError` if it |
| 1484 | can detect that the list has been mutated during a sort. |
| 1485 | |
Raymond Hettinger | 7f73295 | 2008-02-14 13:34:38 +0000 | [diff] [blame] | 1486 | (8) |
| 1487 | :meth:`sort` is not supported by :class:`bytearray` objects. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1488 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1489 | .. _bytes-methods: |
| 1490 | |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 1491 | Bytes and Byte Array Methods |
| 1492 | ---------------------------- |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1493 | |
| 1494 | .. index:: pair: bytes; methods |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 1495 | pair: bytearray; methods |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1496 | |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 1497 | Bytes and bytearray objects, being "strings of bytes", have all methods found on |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 1498 | strings, with the exception of :func:`encode`, :func:`format` and |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 1499 | :func:`isidentifier`, which do not make sense with these types. For converting |
| 1500 | the objects to strings, they have a :func:`decode` method. |
| 1501 | |
| 1502 | Wherever one of these methods needs to interpret the bytes as characters |
| 1503 | (e.g. the :func:`is...` methods), the ASCII character set is assumed. |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1504 | |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 1505 | .. note:: |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1506 | |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 1507 | 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] | 1508 | arguments, just as the methods on strings don't accept bytes as their |
| 1509 | arguments. For example, you have to write :: |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1510 | |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 1511 | a = "abc" |
| 1512 | b = a.replace("a", "f") |
| 1513 | |
| 1514 | and :: |
| 1515 | |
| 1516 | a = b"abc" |
| 1517 | b = a.replace(b"a", b"f") |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1518 | |
| 1519 | |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 1520 | The bytes and bytearray types have an additional class method: |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1521 | |
| 1522 | .. method:: bytes.fromhex(string) |
Georg Brandl | 18da8f0 | 2008-07-01 20:08:02 +0000 | [diff] [blame] | 1523 | bytearray.fromhex(string) |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1524 | |
Georg Brandl | 18da8f0 | 2008-07-01 20:08:02 +0000 | [diff] [blame] | 1525 | This :class:`bytes` class method returns a bytes or bytearray object, |
| 1526 | decoding the given string object. The string must contain two hexadecimal |
| 1527 | digits per byte, spaces are ignored. |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1528 | |
Georg Brandl | 18da8f0 | 2008-07-01 20:08:02 +0000 | [diff] [blame] | 1529 | >>> bytes.fromhex('f0 f1f2 ') |
| 1530 | b'\xf0\xf1\xf2' |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1531 | |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 1532 | .. XXX verify/document translate() semantics! |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1533 | |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 1534 | .. method:: bytes.translate(table[, delete]) |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1535 | |
| 1536 | Return a copy of the bytes object where all bytes occurring in the optional |
Georg Brandl | 7f13e6b | 2007-08-31 10:37:15 +0000 | [diff] [blame] | 1537 | argument *delete* are removed, and the remaining bytes have been mapped |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1538 | through the given translation table, which must be a bytes object of length |
| 1539 | 256. |
| 1540 | |
| 1541 | You can use the :func:`maketrans` helper function in the :mod:`string` module to |
| 1542 | create a translation table. |
| 1543 | |
| 1544 | .. XXX a None table doesn't seem to be supported |
Georg Brandl | 7f13e6b | 2007-08-31 10:37:15 +0000 | [diff] [blame] | 1545 | Set the *table* argument to ``None`` for translations that only delete characters:: |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1546 | |
| 1547 | >>> 'read this short text'.translate(None, 'aeiou') |
| 1548 | 'rd ths shrt txt' |
| 1549 | |
| 1550 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1551 | .. _types-set: |
| 1552 | |
| 1553 | Set Types --- :class:`set`, :class:`frozenset` |
| 1554 | ============================================== |
| 1555 | |
| 1556 | .. index:: object: set |
| 1557 | |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 1558 | 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] | 1559 | Common uses include membership testing, removing duplicates from a sequence, and |
| 1560 | computing mathematical operations such as intersection, union, difference, and |
| 1561 | symmetric difference. |
| 1562 | (For other containers see the built in :class:`dict`, :class:`list`, |
| 1563 | and :class:`tuple` classes, and the :mod:`collections` module.) |
| 1564 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1565 | Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in |
| 1566 | set``. Being an unordered collection, sets do not record element position or |
| 1567 | order of insertion. Accordingly, sets do not support indexing, slicing, or |
| 1568 | other sequence-like behavior. |
| 1569 | |
| 1570 | There are currently two builtin set types, :class:`set` and :class:`frozenset`. |
| 1571 | The :class:`set` type is mutable --- the contents can be changed using methods |
| 1572 | like :meth:`add` and :meth:`remove`. Since it is mutable, it has no hash value |
| 1573 | and cannot be used as either a dictionary key or as an element of another set. |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 1574 | The :class:`frozenset` type is immutable and :term:`hashable` --- its contents cannot be |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1575 | altered after it is created; it can therefore be used as a dictionary key or as |
| 1576 | an element of another set. |
| 1577 | |
| 1578 | The constructors for both classes work the same: |
| 1579 | |
| 1580 | .. class:: set([iterable]) |
| 1581 | frozenset([iterable]) |
| 1582 | |
| 1583 | Return a new set or frozenset object whose elements are taken from |
| 1584 | *iterable*. The elements of a set must be hashable. To represent sets of |
| 1585 | sets, the inner sets must be :class:`frozenset` objects. If *iterable* is |
| 1586 | not specified, a new empty set is returned. |
| 1587 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1588 | Instances of :class:`set` and :class:`frozenset` provide the following |
| 1589 | operations: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1590 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1591 | .. describe:: len(s) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1592 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1593 | Return the cardinality of set *s*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1594 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1595 | .. describe:: x in s |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1596 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1597 | Test *x* for membership in *s*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1598 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1599 | .. describe:: x not in s |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1600 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1601 | Test *x* for non-membership in *s*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1602 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1603 | .. method:: isdisjoint(other) |
Guido van Rossum | 58da931 | 2007-11-10 23:39:45 +0000 | [diff] [blame] | 1604 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1605 | 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] | 1606 | disjoint if and only if their intersection is the empty set. |
Guido van Rossum | 58da931 | 2007-11-10 23:39:45 +0000 | [diff] [blame] | 1607 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1608 | .. method:: issubset(other) |
| 1609 | set <= other |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1610 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1611 | Test whether every element in the set is in *other*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1612 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1613 | .. method:: set < other |
Georg Brandl | a6f5278 | 2007-09-01 15:49:30 +0000 | [diff] [blame] | 1614 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1615 | Test whether the set is a true subset of *other*, that is, |
| 1616 | ``set <= other and set != other``. |
Georg Brandl | a6f5278 | 2007-09-01 15:49:30 +0000 | [diff] [blame] | 1617 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1618 | .. method:: issuperset(other) |
| 1619 | set >= other |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1620 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1621 | Test whether every element in *other* is in the set. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1622 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1623 | .. method:: set > other |
Georg Brandl | a6f5278 | 2007-09-01 15:49:30 +0000 | [diff] [blame] | 1624 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1625 | Test whether the set is a true superset of *other*, that is, ``set >= |
| 1626 | other and set != other``. |
Georg Brandl | a6f5278 | 2007-09-01 15:49:30 +0000 | [diff] [blame] | 1627 | |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 1628 | .. method:: union(other, ...) |
| 1629 | set | other | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1630 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1631 | Return a new set with elements from both sets. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1632 | |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 1633 | .. method:: intersection(other, ...) |
| 1634 | set & other & ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1635 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1636 | Return a new set with elements common to both sets. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1637 | |
Amaury Forgeot d'Arc | fdfe62d | 2008-06-17 20:36:03 +0000 | [diff] [blame] | 1638 | .. method:: difference(other, ...) |
| 1639 | set - other - ... |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 1640 | |
Amaury Forgeot d'Arc | fdfe62d | 2008-06-17 20:36:03 +0000 | [diff] [blame] | 1641 | 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] | 1642 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1643 | .. method:: symmetric_difference(other) |
| 1644 | set ^ other |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1645 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1646 | 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] | 1647 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1648 | .. method:: copy() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1649 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1650 | Return a new set with a shallow copy of *s*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1651 | |
| 1652 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1653 | Note, the non-operator versions of :meth:`union`, :meth:`intersection`, |
| 1654 | :meth:`difference`, and :meth:`symmetric_difference`, :meth:`issubset`, and |
| 1655 | :meth:`issuperset` methods will accept any iterable as an argument. In |
| 1656 | contrast, their operator based counterparts require their arguments to be |
| 1657 | sets. This precludes error-prone constructions like ``set('abc') & 'cbs'`` |
| 1658 | in favor of the more readable ``set('abc').intersection('cbs')``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1659 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1660 | Both :class:`set` and :class:`frozenset` support set to set comparisons. Two |
| 1661 | sets are equal if and only if every element of each set is contained in the |
| 1662 | other (each is a subset of the other). A set is less than another set if and |
| 1663 | only if the first set is a proper subset of the second set (is a subset, but |
| 1664 | is not equal). A set is greater than another set if and only if the first set |
| 1665 | 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] | 1666 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1667 | Instances of :class:`set` are compared to instances of :class:`frozenset` |
| 1668 | based on their members. For example, ``set('abc') == frozenset('abc')`` |
| 1669 | returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1670 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1671 | The subset and equality comparisons do not generalize to a complete ordering |
| 1672 | function. For example, any two disjoint sets are not equal and are not |
| 1673 | 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] | 1674 | ``a==b``, or ``a>b``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1675 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1676 | Since sets only define partial ordering (subset relationships), the output of |
| 1677 | the :meth:`list.sort` method is undefined for lists of sets. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1678 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1679 | Set elements, like dictionary keys, must be :term:`hashable`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1680 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1681 | Binary operations that mix :class:`set` instances with :class:`frozenset` |
| 1682 | return the type of the first operand. For example: ``frozenset('ab') | |
| 1683 | set('bc')`` returns an instance of :class:`frozenset`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1684 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1685 | The following table lists operations available for :class:`set` that do not |
| 1686 | apply to immutable instances of :class:`frozenset`: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1687 | |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 1688 | .. method:: update(other, ...) |
| 1689 | set |= other | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1690 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1691 | Update the set, adding elements from *other*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1692 | |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 1693 | .. method:: intersection_update(other, ...) |
| 1694 | set &= other & ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1695 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1696 | Update the set, keeping only elements found in it and *other*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1697 | |
Amaury Forgeot d'Arc | fdfe62d | 2008-06-17 20:36:03 +0000 | [diff] [blame] | 1698 | .. method:: difference_update(other, ...) |
| 1699 | set -= other | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1700 | |
Amaury Forgeot d'Arc | fdfe62d | 2008-06-17 20:36:03 +0000 | [diff] [blame] | 1701 | Update the set, removing elements found in others. |
| 1702 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1703 | .. method:: symmetric_difference_update(other) |
| 1704 | set ^= other |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1705 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1706 | 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] | 1707 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1708 | .. method:: add(elem) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1709 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1710 | Add element *elem* to the set. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1711 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1712 | .. method:: remove(elem) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1713 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1714 | Remove element *elem* from the set. Raises :exc:`KeyError` if *elem* is |
| 1715 | not contained in the set. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1716 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1717 | .. method:: discard(elem) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1718 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1719 | Remove element *elem* from the set if it is present. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1720 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1721 | .. method:: pop() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1722 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1723 | Remove and return an arbitrary element from the set. Raises |
| 1724 | :exc:`KeyError` if the set is empty. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1725 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1726 | .. method:: clear() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1727 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1728 | Remove all elements from the set. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1729 | |
| 1730 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1731 | Note, the non-operator versions of the :meth:`update`, |
| 1732 | :meth:`intersection_update`, :meth:`difference_update`, and |
| 1733 | :meth:`symmetric_difference_update` methods will accept any iterable as an |
| 1734 | argument. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1735 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1736 | Note, the *elem* argument to the :meth:`__contains__`, :meth:`remove`, and |
| 1737 | :meth:`discard` methods may be a set. To support searching for an equivalent |
| 1738 | frozenset, the *elem* set is temporarily mutated during the search and then |
| 1739 | restored. During the search, the *elem* set should not be read or mutated |
| 1740 | since it does not have a meaningful value. |
Benjamin Peterson | 699adb9 | 2008-05-08 22:27:58 +0000 | [diff] [blame] | 1741 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1742 | |
| 1743 | .. _typesmapping: |
| 1744 | |
| 1745 | Mapping Types --- :class:`dict` |
| 1746 | =============================== |
| 1747 | |
| 1748 | .. index:: |
| 1749 | object: mapping |
| 1750 | object: dictionary |
| 1751 | triple: operations on; mapping; types |
| 1752 | triple: operations on; dictionary; type |
| 1753 | statement: del |
| 1754 | builtin: len |
| 1755 | |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 1756 | A :dfn:`mapping` object maps :term:`hashable` values to arbitrary objects. |
| 1757 | Mappings are mutable objects. There is currently only one standard mapping |
| 1758 | type, the :dfn:`dictionary`. (For other containers see the built in |
| 1759 | :class:`list`, :class:`set`, and :class:`tuple` classes, and the |
| 1760 | :mod:`collections` module.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1761 | |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 1762 | A dictionary's keys are *almost* arbitrary values. Values that are not |
| 1763 | :term:`hashable`, that is, values containing lists, dictionaries or other |
| 1764 | mutable types (that are compared by value rather than by object identity) may |
| 1765 | not be used as keys. Numeric types used for keys obey the normal rules for |
| 1766 | numeric comparison: if two numbers compare equal (such as ``1`` and ``1.0``) |
| 1767 | then they can be used interchangeably to index the same dictionary entry. (Note |
| 1768 | however, that since computers store floating-point numbers as approximations it |
| 1769 | is usually unwise to use them as dictionary keys.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1770 | |
| 1771 | Dictionaries can be created by placing a comma-separated list of ``key: value`` |
| 1772 | pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098: |
| 1773 | 'jack', 4127: 'sjoerd'}``, or by the :class:`dict` constructor. |
| 1774 | |
| 1775 | .. class:: dict([arg]) |
| 1776 | |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 1777 | Return a new dictionary initialized from an optional positional argument or |
| 1778 | from a set of keyword arguments. If no arguments are given, return a new |
| 1779 | empty dictionary. If the positional argument *arg* is a mapping object, |
| 1780 | return a dictionary mapping the same keys to the same values as does the |
| 1781 | mapping object. Otherwise the positional argument must be a sequence, a |
| 1782 | container that supports iteration, or an iterator object. The elements of |
| 1783 | the argument must each also be of one of those kinds, and each must in turn |
| 1784 | contain exactly two objects. The first is used as a key in the new |
| 1785 | dictionary, and the second as the key's value. If a given key is seen more |
| 1786 | than once, the last value associated with it is retained in the new |
| 1787 | dictionary. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1788 | |
| 1789 | If keyword arguments are given, the keywords themselves with their associated |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 1790 | values are added as items to the dictionary. If a key is specified both in |
| 1791 | the positional argument and as a keyword argument, the value associated with |
| 1792 | the keyword is retained in the dictionary. For example, these all return a |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1793 | dictionary equal to ``{"one": 2, "two": 3}``: |
| 1794 | |
| 1795 | * ``dict(one=2, two=3)`` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1796 | * ``dict({'one': 2, 'two': 3})`` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1797 | * ``dict(zip(('one', 'two'), (2, 3)))`` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1798 | * ``dict([['two', 3], ['one', 2]])`` |
| 1799 | |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 1800 | The first example only works for keys that are valid Python identifiers; the |
| 1801 | others work with any valid keys. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1802 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1803 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1804 | These are the operations that dictionaries support (and therefore, custom |
| 1805 | mapping types should support too): |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1806 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1807 | .. describe:: len(d) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1808 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1809 | Return the number of items in the dictionary *d*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1810 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1811 | .. describe:: d[key] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1812 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1813 | Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key* is |
| 1814 | not in the map. |
| 1815 | |
| 1816 | If a subclass of dict defines a method :meth:`__missing__`, if the key *key* |
| 1817 | is not present, the ``d[key]`` operation calls that method with the key *key* |
| 1818 | as argument. The ``d[key]`` operation then returns or raises whatever is |
| 1819 | returned or raised by the ``__missing__(key)`` call if the key is not |
| 1820 | present. No other operations or methods invoke :meth:`__missing__`. If |
| 1821 | :meth:`__missing__` is not defined, :exc:`KeyError` is raised. |
| 1822 | :meth:`__missing__` must be a method; it cannot be an instance variable. For |
| 1823 | an example, see :class:`collections.defaultdict`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1824 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1825 | .. describe:: d[key] = value |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1826 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1827 | Set ``d[key]`` to *value*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1828 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1829 | .. describe:: del d[key] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1830 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1831 | Remove ``d[key]`` from *d*. Raises a :exc:`KeyError` if *key* is not in the |
| 1832 | map. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1833 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1834 | .. describe:: key in d |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1835 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1836 | Return ``True`` if *d* has a key *key*, else ``False``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1837 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1838 | .. describe:: key not in d |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1839 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1840 | Equivalent to ``not key in d``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1841 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1842 | .. method:: clear() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1843 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1844 | Remove all items from the dictionary. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1845 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1846 | .. method:: copy() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1847 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1848 | Return a shallow copy of the dictionary. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1849 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1850 | .. method:: fromkeys(seq[, value]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1851 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1852 | Create a new dictionary with keys from *seq* and values set to *value*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1853 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1854 | :meth:`fromkeys` is a class method that returns a new dictionary. *value* |
| 1855 | defaults to ``None``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1856 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1857 | .. method:: get(key[, default]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1858 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1859 | Return the value for *key* if *key* is in the dictionary, else *default*. |
| 1860 | If *default* is not given, it defaults to ``None``, so that this method |
| 1861 | never raises a :exc:`KeyError`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1862 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1863 | .. method:: items() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1864 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1865 | Return a new view of the dictionary's items (``(key, value)`` pairs). See |
| 1866 | below for documentation of view objects. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1867 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1868 | .. method:: keys() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1869 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1870 | Return a new view of the dictionary's keys. See below for documentation of |
| 1871 | view objects. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1872 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1873 | .. method:: pop(key[, default]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1874 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1875 | If *key* is in the dictionary, remove it and return its value, else return |
| 1876 | *default*. If *default* is not given and *key* is not in the dictionary, |
| 1877 | a :exc:`KeyError` is raised. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1878 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1879 | .. method:: popitem() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1880 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1881 | Remove and return an arbitrary ``(key, value)`` pair from the dictionary. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1882 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1883 | :meth:`popitem` is useful to destructively iterate over a dictionary, as |
| 1884 | often used in set algorithms. If the dictionary is empty, calling |
| 1885 | :meth:`popitem` raises a :exc:`KeyError`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1886 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1887 | .. method:: setdefault(key[, default]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1888 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1889 | If *key* is in the dictionary, return its value. If not, insert *key* |
| 1890 | with a value of *default* and return *default*. *default* defaults to |
| 1891 | ``None``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1892 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1893 | .. method:: update([other]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1894 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1895 | Update the dictionary with the key/value pairs from *other*, overwriting |
| 1896 | existing keys. Return ``None``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1897 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1898 | :meth:`update` accepts either another dictionary object or an iterable of |
| 1899 | key/value pairs (as a tuple or other iterable of length two). If keyword |
| 1900 | arguments are specified, the dictionary is then is updated with those |
| 1901 | key/value pairs: ``d.update(red=1, blue=2)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1902 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1903 | .. method:: values() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1904 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 1905 | Return a new view of the dictionary's values. See below for documentation of |
| 1906 | view objects. |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 1907 | |
| 1908 | |
Benjamin Peterson | 44309e6 | 2008-11-22 00:41:45 +0000 | [diff] [blame] | 1909 | .. _dict-views: |
| 1910 | |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 1911 | Dictionary view objects |
| 1912 | ----------------------- |
| 1913 | |
| 1914 | The objects returned by :meth:`dict.keys`, :meth:`dict.values` and |
| 1915 | :meth:`dict.items` are *view objects*. They provide a dynamic view on the |
| 1916 | dictionary's entries, which means that when the dictionary changes, the view |
Benjamin Peterson | ce0506c | 2008-11-17 21:47:41 +0000 | [diff] [blame] | 1917 | reflects these changes. |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 1918 | |
| 1919 | Dictionary views can be iterated over to yield their respective data, and |
| 1920 | support membership tests: |
| 1921 | |
| 1922 | .. describe:: len(dictview) |
| 1923 | |
| 1924 | Return the number of entries in the dictionary. |
| 1925 | |
| 1926 | .. describe:: iter(dictview) |
| 1927 | |
| 1928 | Return an iterator over the keys, values or items (represented as tuples of |
| 1929 | ``(key, value)``) in the dictionary. |
| 1930 | |
| 1931 | Keys and values are iterated over in an arbitrary order which is non-random, |
| 1932 | varies across Python implementations, and depends on the dictionary's history |
| 1933 | of insertions and deletions. If keys, values and items views are iterated |
| 1934 | over with no intervening modifications to the dictionary, the order of items |
| 1935 | will directly correspond. This allows the creation of ``(value, key)`` pairs |
| 1936 | using :func:`zip`: ``pairs = zip(d.values(), d.keys())``. Another way to |
| 1937 | create the same list is ``pairs = [(v, k) for (k, v) in d.items()]``. |
| 1938 | |
| 1939 | .. describe:: x in dictview |
| 1940 | |
| 1941 | Return ``True`` if *x* is in the underlying dictionary's keys, values or |
| 1942 | items (in the latter case, *x* should be a ``(key, value)`` tuple). |
| 1943 | |
| 1944 | |
Benjamin Peterson | ce0506c | 2008-11-17 21:47:41 +0000 | [diff] [blame] | 1945 | Keys views are set-like since their entries are unique and hashable. If all |
| 1946 | values are hashable, so that (key, value) pairs are unique and hashable, then |
| 1947 | the items view is also set-like. (Values views are not treated as set-like |
| 1948 | since the entries are generally not unique.) Then these set operations are |
| 1949 | available ("other" refers either to another view or a set): |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 1950 | |
| 1951 | .. describe:: dictview & other |
| 1952 | |
| 1953 | Return the intersection of the dictview and the other object as a new set. |
| 1954 | |
| 1955 | .. describe:: dictview | other |
| 1956 | |
| 1957 | Return the union of the dictview and the other object as a new set. |
| 1958 | |
| 1959 | .. describe:: dictview - other |
| 1960 | |
| 1961 | Return the difference between the dictview and the other object (all elements |
| 1962 | in *dictview* that aren't in *other*) as a new set. |
| 1963 | |
| 1964 | .. describe:: dictview ^ other |
| 1965 | |
| 1966 | Return the symmetric difference (all elements either in *dictview* or |
| 1967 | *other*, but not in both) of the dictview and the other object as a new set. |
| 1968 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1969 | |
Georg Brandl | c53c966 | 2007-09-04 17:58:02 +0000 | [diff] [blame] | 1970 | An example of dictionary view usage:: |
| 1971 | |
| 1972 | >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500} |
| 1973 | >>> keys = dishes.keys() |
| 1974 | >>> values = dishes.values() |
| 1975 | |
| 1976 | >>> # iteration |
| 1977 | >>> n = 0 |
| 1978 | >>> for val in values: |
| 1979 | ... n += val |
| 1980 | >>> print(n) |
| 1981 | 504 |
| 1982 | |
| 1983 | >>> # keys and values are iterated over in the same order |
| 1984 | >>> list(keys) |
| 1985 | ['eggs', 'bacon', 'sausage', 'spam'] |
| 1986 | >>> list(values) |
| 1987 | [2, 1, 1, 500] |
| 1988 | |
| 1989 | >>> # view objects are dynamic and reflect dict changes |
| 1990 | >>> del dishes['eggs'] |
| 1991 | >>> del dishes['sausage'] |
| 1992 | >>> list(keys) |
| 1993 | ['spam', 'bacon'] |
| 1994 | |
| 1995 | >>> # set operations |
| 1996 | >>> keys & {'eggs', 'bacon', 'salad'} |
Gregory P. Smith | e838812 | 2008-09-04 04:18:09 +0000 | [diff] [blame] | 1997 | {'bacon'} |
Georg Brandl | c53c966 | 2007-09-04 17:58:02 +0000 | [diff] [blame] | 1998 | |
| 1999 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2000 | .. _bltin-file-objects: |
| 2001 | |
| 2002 | File Objects |
| 2003 | ============ |
| 2004 | |
| 2005 | .. index:: |
| 2006 | object: file |
| 2007 | builtin: file |
| 2008 | module: os |
| 2009 | module: socket |
| 2010 | |
Georg Brandl | 81ac1ce | 2007-08-31 17:17:17 +0000 | [diff] [blame] | 2011 | .. XXX this is quite out of date, must be updated with "io" module |
| 2012 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2013 | File objects are implemented using C's ``stdio`` package and can be |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 2014 | created with the built-in :func:`open` function. File |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2015 | objects are also returned by some other built-in functions and methods, |
| 2016 | such as :func:`os.popen` and :func:`os.fdopen` and the :meth:`makefile` |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 2017 | method of socket objects. Temporary files can be created using the |
| 2018 | :mod:`tempfile` module, and high-level file operations such as copying, |
| 2019 | moving, and deleting files and directories can be achieved with the |
| 2020 | :mod:`shutil` module. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2021 | |
| 2022 | When a file operation fails for an I/O-related reason, the exception |
| 2023 | :exc:`IOError` is raised. This includes situations where the operation is not |
| 2024 | defined for some reason, like :meth:`seek` on a tty device or writing a file |
| 2025 | opened for reading. |
| 2026 | |
| 2027 | Files have the following methods: |
| 2028 | |
| 2029 | |
| 2030 | .. method:: file.close() |
| 2031 | |
| 2032 | Close the file. A closed file cannot be read or written any more. Any operation |
| 2033 | which requires that the file be open will raise a :exc:`ValueError` after the |
| 2034 | file has been closed. Calling :meth:`close` more than once is allowed. |
| 2035 | |
Georg Brandl | e6bcc91 | 2008-05-12 18:05:20 +0000 | [diff] [blame] | 2036 | You can avoid having to call this method explicitly if you use |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2037 | the :keyword:`with` statement. For example, the following code will |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 2038 | automatically close *f* when the :keyword:`with` block is exited:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2039 | |
Benjamin Peterson | a986dfa | 2008-07-31 21:10:28 +0000 | [diff] [blame] | 2040 | from __future__ import with_statement # This isn't required in Python 2.6 |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2041 | |
| 2042 | with open("hello.txt") as f: |
| 2043 | for line in f: |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 2044 | print(line) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2045 | |
| 2046 | In older versions of Python, you would have needed to do this to get the same |
| 2047 | effect:: |
| 2048 | |
| 2049 | f = open("hello.txt") |
| 2050 | try: |
| 2051 | for line in f: |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 2052 | print(line) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2053 | finally: |
| 2054 | f.close() |
| 2055 | |
| 2056 | .. note:: |
| 2057 | |
| 2058 | Not all "file-like" types in Python support use as a context manager for the |
| 2059 | :keyword:`with` statement. If your code is intended to work with any file-like |
| 2060 | object, you can use the function :func:`contextlib.closing` instead of using |
| 2061 | the object directly. |
| 2062 | |
| 2063 | |
| 2064 | .. method:: file.flush() |
| 2065 | |
| 2066 | Flush the internal buffer, like ``stdio``'s :cfunc:`fflush`. This may be a |
| 2067 | no-op on some file-like objects. |
| 2068 | |
| 2069 | |
| 2070 | .. method:: file.fileno() |
| 2071 | |
| 2072 | .. index:: |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 2073 | pair: file; descriptor |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2074 | module: fcntl |
| 2075 | |
| 2076 | Return the integer "file descriptor" that is used by the underlying |
| 2077 | implementation to request I/O operations from the operating system. This can be |
| 2078 | useful for other, lower level interfaces that use file descriptors, such as the |
| 2079 | :mod:`fcntl` module or :func:`os.read` and friends. |
| 2080 | |
| 2081 | .. note:: |
| 2082 | |
| 2083 | File-like objects which do not have a real file descriptor should *not* provide |
| 2084 | this method! |
| 2085 | |
| 2086 | |
| 2087 | .. method:: file.isatty() |
| 2088 | |
| 2089 | Return ``True`` if the file is connected to a tty(-like) device, else ``False``. |
| 2090 | |
| 2091 | .. note:: |
| 2092 | |
| 2093 | If a file-like object is not associated with a real file, this method should |
| 2094 | *not* be implemented. |
| 2095 | |
| 2096 | |
| 2097 | .. method:: file.__next__() |
| 2098 | |
| 2099 | A file object is its own iterator, for example ``iter(f)`` returns *f* (unless |
| 2100 | *f* is closed). When a file is used as an iterator, typically in a |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 2101 | :keyword:`for` loop (for example, ``for line in f: print(line)``), the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2102 | :meth:`__next__` method is called repeatedly. This method returns the next |
| 2103 | input line, or raises :exc:`StopIteration` when EOF is hit when the file is open |
| 2104 | for reading (behavior is undefined when the file is open for writing). In order |
| 2105 | to make a :keyword:`for` loop the most efficient way of looping over the lines |
| 2106 | of a file (a very common operation), the :meth:`__next__` method uses a hidden |
| 2107 | read-ahead buffer. As a consequence of using a read-ahead buffer, combining |
| 2108 | :meth:`__next__` with other file methods (like :meth:`readline`) does not work |
| 2109 | right. However, using :meth:`seek` to reposition the file to an absolute |
| 2110 | position will flush the read-ahead buffer. |
| 2111 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2112 | |
| 2113 | .. method:: file.read([size]) |
| 2114 | |
| 2115 | Read at most *size* bytes from the file (less if the read hits EOF before |
| 2116 | obtaining *size* bytes). If the *size* argument is negative or omitted, read |
| 2117 | all data until EOF is reached. The bytes are returned as a string object. An |
| 2118 | empty string is returned when EOF is encountered immediately. (For certain |
| 2119 | files, like ttys, it makes sense to continue reading after an EOF is hit.) Note |
| 2120 | that this method may call the underlying C function :cfunc:`fread` more than |
| 2121 | once in an effort to acquire as close to *size* bytes as possible. Also note |
Georg Brandl | 86b2fb9 | 2008-07-16 03:43:04 +0000 | [diff] [blame] | 2122 | that when in non-blocking mode, less data than was requested may be |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2123 | returned, even if no *size* parameter was given. |
| 2124 | |
| 2125 | |
| 2126 | .. method:: file.readline([size]) |
| 2127 | |
| 2128 | Read one entire line from the file. A trailing newline character is kept in the |
| 2129 | string (but may be absent when a file ends with an incomplete line). [#]_ If |
| 2130 | the *size* argument is present and non-negative, it is a maximum byte count |
| 2131 | (including the trailing newline) and an incomplete line may be returned. An |
| 2132 | empty string is returned *only* when EOF is encountered immediately. |
| 2133 | |
| 2134 | .. note:: |
| 2135 | |
| 2136 | Unlike ``stdio``'s :cfunc:`fgets`, the returned string contains null characters |
| 2137 | (``'\0'``) if they occurred in the input. |
| 2138 | |
| 2139 | |
| 2140 | .. method:: file.readlines([sizehint]) |
| 2141 | |
| 2142 | Read until EOF using :meth:`readline` and return a list containing the lines |
| 2143 | thus read. If the optional *sizehint* argument is present, instead of |
| 2144 | reading up to EOF, whole lines totalling approximately *sizehint* bytes |
| 2145 | (possibly after rounding up to an internal buffer size) are read. Objects |
| 2146 | implementing a file-like interface may choose to ignore *sizehint* if it |
| 2147 | cannot be implemented, or cannot be implemented efficiently. |
| 2148 | |
| 2149 | |
| 2150 | .. method:: file.seek(offset[, whence]) |
| 2151 | |
| 2152 | Set the file's current position, like ``stdio``'s :cfunc:`fseek`. The *whence* |
| 2153 | argument is optional and defaults to ``os.SEEK_SET`` or ``0`` (absolute file |
| 2154 | positioning); other values are ``os.SEEK_CUR`` or ``1`` (seek relative to the |
| 2155 | current position) and ``os.SEEK_END`` or ``2`` (seek relative to the file's |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 2156 | end). There is no return value. |
| 2157 | |
| 2158 | For example, ``f.seek(2, os.SEEK_CUR)`` advances the position by two and |
| 2159 | ``f.seek(-3, os.SEEK_END)`` sets the position to the third to last. |
| 2160 | |
| 2161 | Note that if the file is opened for appending |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2162 | (mode ``'a'`` or ``'a+'``), any :meth:`seek` operations will be undone at the |
| 2163 | next write. If the file is only opened for writing in append mode (mode |
| 2164 | ``'a'``), this method is essentially a no-op, but it remains useful for files |
| 2165 | opened in append mode with reading enabled (mode ``'a+'``). If the file is |
| 2166 | opened in text mode (without ``'b'``), only offsets returned by :meth:`tell` are |
| 2167 | legal. Use of other offsets causes undefined behavior. |
| 2168 | |
| 2169 | Note that not all file objects are seekable. |
| 2170 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2171 | |
| 2172 | .. method:: file.tell() |
| 2173 | |
| 2174 | Return the file's current position, like ``stdio``'s :cfunc:`ftell`. |
| 2175 | |
| 2176 | .. note:: |
| 2177 | |
| 2178 | On Windows, :meth:`tell` can return illegal values (after an :cfunc:`fgets`) |
| 2179 | when reading files with Unix-style line-endings. Use binary mode (``'rb'``) to |
| 2180 | circumvent this problem. |
| 2181 | |
| 2182 | |
| 2183 | .. method:: file.truncate([size]) |
| 2184 | |
| 2185 | Truncate the file's size. If the optional *size* argument is present, the file |
| 2186 | is truncated to (at most) that size. The size defaults to the current position. |
| 2187 | The current file position is not changed. Note that if a specified size exceeds |
| 2188 | the file's current size, the result is platform-dependent: possibilities |
| 2189 | include that the file may remain unchanged, increase to the specified size as if |
| 2190 | zero-filled, or increase to the specified size with undefined new content. |
| 2191 | Availability: Windows, many Unix variants. |
| 2192 | |
| 2193 | |
| 2194 | .. method:: file.write(str) |
| 2195 | |
Georg Brandl | 3888980 | 2008-03-21 19:42:31 +0000 | [diff] [blame] | 2196 | Write a string to the file. Due to buffering, the string may not actually |
| 2197 | show up in the file until the :meth:`flush` or :meth:`close` method is |
| 2198 | called. |
| 2199 | |
| 2200 | The meaning of the return value is not defined for every file-like object. |
| 2201 | Some (mostly low-level) file-like objects may return the number of bytes |
| 2202 | actually written, others return ``None``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2203 | |
| 2204 | |
| 2205 | .. method:: file.writelines(sequence) |
| 2206 | |
| 2207 | Write a sequence of strings to the file. The sequence can be any iterable |
| 2208 | object producing strings, typically a list of strings. There is no return value. |
| 2209 | (The name is intended to match :meth:`readlines`; :meth:`writelines` does not |
| 2210 | add line separators.) |
| 2211 | |
| 2212 | Files support the iterator protocol. Each iteration returns the same result as |
| 2213 | ``file.readline()``, and iteration ends when the :meth:`readline` method returns |
| 2214 | an empty string. |
| 2215 | |
| 2216 | File objects also offer a number of other interesting attributes. These are not |
| 2217 | required for file-like objects, but should be implemented if they make sense for |
| 2218 | the particular object. |
| 2219 | |
| 2220 | |
| 2221 | .. attribute:: file.closed |
| 2222 | |
| 2223 | bool indicating the current state of the file object. This is a read-only |
| 2224 | attribute; the :meth:`close` method changes the value. It may not be available |
| 2225 | on all file-like objects. |
| 2226 | |
| 2227 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 2228 | .. XXX does this still apply? |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2229 | .. attribute:: file.encoding |
| 2230 | |
Georg Brandl | f694518 | 2008-02-01 11:56:49 +0000 | [diff] [blame] | 2231 | The encoding that this file uses. When strings are written to a file, |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2232 | they will be converted to byte strings using this encoding. In addition, when |
| 2233 | the file is connected to a terminal, the attribute gives the encoding that the |
| 2234 | terminal is likely to use (that information might be incorrect if the user has |
| 2235 | misconfigured the terminal). The attribute is read-only and may not be present |
| 2236 | on all file-like objects. It may also be ``None``, in which case the file uses |
Georg Brandl | f694518 | 2008-02-01 11:56:49 +0000 | [diff] [blame] | 2237 | the system default encoding for converting strings. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2238 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2239 | |
Benjamin Peterson | dcf97b9 | 2008-07-02 17:30:14 +0000 | [diff] [blame] | 2240 | .. attribute:: file.errors |
| 2241 | |
| 2242 | The Unicode error handler used along with the encoding. |
| 2243 | |
| 2244 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2245 | .. attribute:: file.mode |
| 2246 | |
| 2247 | The I/O mode for the file. If the file was created using the :func:`open` |
| 2248 | built-in function, this will be the value of the *mode* parameter. This is a |
| 2249 | read-only attribute and may not be present on all file-like objects. |
| 2250 | |
| 2251 | |
| 2252 | .. attribute:: file.name |
| 2253 | |
| 2254 | If the file object was created using :func:`open`, the name of the file. |
| 2255 | Otherwise, some string that indicates the source of the file object, of the |
| 2256 | form ``<...>``. This is a read-only attribute and may not be present on all |
| 2257 | file-like objects. |
| 2258 | |
| 2259 | |
| 2260 | .. attribute:: file.newlines |
| 2261 | |
| 2262 | If Python was built with the :option:`--with-universal-newlines` option to |
| 2263 | :program:`configure` (the default) this read-only attribute exists, and for |
| 2264 | files opened in universal newline read mode it keeps track of the types of |
| 2265 | newlines encountered while reading the file. The values it can take are |
| 2266 | ``'\r'``, ``'\n'``, ``'\r\n'``, ``None`` (unknown, no newlines read yet) or a |
| 2267 | tuple containing all the newline types seen, to indicate that multiple newline |
| 2268 | conventions were encountered. For files not opened in universal newline read |
| 2269 | mode the value of this attribute will be ``None``. |
| 2270 | |
| 2271 | |
Benjamin Peterson | 1b25b92 | 2008-09-09 22:15:27 +0000 | [diff] [blame] | 2272 | .. _typememoryview: |
| 2273 | |
| 2274 | memoryview Types |
| 2275 | ================ |
| 2276 | |
| 2277 | :class:`memoryview`\s allow Python code to access the internal data of an object |
Georg Brandl | 1009d39 | 2008-09-10 07:14:18 +0000 | [diff] [blame] | 2278 | that supports the buffer protocol without copying. Memory can be interpreted as |
| 2279 | simple bytes or complex data structures. |
Benjamin Peterson | 1b25b92 | 2008-09-09 22:15:27 +0000 | [diff] [blame] | 2280 | |
| 2281 | .. class:: memoryview(obj) |
| 2282 | |
Georg Brandl | 1009d39 | 2008-09-10 07:14:18 +0000 | [diff] [blame] | 2283 | Create a :class:`memoryview` that references *obj*. *obj* must support the |
Benjamin Peterson | 1b25b92 | 2008-09-09 22:15:27 +0000 | [diff] [blame] | 2284 | buffer protocol. Builtin objects that support the buffer protocol include |
| 2285 | :class:`bytes` and :class:`bytearray`. |
| 2286 | |
Benjamin Peterson | 5e19e44 | 2008-09-10 21:47:03 +0000 | [diff] [blame] | 2287 | ``len(view)`` returns the total number of bytes in the memoryview, *view*. |
| 2288 | |
Georg Brandl | 1009d39 | 2008-09-10 07:14:18 +0000 | [diff] [blame] | 2289 | A :class:`memoryview` supports slicing to expose its data. Taking a single |
| 2290 | index will return a single byte. Full slicing will result in a subview:: |
Benjamin Peterson | 1b25b92 | 2008-09-09 22:15:27 +0000 | [diff] [blame] | 2291 | |
| 2292 | >>> v = memoryview(b'abcefg') |
| 2293 | >>> v[1] |
| 2294 | b'b' |
| 2295 | >>> v[-1] |
| 2296 | b'g' |
| 2297 | >>> v[1:4] |
| 2298 | <memory at 0x77ab28> |
| 2299 | >>> bytes(v[1:4]) |
| 2300 | b'bce' |
| 2301 | >>> v[3:-1] |
| 2302 | <memory at 0x744f18> |
| 2303 | >>> bytes(v[4:-1]) |
| 2304 | |
Georg Brandl | 1009d39 | 2008-09-10 07:14:18 +0000 | [diff] [blame] | 2305 | If the object the memory view is over supports changing its data, the |
| 2306 | memoryview supports slice assignment:: |
Benjamin Peterson | 1b25b92 | 2008-09-09 22:15:27 +0000 | [diff] [blame] | 2307 | |
| 2308 | >>> data = bytearray(b'abcefg') |
| 2309 | >>> v = memoryview(data) |
| 2310 | >>> v.readonly |
| 2311 | False |
| 2312 | >>> v[0] = 'z' |
| 2313 | >>> data |
| 2314 | bytearray(b'zbcefg') |
| 2315 | >>> v[1:4] = b'123' |
| 2316 | >>> data |
| 2317 | bytearray(b'a123fg') |
| 2318 | >>> v[2] = b'spam' |
| 2319 | Traceback (most recent call last): |
| 2320 | File "<stdin>", line 1, in <module> |
| 2321 | ValueError: cannot modify size of memoryview object |
| 2322 | |
| 2323 | Notice how the size of the memoryview object can not be changed. |
| 2324 | |
| 2325 | |
Benjamin Peterson | 0c80465 | 2008-09-10 21:31:58 +0000 | [diff] [blame] | 2326 | :class:`memoryview` has two methods: |
Benjamin Peterson | 1b25b92 | 2008-09-09 22:15:27 +0000 | [diff] [blame] | 2327 | |
| 2328 | .. method:: tobytes() |
| 2329 | |
Benjamin Peterson | 0c80465 | 2008-09-10 21:31:58 +0000 | [diff] [blame] | 2330 | Return the data in the buffer as a bytestring. |
| 2331 | |
| 2332 | .. method:: tolist() |
| 2333 | |
| 2334 | Return the data in the buffer as a list of integers. :: |
| 2335 | |
| 2336 | >>> memoryview(b'abc').tolist() |
| 2337 | [97, 98, 99] |
Benjamin Peterson | 1b25b92 | 2008-09-09 22:15:27 +0000 | [diff] [blame] | 2338 | |
| 2339 | There are also several readonly attributes available: |
| 2340 | |
| 2341 | .. attribute:: format |
| 2342 | |
| 2343 | A string containing the format (in :mod:`struct` module style) for each |
| 2344 | element in the view. This defaults to ``'B'``, a simple bytestring. |
| 2345 | |
| 2346 | .. attribute:: itemsize |
| 2347 | |
| 2348 | The size in bytes of each element of the memoryview. |
| 2349 | |
| 2350 | .. attribute:: shape |
| 2351 | |
Georg Brandl | 1009d39 | 2008-09-10 07:14:18 +0000 | [diff] [blame] | 2352 | A tuple of integers the length of :attr:`ndim` giving the shape of the |
| 2353 | memory as a N-dimensional array. |
Benjamin Peterson | 1b25b92 | 2008-09-09 22:15:27 +0000 | [diff] [blame] | 2354 | |
| 2355 | .. attribute:: ndim |
| 2356 | |
| 2357 | An integer indicating how many dimensions of a multi-dimensional array the |
| 2358 | memory represents. |
| 2359 | |
| 2360 | .. attribute:: strides |
| 2361 | |
Benjamin Peterson | 2409dc7 | 2008-09-10 21:38:31 +0000 | [diff] [blame] | 2362 | A tuple of integers the length of :attr:`ndim` giving the size in bytes to |
| 2363 | access each element for each dimension of the array. |
Benjamin Peterson | 1b25b92 | 2008-09-09 22:15:27 +0000 | [diff] [blame] | 2364 | |
Benjamin Peterson | 1b25b92 | 2008-09-09 22:15:27 +0000 | [diff] [blame] | 2365 | .. memoryview.suboffsets isn't documented because it only seems useful for C |
| 2366 | |
| 2367 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2368 | .. _typecontextmanager: |
| 2369 | |
| 2370 | Context Manager Types |
| 2371 | ===================== |
| 2372 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2373 | .. index:: |
| 2374 | single: context manager |
| 2375 | single: context management protocol |
| 2376 | single: protocol; context management |
| 2377 | |
| 2378 | Python's :keyword:`with` statement supports the concept of a runtime context |
| 2379 | defined by a context manager. This is implemented using two separate methods |
| 2380 | that allow user-defined classes to define a runtime context that is entered |
| 2381 | before the statement body is executed and exited when the statement ends. |
| 2382 | |
| 2383 | The :dfn:`context management protocol` consists of a pair of methods that need |
| 2384 | to be provided for a context manager object to define a runtime context: |
| 2385 | |
| 2386 | |
| 2387 | .. method:: contextmanager.__enter__() |
| 2388 | |
| 2389 | Enter the runtime context and return either this object or another object |
| 2390 | related to the runtime context. The value returned by this method is bound to |
| 2391 | the identifier in the :keyword:`as` clause of :keyword:`with` statements using |
| 2392 | this context manager. |
| 2393 | |
| 2394 | An example of a context manager that returns itself is a file object. File |
| 2395 | objects return themselves from __enter__() to allow :func:`open` to be used as |
| 2396 | the context expression in a :keyword:`with` statement. |
| 2397 | |
| 2398 | 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] | 2399 | returned by :func:`decimal.localcontext`. These managers set the active |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2400 | decimal context to a copy of the original decimal context and then return the |
| 2401 | copy. This allows changes to be made to the current decimal context in the body |
| 2402 | of the :keyword:`with` statement without affecting code outside the |
| 2403 | :keyword:`with` statement. |
| 2404 | |
| 2405 | |
| 2406 | .. method:: contextmanager.__exit__(exc_type, exc_val, exc_tb) |
| 2407 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 2408 | 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] | 2409 | that occurred should be suppressed. If an exception occurred while executing the |
| 2410 | body of the :keyword:`with` statement, the arguments contain the exception type, |
| 2411 | value and traceback information. Otherwise, all three arguments are ``None``. |
| 2412 | |
| 2413 | Returning a true value from this method will cause the :keyword:`with` statement |
| 2414 | to suppress the exception and continue execution with the statement immediately |
| 2415 | following the :keyword:`with` statement. Otherwise the exception continues |
| 2416 | propagating after this method has finished executing. Exceptions that occur |
| 2417 | during execution of this method will replace any exception that occurred in the |
| 2418 | body of the :keyword:`with` statement. |
| 2419 | |
| 2420 | The exception passed in should never be reraised explicitly - instead, this |
| 2421 | method should return a false value to indicate that the method completed |
| 2422 | successfully and does not want to suppress the raised exception. This allows |
| 2423 | context management code (such as ``contextlib.nested``) to easily detect whether |
| 2424 | or not an :meth:`__exit__` method has actually failed. |
| 2425 | |
| 2426 | Python defines several context managers to support easy thread synchronisation, |
| 2427 | prompt closure of files or other objects, and simpler manipulation of the active |
| 2428 | decimal arithmetic context. The specific types are not treated specially beyond |
| 2429 | their implementation of the context management protocol. See the |
| 2430 | :mod:`contextlib` module for some examples. |
| 2431 | |
Christian Heimes | d8654cf | 2007-12-02 15:22:16 +0000 | [diff] [blame] | 2432 | Python's :term:`generator`\s and the ``contextlib.contextfactory`` :term:`decorator` |
| 2433 | provide a convenient way to implement these protocols. If a generator function is |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2434 | decorated with the ``contextlib.contextfactory`` decorator, it will return a |
| 2435 | context manager implementing the necessary :meth:`__enter__` and |
| 2436 | :meth:`__exit__` methods, rather than the iterator produced by an undecorated |
| 2437 | generator function. |
| 2438 | |
| 2439 | Note that there is no specific slot for any of these methods in the type |
| 2440 | structure for Python objects in the Python/C API. Extension types wanting to |
| 2441 | define these methods must provide them as a normal Python accessible method. |
| 2442 | Compared to the overhead of setting up the runtime context, the overhead of a |
| 2443 | single class dictionary lookup is negligible. |
| 2444 | |
| 2445 | |
| 2446 | .. _typesother: |
| 2447 | |
| 2448 | Other Built-in Types |
| 2449 | ==================== |
| 2450 | |
| 2451 | The interpreter supports several other kinds of objects. Most of these support |
| 2452 | only one or two operations. |
| 2453 | |
| 2454 | |
| 2455 | .. _typesmodules: |
| 2456 | |
| 2457 | Modules |
| 2458 | ------- |
| 2459 | |
| 2460 | The only special operation on a module is attribute access: ``m.name``, where |
| 2461 | *m* is a module and *name* accesses a name defined in *m*'s symbol table. |
| 2462 | Module attributes can be assigned to. (Note that the :keyword:`import` |
| 2463 | statement is not, strictly speaking, an operation on a module object; ``import |
| 2464 | foo`` does not require a module object named *foo* to exist, rather it requires |
| 2465 | an (external) *definition* for a module named *foo* somewhere.) |
| 2466 | |
| 2467 | A special member of every module is :attr:`__dict__`. This is the dictionary |
| 2468 | containing the module's symbol table. Modifying this dictionary will actually |
| 2469 | change the module's symbol table, but direct assignment to the :attr:`__dict__` |
| 2470 | attribute is not possible (you can write ``m.__dict__['a'] = 1``, which defines |
| 2471 | ``m.a`` to be ``1``, but you can't write ``m.__dict__ = {}``). Modifying |
| 2472 | :attr:`__dict__` directly is not recommended. |
| 2473 | |
| 2474 | Modules built into the interpreter are written like this: ``<module 'sys' |
| 2475 | (built-in)>``. If loaded from a file, they are written as ``<module 'os' from |
| 2476 | '/usr/local/lib/pythonX.Y/os.pyc'>``. |
| 2477 | |
| 2478 | |
| 2479 | .. _typesobjects: |
| 2480 | |
| 2481 | Classes and Class Instances |
| 2482 | --------------------------- |
| 2483 | |
| 2484 | See :ref:`objects` and :ref:`class` for these. |
| 2485 | |
| 2486 | |
| 2487 | .. _typesfunctions: |
| 2488 | |
| 2489 | Functions |
| 2490 | --------- |
| 2491 | |
| 2492 | Function objects are created by function definitions. The only operation on a |
| 2493 | function object is to call it: ``func(argument-list)``. |
| 2494 | |
| 2495 | There are really two flavors of function objects: built-in functions and |
| 2496 | user-defined functions. Both support the same operation (to call the function), |
| 2497 | but the implementation is different, hence the different object types. |
| 2498 | |
| 2499 | See :ref:`function` for more information. |
| 2500 | |
| 2501 | |
| 2502 | .. _typesmethods: |
| 2503 | |
| 2504 | Methods |
| 2505 | ------- |
| 2506 | |
| 2507 | .. index:: object: method |
| 2508 | |
| 2509 | Methods are functions that are called using the attribute notation. There are |
| 2510 | two flavors: built-in methods (such as :meth:`append` on lists) and class |
| 2511 | instance methods. Built-in methods are described with the types that support |
| 2512 | them. |
| 2513 | |
Georg Brandl | 2e0b755 | 2007-11-27 12:43:08 +0000 | [diff] [blame] | 2514 | If you access a method (a function defined in a class namespace) through an |
| 2515 | instance, you get a special object: a :dfn:`bound method` (also called |
| 2516 | :dfn:`instance method`) object. When called, it will add the ``self`` argument |
| 2517 | to the argument list. Bound methods have two special read-only attributes: |
| 2518 | ``m.__self__`` is the object on which the method operates, and ``m.__func__`` is |
| 2519 | the function implementing the method. Calling ``m(arg-1, arg-2, ..., arg-n)`` |
| 2520 | is completely equivalent to calling ``m.__func__(m.__self__, arg-1, arg-2, ..., |
| 2521 | arg-n)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2522 | |
Georg Brandl | 2e0b755 | 2007-11-27 12:43:08 +0000 | [diff] [blame] | 2523 | Like function objects, bound method objects support getting arbitrary |
| 2524 | attributes. However, since method attributes are actually stored on the |
| 2525 | underlying function object (``meth.__func__``), setting method attributes on |
| 2526 | bound methods is disallowed. Attempting to set a method attribute results in a |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2527 | :exc:`TypeError` being raised. In order to set a method attribute, you need to |
| 2528 | explicitly set it on the underlying function object:: |
| 2529 | |
| 2530 | class C: |
| 2531 | def method(self): |
| 2532 | pass |
| 2533 | |
| 2534 | c = C() |
Christian Heimes | ff73795 | 2007-11-27 10:40:20 +0000 | [diff] [blame] | 2535 | c.method.__func__.whoami = 'my name is c' |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2536 | |
| 2537 | See :ref:`types` for more information. |
| 2538 | |
| 2539 | |
| 2540 | .. _bltin-code-objects: |
| 2541 | |
| 2542 | Code Objects |
| 2543 | ------------ |
| 2544 | |
| 2545 | .. index:: object: code |
| 2546 | |
| 2547 | .. index:: |
| 2548 | builtin: compile |
| 2549 | single: __code__ (function object attribute) |
| 2550 | |
| 2551 | Code objects are used by the implementation to represent "pseudo-compiled" |
| 2552 | executable Python code such as a function body. They differ from function |
| 2553 | objects because they don't contain a reference to their global execution |
| 2554 | environment. Code objects are returned by the built-in :func:`compile` function |
| 2555 | and can be extracted from function objects through their :attr:`__code__` |
| 2556 | attribute. See also the :mod:`code` module. |
| 2557 | |
| 2558 | .. index:: |
| 2559 | builtin: exec |
| 2560 | builtin: eval |
| 2561 | |
| 2562 | A code object can be executed or evaluated by passing it (instead of a source |
| 2563 | string) to the :func:`exec` or :func:`eval` built-in functions. |
| 2564 | |
| 2565 | See :ref:`types` for more information. |
| 2566 | |
| 2567 | |
| 2568 | .. _bltin-type-objects: |
| 2569 | |
| 2570 | Type Objects |
| 2571 | ------------ |
| 2572 | |
| 2573 | .. index:: |
| 2574 | builtin: type |
| 2575 | module: types |
| 2576 | |
| 2577 | Type objects represent the various object types. An object's type is accessed |
| 2578 | by the built-in function :func:`type`. There are no special operations on |
| 2579 | types. The standard module :mod:`types` defines names for all standard built-in |
| 2580 | types. |
| 2581 | |
Martin v. Löwis | 250ad61 | 2008-04-07 05:43:42 +0000 | [diff] [blame] | 2582 | Types are written like this: ``<class 'int'>``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2583 | |
| 2584 | |
| 2585 | .. _bltin-null-object: |
| 2586 | |
| 2587 | The Null Object |
| 2588 | --------------- |
| 2589 | |
| 2590 | This object is returned by functions that don't explicitly return a value. It |
| 2591 | supports no special operations. There is exactly one null object, named |
| 2592 | ``None`` (a built-in name). |
| 2593 | |
| 2594 | It is written as ``None``. |
| 2595 | |
| 2596 | |
| 2597 | .. _bltin-ellipsis-object: |
| 2598 | |
| 2599 | The Ellipsis Object |
| 2600 | ------------------- |
| 2601 | |
Georg Brandl | cb8ecb1 | 2007-09-04 06:35:14 +0000 | [diff] [blame] | 2602 | This object is commonly used by slicing (see :ref:`slicings`). It supports no |
| 2603 | special operations. There is exactly one ellipsis object, named |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2604 | :const:`Ellipsis` (a built-in name). |
| 2605 | |
| 2606 | It is written as ``Ellipsis`` or ``...``. |
| 2607 | |
| 2608 | |
| 2609 | Boolean Values |
| 2610 | -------------- |
| 2611 | |
| 2612 | Boolean values are the two constant objects ``False`` and ``True``. They are |
| 2613 | used to represent truth values (although other values can also be considered |
| 2614 | false or true). In numeric contexts (for example when used as the argument to |
| 2615 | an arithmetic operator), they behave like the integers 0 and 1, respectively. |
| 2616 | The built-in function :func:`bool` can be used to cast any value to a Boolean, |
| 2617 | if the value can be interpreted as a truth value (see section Truth Value |
| 2618 | Testing above). |
| 2619 | |
| 2620 | .. index:: |
| 2621 | single: False |
| 2622 | single: True |
| 2623 | pair: Boolean; values |
| 2624 | |
| 2625 | They are written as ``False`` and ``True``, respectively. |
| 2626 | |
| 2627 | |
| 2628 | .. _typesinternal: |
| 2629 | |
| 2630 | Internal Objects |
| 2631 | ---------------- |
| 2632 | |
| 2633 | See :ref:`types` for this information. It describes stack frame objects, |
| 2634 | traceback objects, and slice objects. |
| 2635 | |
| 2636 | |
| 2637 | .. _specialattrs: |
| 2638 | |
| 2639 | Special Attributes |
| 2640 | ================== |
| 2641 | |
| 2642 | The implementation adds a few special read-only attributes to several object |
| 2643 | types, where they are relevant. Some of these are not reported by the |
| 2644 | :func:`dir` built-in function. |
| 2645 | |
| 2646 | |
| 2647 | .. attribute:: object.__dict__ |
| 2648 | |
| 2649 | A dictionary or other mapping object used to store an object's (writable) |
| 2650 | attributes. |
| 2651 | |
| 2652 | |
| 2653 | .. attribute:: instance.__class__ |
| 2654 | |
| 2655 | The class to which a class instance belongs. |
| 2656 | |
| 2657 | |
| 2658 | .. attribute:: class.__bases__ |
| 2659 | |
| 2660 | The tuple of base classes of a class object. If there are no base classes, this |
| 2661 | will be an empty tuple. |
| 2662 | |
| 2663 | |
| 2664 | .. attribute:: class.__name__ |
| 2665 | |
| 2666 | The name of the class or type. |
| 2667 | |
| 2668 | .. rubric:: Footnotes |
| 2669 | |
| 2670 | .. [#] Additional information on these special methods may be found in the Python |
| 2671 | Reference Manual (:ref:`customization`). |
| 2672 | |
| 2673 | .. [#] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and |
| 2674 | similarly for tuples. |
| 2675 | |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame^] | 2676 | .. [#] Beware of this formula! It's mathematically valid, but as a |
| 2677 | Python expression it will not give correct results for all ``x``, |
| 2678 | as a consequence of the limited precision of floating-point |
| 2679 | arithmetic. |
| 2680 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2681 | .. [#] They must have since the parser can't tell the type of the operands. |
| 2682 | |
| 2683 | .. [#] To format only a tuple you should therefore provide a singleton tuple whose only |
| 2684 | element is the tuple to be formatted. |
| 2685 | |
| 2686 | .. [#] These numbers are fairly arbitrary. They are intended to avoid printing endless |
| 2687 | strings of meaningless digits without hampering correct use and without having |
| 2688 | to know the exact precision of floating point values on a particular machine. |
| 2689 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2690 | .. [#] The advantage of leaving the newline on is that returning an empty string is |
| 2691 | then an unambiguous EOF indication. It is also possible (in cases where it |
| 2692 | might matter, for example, if you want to make an exact copy of a file while |
| 2693 | scanning its lines) to tell whether the last line of a file ended in a newline |
| 2694 | or not (yes this happens!). |