| (-1)/(-2) is 0. Note that the result is a long integer if either operand is a |
| long integer, regardless of the numeric value. |
| |
| (2) |
| .. index:: |
| module: math |
| single: floor() (in module math) |
| single: ceil() (in module math) |
n | single: trunc() (in module math) |
| pair: numeric; conversions |
n | pair: C; language |
| |
n | Conversion from floating point to (long or plain) integer may round or truncate |
n | Conversion from floats using :func:`int` or :func:`long` truncates toward |
| as in C; see functions :func:`floor` and :func:`ceil` in the :mod:`math` module |
| zero like the related function, :func:`math.trunc`. Use the function |
| for well-defined conversions. |
| :func:`math.floor` to round downward and :func:`math.ceil` to round |
| upward. |
| |
| (3) |
n | See section :ref:`built-in-funcs`, "Built-in Functions," for a full description. |
n | See :ref:`built-in-funcs` for a full description. |
| |
| (4) |
| Complex floor division operator, modulo operator, and :func:`divmod`. |
| |
| .. deprecated:: 2.3 |
| Instead convert to float using :func:`abs` if appropriate. |
| |
| (5) |
| Also referred to as integer division. The resultant value is a whole integer, |
| though the result's type is not necessarily int. |
| |
n | (6) |
| float also accepts the strings "nan" and "inf" with an optional prefix "+" |
| or "-" for Not a Number (NaN) and positive or negative infinity. |
| |
| .. versionadded:: 2.6 |
| |
| (7) |
| Python defines ``pow(0, 0)`` and ``0 ** 0`` to be ``1``, as is common for |
| programming languages. |
| |
| All :class:`numbers.Real` types (:class:`int`, :class:`long`, and |
| :class:`float`) also include the following operations: |
| |
| +--------------------+------------------------------------+--------+ |
| | Operation | Result | Notes | |
| +====================+====================================+========+ |
| | ``math.trunc(x)`` | *x* truncated to Integral | | |
| +--------------------+------------------------------------+--------+ |
| | ``round(x[, n])`` | *x* rounded to n digits, | | |
| | | rounding half to even. If n is | | |
| | | omitted, it defaults to 0. | | |
| +--------------------+------------------------------------+--------+ |
| | ``math.floor(x)`` | the greatest integral float <= *x* | | |
| +--------------------+------------------------------------+--------+ |
| | ``math.ceil(x)`` | the least integral float >= *x* | | |
| +--------------------+------------------------------------+--------+ |
| |
| .. % XXXJH exceptions: overflow (when? what operations?) zerodivision |
| .. XXXJH exceptions: overflow (when? what operations?) zerodivision |
| |
| |
| .. _bitstring-ops: |
| |
| Bit-string Operations on Integer Types |
| -------------------------------------- |
| |
n | .. _bit-string operations: |
n | .. _bit-string-operations: |
| |
| Plain and long integer types support additional operations that make sense only |
| for bit-strings. Negative numbers are treated as their 2's complement value |
| (for long integers, this assumes a sufficiently large number of bits that no |
| overflow occurs during the operation). |
| |
n | The priorities of the binary bit-wise operations are all lower than the numeric |
n | The priorities of the binary bitwise operations are all lower than the numeric |
| operations and higher than the comparisons; the unary operation ``~`` has the |
| same priority as the other unary numeric operations (``+`` and ``-``). |
| |
n | This table lists the bit-string operations sorted in ascending priority |
n | This table lists the bit-string operations sorted in ascending priority: |
| (operations in the same box have the same priority): |
| |
| +------------+--------------------------------+----------+ |
| | Operation | Result | Notes | |
| +============+================================+==========+ |
| | ``x | y`` | bitwise :dfn:`or` of *x* and | | |
| | | *y* | | |
| +------------+--------------------------------+----------+ |
| | ``x ^ y`` | bitwise :dfn:`exclusive or` of | | |
| | | *x* and *y* | | |
| +------------+--------------------------------+----------+ |
| | ``x & y`` | bitwise :dfn:`and` of *x* and | | |
| | | *y* | | |
| +------------+--------------------------------+----------+ |
n | | ``x << n`` | *x* shifted left by *n* bits | (1), (2) | |
n | | ``x << n`` | *x* shifted left by *n* bits | (1)(2) | |
| +------------+--------------------------------+----------+ |
n | | ``x >> n`` | *x* shifted right by *n* bits | (1), (3) | |
n | | ``x >> n`` | *x* shifted right by *n* bits | (1)(3) | |
| +------------+--------------------------------+----------+ |
| | ``~x`` | the bits of *x* inverted | | |
| +------------+--------------------------------+----------+ |
| |
| .. index:: |
| triple: operations on; integer; types |
| pair: bit-string; operations |
| pair: shifting; operations |
| pair: masking; operations |
| |
| Notes: |
| |
| (1) |
| Negative shift counts are illegal and cause a :exc:`ValueError` to be raised. |
| |
| (2) |
n | A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)`` |
n | A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)``. A |
| without overflow check. |
| long integer is returned if the result exceeds the range of plain integers. |
| |
| (3) |
n | A right shift by *n* bits is equivalent to division by ``pow(2, n)`` without |
n | A right shift by *n* bits is equivalent to division by ``pow(2, n)``. |
| overflow check. |
| |
| |
| Additional Methods on Float |
| --------------------------- |
| |
| The float type has some additional methods. |
| |
| .. method:: float.as_integer_ratio() |
| |
| Return a pair of integers whose ratio is exactly equal to the |
| original float and with a positive denominator. Raises |
| :exc:`OverflowError` on infinities and a :exc:`ValueError` on |
| NaNs. |
| |
| .. versionadded:: 2.6 |
| |
| Two methods support conversion to |
| and from hexadecimal strings. Since Python's floats are stored |
| internally as binary numbers, converting a float to or from a |
| *decimal* string usually involves a small rounding error. In |
| contrast, hexadecimal strings allow exact representation and |
| specification of floating-point numbers. This can be useful when |
| debugging, and in numerical work. |
| |
| |
| .. method:: float.hex() |
| |
| Return a representation of a floating-point number as a hexadecimal |
| string. For finite floating-point numbers, this representation |
| will always include a leading ``0x`` and a trailing ``p`` and |
| exponent. |
| |
| .. versionadded:: 2.6 |
| |
| |
| .. method:: float.fromhex(s) |
| |
| Class method to return the float represented by a hexadecimal |
| string *s*. The string *s* may have leading and trailing |
| whitespace. |
| |
| .. versionadded:: 2.6 |
| |
| |
| Note that :meth:`float.hex` is an instance method, while |
| :meth:`float.fromhex` is a class method. |
| |
| A hexadecimal string takes the form:: |
| |
| [sign] ['0x'] integer ['.' fraction] ['p' exponent] |
| |
| where the optional ``sign`` may by either ``+`` or ``-``, ``integer`` |
| and ``fraction`` are strings of hexadecimal digits, and ``exponent`` |
| is a decimal integer with an optional leading sign. Case is not |
| significant, and there must be at least one hexadecimal digit in |
| either the integer or the fraction. This syntax is similar to the |
| syntax specified in section 6.4.4.2 of the C99 standard, and also to |
| the syntax used in Java 1.5 onwards. In particular, the output of |
| :meth:`float.hex` is usable as a hexadecimal floating-point literal in |
| C or Java code, and hexadecimal strings produced by C's ``%a`` format |
| character or Java's ``Double.toHexString`` are accepted by |
| :meth:`float.fromhex`. |
| |
| |
| Note that the exponent is written in decimal rather than hexadecimal, |
| and that it gives the power of 2 by which to multiply the coefficient. |
| For example, the hexadecimal string ``0x3.a7p10`` represents the |
| floating-point number ``(3 + 10./16 + 7./16**2) * 2.0**10``, or |
| ``3740.0``:: |
| |
| >>> float.fromhex('0x3.a7p10') |
| 3740.0 |
| |
| |
| Applying the reverse conversion to ``3740.0`` gives a different |
| hexadecimal string representing the same number:: |
| |
| >>> float.hex(3740.0) |
| '0x1.d380000000000p+11' |
| |
| |
| .. _typeiter: |
| |
| Iterator Types |
| ============== |
| |
| .. versionadded:: 2.2 |
| |
| .. versionadded:: 2.0 |
| |
| .. versionchanged:: 2.3 |
| Support for ``'xmlcharrefreplace'`` and ``'backslashreplace'`` and other error |
| handling schemes added. |
| |
| |
n | .. method:: string.endswith(suffix[, start[, end]]) |
n | .. method:: str.endswith(suffix[, start[, end]]) |
| |
| Return ``True`` if the string ends with the specified *suffix*, otherwise return |
| ``False``. *suffix* can also be a tuple of suffixes to look for. With optional |
| *start*, test beginning at that position. With optional *end*, stop comparing |
| at that position. |
| |
| .. versionchanged:: 2.5 |
| Accept tuples as *suffix*. |
| |
| |
n | .. method:: string.expandtabs([tabsize]) |
n | .. method:: str.expandtabs([tabsize]) |
| |
n | Return a copy of the string where all tab characters are expanded using spaces. |
n | Return a copy of the string where all tab characters are replaced by one or |
| more spaces, depending on the current column and the given tab size. The |
| column number is reset to zero after each newline occurring in the string. |
| If *tabsize* is not given, a tab size of ``8`` characters is assumed. |
| If *tabsize* is not given, a tab size of ``8`` characters is assumed. This |
| doesn't understand other non-printing characters or escape sequences. |
| |
| |
n | .. method:: string.find(sub[, start[, end]]) |
n | .. method:: str.find(sub[, start[, end]]) |
| |
| Return the lowest index in the string where substring *sub* is found, such that |
| *sub* is contained in the range [*start*, *end*]. Optional arguments *start* |
| and *end* are interpreted as in slice notation. Return ``-1`` if *sub* is not |
| found. |
| |
| |
n | .. method:: str.format(format_string, *args, **kwargs) |
| |
| Perform a string formatting operation. The *format_string* argument can |
| contain literal text or replacement fields delimited by braces ``{}``. Each |
| replacement field contains either the numeric index of a positional argument, |
| or the name of a keyword argument. Returns a copy of *format_string* where |
| each replacement field is replaced with the string value of the corresponding |
| argument. |
| |
| >>> "The sum of 1 + 2 is {0}".format(1+2) |
| 'The sum of 1 + 2 is 3' |
| |
| See :ref:`formatstrings` for a description of the various formatting options |
| that can be specified in format strings. |
| |
| This method of string formatting is the new standard in Python 3.0, and |
| should be preferred to the ``%`` formatting described in |
| :ref:`string-formatting` in new code. |
| |
| .. versionadded:: 2.6 |
| |
| |
| .. method:: string.index(sub[, start[, end]]) |
| .. method:: str.index(sub[, start[, end]]) |
| |
| Like :meth:`find`, but raise :exc:`ValueError` when the substring is not found. |
| |
| |
n | .. method:: string.isalnum() |
n | .. method:: str.isalnum() |
| |
| Return true if all characters in the string are alphanumeric and there is at |
| least one character, false otherwise. |
| |
| For 8-bit strings, this method is locale-dependent. |
| |
| |
n | .. method:: string.isalpha() |
n | .. method:: str.isalpha() |
| |
| Return true if all characters in the string are alphabetic and there is at least |
| one character, false otherwise. |
| |
| For 8-bit strings, this method is locale-dependent. |
| |
| |
n | .. method:: string.isdigit() |
n | .. method:: str.isdigit() |
| |
| Return true if all characters in the string are digits and there is at least one |
| character, false otherwise. |
| |
| For 8-bit strings, this method is locale-dependent. |
| |
| |
n | .. method:: string.islower() |
n | .. method:: str.islower() |
| |
| Return true if all cased characters in the string are lowercase and there is at |
| least one cased character, false otherwise. |
| |
| For 8-bit strings, this method is locale-dependent. |
| |
| |
n | .. method:: string.isspace() |
n | .. method:: str.isspace() |
| |
| Return true if there are only whitespace characters in the string and there is |
| at least one character, false otherwise. |
| |
| For 8-bit strings, this method is locale-dependent. |
| |
| |
n | .. method:: string.istitle() |
n | .. method:: str.istitle() |
| |
| Return true if the string is a titlecased string and there is at least one |
| character, for example uppercase characters may only follow uncased characters |
| and lowercase characters only cased ones. Return false otherwise. |
| |
| For 8-bit strings, this method is locale-dependent. |
| |
| |
n | .. method:: string.isupper() |
n | .. method:: str.isupper() |
| |
| Return true if all cased characters in the string are uppercase and there is at |
| least one cased character, false otherwise. |
| |
| For 8-bit strings, this method is locale-dependent. |
| |
| |
n | .. method:: string.join(seq) |
n | .. method:: str.join(seq) |
| |
| Return a string which is the concatenation of the strings in the sequence *seq*. |
| The separator between elements is the string providing this method. |
| |
| |
n | .. method:: string.ljust(width[, fillchar]) |
n | .. method:: str.ljust(width[, fillchar]) |
| |
| Return the string left justified in a string of length *width*. Padding is done |
| using the specified *fillchar* (default is a space). The original string is |
| returned if *width* is less than ``len(s)``. |
| |
| .. versionchanged:: 2.4 |
| Support for the *fillchar* argument. |
| |
| |
n | .. method:: string.lower() |
n | .. method:: str.lower() |
| |
| Return a copy of the string converted to lowercase. |
| |
| For 8-bit strings, this method is locale-dependent. |
| |
| |
n | .. method:: string.lstrip([chars]) |
n | .. method:: str.lstrip([chars]) |
| |
| Return a copy of the string with leading characters removed. The *chars* |
| argument is a string specifying the set of characters to be removed. If omitted |
| or ``None``, the *chars* argument defaults to removing whitespace. The *chars* |
n | argument is not a prefix; rather, all combinations of its values are stripped:: |
n | argument is not a prefix; rather, all combinations of its values are stripped: |
| |
| >>> ' spacious '.lstrip() |
| 'spacious ' |
| >>> 'www.example.com'.lstrip('cmowz.') |
| 'example.com' |
| |
| .. versionchanged:: 2.2.2 |
| Support for the *chars* argument. |
| |
| |
n | .. method:: string.partition(sep) |
n | .. method:: str.partition(sep) |
| |
| Split the string at the first occurrence of *sep*, and return a 3-tuple |
| containing the part before the separator, the separator itself, and the part |
| after the separator. If the separator is not found, return a 3-tuple containing |
| the string itself, followed by two empty strings. |
| |
| .. versionadded:: 2.5 |
| |
| |
n | .. method:: string.replace(old, new[, count]) |
n | .. method:: str.replace(old, new[, count]) |
| |
| Return a copy of the string with all occurrences of substring *old* replaced by |
| *new*. If the optional argument *count* is given, only the first *count* |
| occurrences are replaced. |
| |
| |
n | .. method:: string.rfind(sub [,start [,end]]) |
n | .. method:: str.rfind(sub [,start [,end]]) |
| |
| Return the highest index in the string where substring *sub* is found, such that |
| *sub* is contained within s[start,end]. Optional arguments *start* and *end* |
| are interpreted as in slice notation. Return ``-1`` on failure. |
| |
| |
n | .. method:: string.rindex(sub[, start[, end]]) |
n | .. method:: str.rindex(sub[, start[, end]]) |
| |
| Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not |
| found. |
| |
| |
n | .. method:: string.rjust(width[, fillchar]) |
n | .. method:: str.rjust(width[, fillchar]) |
| |
| Return the string right justified in a string of length *width*. Padding is done |
| using the specified *fillchar* (default is a space). The original string is |
| returned if *width* is less than ``len(s)``. |
| |
| .. versionchanged:: 2.4 |
| Support for the *fillchar* argument. |
| |
| |
n | .. method:: string.rpartition(sep) |
n | .. method:: str.rpartition(sep) |
| |
| Split the string at the last occurrence of *sep*, and return a 3-tuple |
| containing the part before the separator, the separator itself, and the part |
| after the separator. If the separator is not found, return a 3-tuple containing |
| two empty strings, followed by the string itself. |
| |
| .. versionadded:: 2.5 |
| |
| |
n | .. method:: string.rsplit([sep [,maxsplit]]) |
n | .. method:: str.rsplit([sep [,maxsplit]]) |
| |
| Return a list of the words in the string, using *sep* as the delimiter string. |
| If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost* |
| ones. If *sep* is not specified or ``None``, any whitespace string is a |
| separator. Except for splitting from the right, :meth:`rsplit` behaves like |
| :meth:`split` which is described in detail below. |
| |
| .. versionadded:: 2.4 |
| |
| |
n | .. method:: string.rstrip([chars]) |
n | .. method:: str.rstrip([chars]) |
| |
| Return a copy of the string with trailing characters removed. The *chars* |
| argument is a string specifying the set of characters to be removed. If omitted |
| or ``None``, the *chars* argument defaults to removing whitespace. The *chars* |
n | argument is not a suffix; rather, all combinations of its values are stripped:: |
n | argument is not a suffix; rather, all combinations of its values are stripped: |
| |
| >>> ' spacious '.rstrip() |
| ' spacious' |
| >>> 'mississippi'.rstrip('ipz') |
| 'mississ' |
| |
| .. versionchanged:: 2.2.2 |
| Support for the *chars* argument. |
| |
| |
n | .. method:: string.split([sep [,maxsplit]]) |
n | .. method:: str.split([sep[, maxsplit]]) |
| |
n | Return a list of the words in the string, using *sep* as the delimiter string. |
n | Return a list of the words in the string, using *sep* as the delimiter |
| If *maxsplit* is given, at most *maxsplit* splits are done. (thus, the list will |
| string. If *maxsplit* is given, at most *maxsplit* splits are done (thus, |
| have at most ``maxsplit+1`` elements). If *maxsplit* is not specified, then |
| the list will have at most ``maxsplit+1`` elements). If *maxsplit* is not |
| there is no limit on the number of splits (all possible splits are made). |
| specified, then there is no limit on the number of splits (all possible |
| Consecutive delimiters are not grouped together and are deemed to delimit empty |
| splits are made). |
| |
| If *sep* is given, consecutive delimiters are not grouped together and are |
| deemed to delimit empty strings (for example, ``'1,,2'.split(',')`` returns |
| ``['1', '', '2']``). The *sep* argument may consist of multiple characters |
| strings (for example, ``'1,,2'.split(',')`` returns ``['1', '', '2']``). The |
| (for example, ``'1<>2<>3'.split('<>')`` returns ``['1', '2', '3']``). |
| *sep* argument may consist of multiple characters (for example, ``'1, 2, |
| Splitting an empty string with a specified separator returns ``['']``. |
| 3'.split(', ')`` returns ``['1', '2', '3']``). Splitting an empty string with a |
| specified separator returns ``['']``. |
| |
| If *sep* is not specified or is ``None``, a different splitting algorithm is |
n | applied. First, whitespace characters (spaces, tabs, newlines, returns, and |
n | applied: runs of consecutive whitespace are regarded as a single separator, |
| formfeeds) are stripped from both ends. Then, words are separated by arbitrary |
| and the result will contain no empty strings at the start or end if the |
| length strings of whitespace characters. Consecutive whitespace delimiters are |
| string has leading or trailing whitespace. Consequently, splitting an empty |
| treated as a single delimiter (``'1 2 3'.split()`` returns ``['1', '2', |
| string or a string consisting of just whitespace with a ``None`` separator |
| '3']``). Splitting an empty string or a string consisting of just whitespace |
| returns ``[]``. |
| returns an empty list. |
| |
n | For example, ``' 1 2 3 '.split()`` returns ``['1', '2', '3']``, and |
| ``' 1 2 3 '.split(None, 1)`` returns ``['1', '2 3 ']``. |
| |
n | |
| .. method:: string.splitlines([keepends]) |
| .. method:: str.splitlines([keepends]) |
| |
| Return a list of the lines in the string, breaking at line boundaries. Line |
| breaks are not included in the resulting list unless *keepends* is given and |
| true. |
| |
| |
n | .. method:: string.startswith(prefix[, start[, end]]) |
n | .. method:: str.startswith(prefix[, start[, end]]) |
| |
| Return ``True`` if string starts with the *prefix*, otherwise return ``False``. |
n | *prefix* can also be a tuple of suffixes to look for. With optional *start*, |
n | *prefix* can also be a tuple of prefixes to look for. With optional *start*, |
| test string beginning at that position. With optional *end*, stop comparing |
| string at that position. |
| |
| .. versionchanged:: 2.5 |
| Accept tuples as *prefix*. |
| |
| |
n | .. method:: string.strip([chars]) |
n | .. method:: str.strip([chars]) |
| |
| Return a copy of the string with the leading and trailing characters removed. |
| The *chars* argument is a string specifying the set of characters to be removed. |
| If omitted or ``None``, the *chars* argument defaults to removing whitespace. |
| The *chars* argument is not a prefix or suffix; rather, all combinations of its |
n | values are stripped:: |
n | values are stripped: |
| |
| >>> ' spacious '.strip() |
| 'spacious' |
| >>> 'www.example.com'.strip('cmowz.') |
| 'example' |
| |
| .. versionchanged:: 2.2.2 |
| Support for the *chars* argument. |
| |
| |
n | .. method:: string.swapcase() |
n | .. method:: str.swapcase() |
| |
| Return a copy of the string with uppercase characters converted to lowercase and |
| vice versa. |
| |
| For 8-bit strings, this method is locale-dependent. |
| |
| |
n | .. method:: string.title() |
n | .. method:: str.title() |
| |
| Return a titlecased version of the string: words start with uppercase |
| characters, all remaining cased characters are lowercase. |
| |
| For 8-bit strings, this method is locale-dependent. |
| |
| |
n | .. method:: string.translate(table[, deletechars]) |
n | .. method:: str.translate(table[, deletechars]) |
| |
| Return a copy of the string where all characters occurring in the optional |
| argument *deletechars* are removed, and the remaining characters have been |
| mapped through the given translation table, which must be a string of length |
| 256. |
n | |
| You can use the :func:`maketrans` helper function in the :mod:`string` module to |
| create a translation table. For string objects, set the *table* argument to |
| ``None`` for translations that only delete characters: |
| |
| >>> 'read this short text'.translate(None, 'aeiou') |
| 'rd ths shrt txt' |
| |
| .. versionadded:: 2.6 |
| Support for a ``None`` *table* argument. |
| |
| For Unicode objects, the :meth:`translate` method does not accept the optional |
| *deletechars* argument. Instead, it returns a copy of the *s* where all |
| characters have been mapped through the given translation table which must be a |
| mapping of Unicode ordinals to Unicode ordinals, Unicode strings or ``None``. |
| Unmapped characters are left untouched. Characters mapped to ``None`` are |
| deleted. Note, a more flexible approach is to create a custom character mapping |
| codec using the :mod:`codecs` module (see :mod:`encodings.cp1251` for an |
| example). |
| |
| |
n | .. method:: string.upper() |
n | .. method:: str.upper() |
| |
| Return a copy of the string converted to uppercase. |
| |
| For 8-bit strings, this method is locale-dependent. |
| |
| |
n | .. method:: string.zfill(width) |
n | .. method:: str.zfill(width) |
| |
n | Return the numeric string left filled with zeros in a string of length *width*. |
n | Return the numeric string left filled with zeros in a string of length |
| *width*. A sign prefix is handled correctly. The original string is |
| The original string is returned if *width* is less than ``len(s)``. |
| returned if *width* is less than ``len(s)``. |
| |
| |
| .. versionadded:: 2.2.2 |
| |
n | The following methods are present only on unicode objects: |
| |
n | .. _typesseq-strings: |
n | .. method:: unicode.isnumeric() |
| |
| Return ``True`` if there are only numeric characters in S, ``False`` |
| otherwise. Numeric characters include digit characters, and all characters |
| that have the Unicode numeric value property, e.g. U+2155, |
| VULGAR FRACTION ONE FIFTH. |
| |
| .. method:: unicode.isdecimal() |
| |
| Return ``True`` if there are only decimal characters in S, ``False`` |
| otherwise. Decimal characters include digit characters, and all characters |
| that that can be used to form decimal-radix numbers, e.g. U+0660, |
| ARABIC-INDIC DIGIT ZERO. |
| |
| |
| .. _string-formatting: |
| |
| String Formatting Operations |
| ---------------------------- |
| |
| .. index:: |
| single: formatting, string (%) |
| single: interpolation, string (%) |
| single: string; formatting |
| |
| #. Length modifier (optional). |
| |
| #. Conversion type. |
| |
| When the right argument is a dictionary (or other mapping type), then the |
| formats in the string *must* include a parenthesised mapping key into that |
| dictionary inserted immediately after the ``'%'`` character. The mapping key |
n | selects the value to be formatted from the mapping. For example:: |
n | selects the value to be formatted from the mapping. For example: |
| |
| >>> print '%(language)s has %(#)03d quote types.' % \ |
n | {'language': "Python", "#": 2} |
n | ... {'language': "Python", "#": 2} |
| Python has 002 quote types. |
| |
| In this case no ``*`` specifiers may occur in a format (since they require a |
| sequential parameter list). |
| |
| The conversion flag characters are: |
| |
n | +---------+-----------------------------------------------+ |
n | +---------+---------------------------------------------------------------------+ |
| | Flag | Meaning | |
| | Flag | Meaning | |
| +=========+===============================================+ |
| +=========+=====================================================================+ |
| | ``'#'`` | The value conversion will use the "alternate | |
| | ``'#'`` | The value conversion will use the "alternate form" (where defined | |
| | | form" (where defined below). | |
| | | below). | |
| +---------+-----------------------------------------------+ |
| +---------+---------------------------------------------------------------------+ |
| | ``'0'`` | The conversion will be zero padded for | |
| | ``'0'`` | The conversion will be zero padded for numeric values. | |
| | | numeric values. | |
| +---------+-----------------------------------------------+ |
| +---------+---------------------------------------------------------------------+ |
| | ``'-'`` | The converted value is left adjusted | |
| | ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` | |
| | | (overrides the ``'0'`` conversion if both are | |
| | | given). | |
| | | conversion if both are given). | |
| +---------+-----------------------------------------------+ |
| +---------+---------------------------------------------------------------------+ |
| | ``' '`` | (a space) A blank should be left before a | |
| | ``' '`` | (a space) A blank should be left before a positive number (or empty | |
| | | positive number (or empty string) produced by | |
| | | a signed conversion. | |
| | | string) produced by a signed conversion. | |
| +---------+-----------------------------------------------+ |
| +---------+---------------------------------------------------------------------+ |
| | ``'+'`` | A sign character (``'+'`` or ``'-'``) will | |
| | ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion | |
| | | precede the conversion (overrides a "space" | |
| | | flag). | |
| | | (overrides a "space" flag). | |
| +---------+-----------------------------------------------+ |
| +---------+---------------------------------------------------------------------+ |
| |
| A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it |
n | is not necessary for Python. |
n | is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``. |
| |
| The conversion types are: |
| |
n | +------------+---------------------------------+-------+ |
n | +------------+-----------------------------------------------------+-------+ |
| | Conversion | Meaning | Notes | |
| | Conversion | Meaning | Notes | |
| +============+=================================+=======+ |
| +============+=====================================================+=======+ |
| | ``'d'`` | Signed integer decimal. | | |
| | ``'d'`` | Signed integer decimal. | | |
| +------------+---------------------------------+-------+ |
| +------------+-----------------------------------------------------+-------+ |
| | ``'i'`` | Signed integer decimal. | | |
| | ``'i'`` | Signed integer decimal. | | |
| +------------+---------------------------------+-------+ |
| +------------+-----------------------------------------------------+-------+ |
| | ``'o'`` | Unsigned octal. | \(1) | |
| | ``'o'`` | Signed octal value. | \(1) | |
| +------------+---------------------------------+-------+ |
| +------------+-----------------------------------------------------+-------+ |
| | ``'u'`` | Unsigned decimal. | | |
| | ``'u'`` | Obsolete type -- it is identical to ``'d'``. | \(7) | |
| +------------+---------------------------------+-------+ |
| +------------+-----------------------------------------------------+-------+ |
| | ``'x'`` | Unsigned hexadecimal | \(2) | |
| | ``'x'`` | Signed hexadecimal (lowercase). | \(2) | |
| | | (lowercase). | | |
| +------------+---------------------------------+-------+ |
| +------------+-----------------------------------------------------+-------+ |
| | ``'X'`` | Unsigned hexadecimal | \(2) | |
| | ``'X'`` | Signed hexadecimal (uppercase). | \(2) | |
| | | (uppercase). | | |
| +------------+---------------------------------+-------+ |
| +------------+-----------------------------------------------------+-------+ |
| | ``'e'`` | Floating point exponential | \(3) | |
| | ``'e'`` | Floating point exponential format (lowercase). | \(3) | |
| | | format (lowercase). | | |
| +------------+---------------------------------+-------+ |
| +------------+-----------------------------------------------------+-------+ |
| | ``'E'`` | Floating point exponential | \(3) | |
| | ``'E'`` | Floating point exponential format (uppercase). | \(3) | |
| | | format (uppercase). | | |
| +------------+---------------------------------+-------+ |
| +------------+-----------------------------------------------------+-------+ |
| | ``'f'`` | Floating point decimal format. | \(3) | |
| | ``'f'`` | Floating point decimal format. | \(3) | |
| +------------+---------------------------------+-------+ |
| +------------+-----------------------------------------------------+-------+ |
| | ``'F'`` | Floating point decimal format. | \(3) | |
| | ``'F'`` | Floating point decimal format. | \(3) | |
| +------------+---------------------------------+-------+ |
| +------------+-----------------------------------------------------+-------+ |
| | ``'g'`` | Floating point format. Uses | \(4) | |
| | ``'g'`` | Floating point format. Uses lowercase exponential | \(4) | |
| | | exponential format if exponent | | |
| | | is greater than -4 or less than | | |
| | | format if exponent is less than -4 or not less than | | |
| | | precision, decimal format | | |
| | | precision, decimal format otherwise. | | |
| | | otherwise. | | |
| +------------+---------------------------------+-------+ |
| +------------+-----------------------------------------------------+-------+ |
| | ``'G'`` | Floating point format. Uses | \(4) | |
| | ``'G'`` | Floating point format. Uses uppercase exponential | \(4) | |
| | | exponential format if exponent | | |
| | | is greater than -4 or less than | | |
| | | format if exponent is less than -4 or not less than | | |
| | | precision, decimal format | | |
| | | precision, decimal format otherwise. | | |
| | | otherwise. | | |
| +------------+---------------------------------+-------+ |
| +------------+-----------------------------------------------------+-------+ |
| | ``'c'`` | Single character (accepts | | |
| | ``'c'`` | Single character (accepts integer or single | | |
| | | integer or single character | | |
| | | string). | | |
| | | character string). | | |
| +------------+---------------------------------+-------+ |
| +------------+-----------------------------------------------------+-------+ |
| | ``'r'`` | String (converts any python | \(5) | |
| | ``'r'`` | String (converts any python object using | \(5) | |
| | | object using :func:`repr`). | | |
| | | :func:`repr`). | | |
| +------------+---------------------------------+-------+ |
| +------------+-----------------------------------------------------+-------+ |
| | ``'s'`` | String (converts any python | \(6) | |
| | ``'s'`` | String (converts any python object using | \(6) | |
| | | object using :func:`str`). | | |
| | | :func:`str`). | | |
| +------------+---------------------------------+-------+ |
| +------------+-----------------------------------------------------+-------+ |
| | ``'%'`` | No argument is converted, | | |
| | ``'%'`` | No argument is converted, results in a ``'%'`` | | |
| | | results in a ``'%'`` character | | |
| | | in the result. | | |
| | | character in the result. | | |
| +------------+---------------------------------+-------+ |
| +------------+-----------------------------------------------------+-------+ |
| |
| Notes: |
| |
| (1) |
n | The alternate form causes a leading zero (``'0'``) to be inserted between left- |
n | The alternate form causes a leading zero (``'0'``) to be inserted between |
| hand padding and the formatting of the number if the leading character of the |
| left-hand padding and the formatting of the number if the leading character |
| result is not already a zero. |
| of the result is not already a zero. |
| |
| (2) |
| The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether |
| the ``'x'`` or ``'X'`` format was used) to be inserted between left-hand padding |
| and the formatting of the number if the leading character of the result is not |
| already a zero. |
| |
| (3) |
| |
| .. _types-set: |
| |
| Set Types --- :class:`set`, :class:`frozenset` |
| ============================================== |
| |
| .. index:: object: set |
| |
n | A :dfn:`set` object is an unordered collection of immutable values. Common uses |
n | A :dfn:`set` object is an unordered collection of distinct :term:`hashable` objects. |
| include membership testing, removing duplicates from a sequence, and computing |
| Common uses include membership testing, removing duplicates from a sequence, and |
| mathematical operations such as intersection, union, difference, and symmetric |
| computing mathematical operations such as intersection, union, difference, and |
| difference. |
| symmetric difference. |
| (For other containers see the built in :class:`dict`, :class:`list`, |
| and :class:`tuple` classes, and the :mod:`collections` module.) |
| |
| |
| .. versionadded:: 2.4 |
| |
| Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in |
| set``. Being an unordered collection, sets do not record element position or |
| order of insertion. Accordingly, sets do not support indexing, slicing, or |
| other sequence-like behavior. |
| |
| There are currently two builtin set types, :class:`set` and :class:`frozenset`. |
| The :class:`set` type is mutable --- the contents can be changed using methods |
| like :meth:`add` and :meth:`remove`. Since it is mutable, it has no hash value |
| and cannot be used as either a dictionary key or as an element of another set. |
n | The :class:`frozenset` type is immutable and hashable --- its contents cannot be |
n | The :class:`frozenset` type is immutable and :term:`hashable` --- its contents cannot be |
| altered after is created; however, it can be used as a dictionary key or as an |
| altered after it is created; it can therefore be used as a dictionary key or as |
| element of another set. |
| an element of another set. |
| |
n | The constructors for both classes work the same: |
| |
| .. class:: set([iterable]) |
| frozenset([iterable]) |
| |
| Return a new set or frozenset object whose elements are taken from |
| *iterable*. The elements of a set must be hashable. To represent sets of |
| sets, the inner sets must be :class:`frozenset` objects. If *iterable* is |
| not specified, a new empty set is returned. |
| |
| Instances of :class:`set` and :class:`frozenset` provide the following |
| Instances of :class:`set` and :class:`frozenset` provide the following |
| operations: |
| operations: |
| |
n | +-------------------------------+------------+---------------------------------+ |
n | .. describe:: len(s) |
| | Operation | Equivalent | Result | |
| +===============================+============+=================================+ |
| | ``len(s)`` | | cardinality of set *s* | |
| +-------------------------------+------------+---------------------------------+ |
| | ``x in s`` | | test *x* for membership in *s* | |
| +-------------------------------+------------+---------------------------------+ |
| | ``x not in s`` | | test *x* for non-membership in | |
| | | | *s* | |
| +-------------------------------+------------+---------------------------------+ |
| | ``s.issubset(t)`` | ``s <= t`` | test whether every element in | |
| | | | *s* is in *t* | |
| +-------------------------------+------------+---------------------------------+ |
| | ``s.issuperset(t)`` | ``s >= t`` | test whether every element in | |
| | | | *t* is in *s* | |
| +-------------------------------+------------+---------------------------------+ |
| | ``s.union(t)`` | *s* \| *t* | new set with elements from both | |
| | | | *s* and *t* | |
| +-------------------------------+------------+---------------------------------+ |
| | ``s.intersection(t)`` | *s* & *t* | new set with elements common to | |
| | | | *s* and *t* | |
| +-------------------------------+------------+---------------------------------+ |
| | ``s.difference(t)`` | *s* - *t* | new set with elements in *s* | |
| | | | but not in *t* | |
| +-------------------------------+------------+---------------------------------+ |
| | ``s.symmetric_difference(t)`` | *s* ^ *t* | new set with elements in either | |
| | | | *s* or *t* but not both | |
| +-------------------------------+------------+---------------------------------+ |
| | ``s.copy()`` | | new set with a shallow copy of | |
| | | | *s* | |
| +-------------------------------+------------+---------------------------------+ |
| |
n | Return the cardinality of set *s*. |
| |
| .. describe:: x in s |
| |
| Test *x* for membership in *s*. |
| |
| .. describe:: x not in s |
| |
| Test *x* for non-membership in *s*. |
| |
| .. method:: isdisjoint(other) |
| |
| Return True if the set has no elements in common with *other*. Sets are |
| disjoint if and only if their intersection is the empty set. |
| |
| .. versionadded:: 2.6 |
| |
| .. method:: issubset(other) |
| set <= other |
| |
| Test whether every element in the set is in *other*. |
| |
| .. method:: set < other |
| |
| Test whether the set is a true subset of *other*, that is, |
| ``set <= other and set != other``. |
| |
| .. method:: issuperset(other) |
| set >= other |
| |
| Test whether every element in *other* is in the set. |
| |
| .. method:: set > other |
| |
| Test whether the set is a true superset of *other*, that is, ``set >= |
| other and set != other``. |
| |
| .. method:: union(other, ...) |
| set | other | ... |
| |
| Return a new set with elements from the set and all others. |
| |
| .. versionchanged:: 2.6 |
| Accepts multiple input iterables. |
| |
| .. method:: intersection(other, ...) |
| set & other & ... |
| |
| Return a new set with elements common to the set and all others. |
| |
| .. versionchanged:: 2.6 |
| Accepts multiple input iterables. |
| |
| .. method:: difference(other, ...) |
| set - other - ... |
| |
| Return a new set with elements in the set that are not in the others. |
| |
| .. versionchanged:: 2.6 |
| Accepts multiple input iterables. |
| |
| .. method:: symmetric_difference(other) |
| set ^ other |
| |
| Return a new set with elements in either the set or *other* but not both. |
| |
| .. method:: copy() |
| |
| Return a new set with a shallow copy of *s*. |
| |
| |
| Note, the non-operator versions of :meth:`union`, :meth:`intersection`, |
| Note, the non-operator versions of :meth:`union`, :meth:`intersection`, |
| :meth:`difference`, and :meth:`symmetric_difference`, :meth:`issubset`, and |
| :meth:`difference`, and :meth:`symmetric_difference`, :meth:`issubset`, and |
| :meth:`issuperset` methods will accept any iterable as an argument. In |
| :meth:`issuperset` methods will accept any iterable as an argument. In |
| contrast, their operator based counterparts require their arguments to be sets. |
| contrast, their operator based counterparts require their arguments to be |
| This precludes error-prone constructions like ``set('abc') & 'cbs'`` in favor of |
| sets. This precludes error-prone constructions like ``set('abc') & 'cbs'`` |
| the more readable ``set('abc').intersection('cbs')``. |
| in favor of the more readable ``set('abc').intersection('cbs')``. |
| |
n | Both :class:`set` and :class:`frozenset` support set to set comparisons. Two |
n | Both :class:`set` and :class:`frozenset` support set to set comparisons. Two |
| sets are equal if and only if every element of each set is contained in the |
| sets are equal if and only if every element of each set is contained in the |
| other (each is a subset of the other). A set is less than another set if and |
| other (each is a subset of the other). A set is less than another set if and |
| only if the first set is a proper subset of the second set (is a subset, but is |
| only if the first set is a proper subset of the second set (is a subset, but |
| not equal). A set is greater than another set if and only if the first set is a |
| is not equal). A set is greater than another set if and only if the first set |
| proper superset of the second set (is a superset, but is not equal). |
| is a proper superset of the second set (is a superset, but is not equal). |
| |
n | Instances of :class:`set` are compared to instances of :class:`frozenset` based |
n | Instances of :class:`set` are compared to instances of :class:`frozenset` |
| on their members. For example, ``set('abc') == frozenset('abc')`` returns |
| based on their members. For example, ``set('abc') == frozenset('abc')`` |
| ``True``. |
| returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``. |
| |
n | The subset and equality comparisons do not generalize to a complete ordering |
n | The subset and equality comparisons do not generalize to a complete ordering |
| function. For example, any two disjoint sets are not equal and are not subsets |
| function. For example, any two disjoint sets are not equal and are not |
| of each other, so *all* of the following return ``False``: ``a<b``, ``a==b``, |
| subsets of each other, so *all* of the following return ``False``: ``a<b``, |
| or ``a>b``. Accordingly, sets do not implement the :meth:`__cmp__` method. |
| ``a==b``, or ``a>b``. Accordingly, sets do not implement the :meth:`__cmp__` |
| method. |
| |
n | Since sets only define partial ordering (subset relationships), the output of |
n | Since sets only define partial ordering (subset relationships), the output of |
| the :meth:`list.sort` method is undefined for lists of sets. |
| the :meth:`list.sort` method is undefined for lists of sets. |
| |
n | Set elements are like dictionary keys; they need to define both :meth:`__hash__` |
n | Set elements, like dictionary keys, must be :term:`hashable`. |
| and :meth:`__eq__` methods. |
| |
n | Binary operations that mix :class:`set` instances with :class:`frozenset` return |
n | Binary operations that mix :class:`set` instances with :class:`frozenset` |
| the type of the first operand. For example: ``frozenset('ab') | set('bc')`` |
| return the type of the first operand. For example: ``frozenset('ab') | |
| returns an instance of :class:`frozenset`. |
| set('bc')`` returns an instance of :class:`frozenset`. |
| |
n | The following table lists operations available for :class:`set` that do not |
n | The following table lists operations available for :class:`set` that do not |
| apply to immutable instances of :class:`frozenset`: |
| apply to immutable instances of :class:`frozenset`: |
| |
n | +--------------------------------------+-------------+---------------------------------+ |
n | .. method:: update(other, ...) |
| | Operation | Equivalent | Result | |
| set |= other | ... |
| +======================================+=============+=================================+ |
| | ``s.update(t)`` | *s* \|= *t* | update set *s*, adding elements | |
| | | | from *t* | |
| +--------------------------------------+-------------+---------------------------------+ |
| | ``s.intersection_update(t)`` | *s* &= *t* | update set *s*, keeping only | |
| | | | elements found in both *s* and | |
| | | | *t* | |
| +--------------------------------------+-------------+---------------------------------+ |
| | ``s.difference_update(t)`` | *s* -= *t* | update set *s*, removing | |
| | | | elements found in *t* | |
| +--------------------------------------+-------------+---------------------------------+ |
| | ``s.symmetric_difference_update(t)`` | *s* ^= *t* | update set *s*, keeping only | |
| | | | elements found in either *s* or | |
| | | | *t* but not in both | |
| +--------------------------------------+-------------+---------------------------------+ |
| | ``s.add(x)`` | | add element *x* to set *s* | |
| +--------------------------------------+-------------+---------------------------------+ |
| | ``s.remove(x)`` | | remove *x* from set *s*; raises | |
| | | | :exc:`KeyError` if not present | |
| +--------------------------------------+-------------+---------------------------------+ |
| | ``s.discard(x)`` | | removes *x* from set *s* if | |
| | | | present | |
| +--------------------------------------+-------------+---------------------------------+ |
| | ``s.pop()`` | | remove and return an arbitrary | |
| | | | element from *s*; raises | |
| | | | :exc:`KeyError` if empty | |
| +--------------------------------------+-------------+---------------------------------+ |
| | ``s.clear()`` | | remove all elements from set | |
| | | | *s* | |
| +--------------------------------------+-------------+---------------------------------+ |
| |
n | Update the set, adding elements from *other*. |
| |
| .. versionchanged:: 2.6 |
| Accepts multiple input iterables. |
| |
| .. method:: intersection_update(other, ...) |
| set &= other & ... |
| |
| Update the set, keeping only elements found in it and *other*. |
| |
| .. versionchanged:: 2.6 |
| Accepts multiple input iterables. |
| |
| .. method:: difference_update(other, ...) |
| set -= other | ... |
| |
| Update the set, removing elements found in others. |
| |
| .. versionchanged:: 2.6 |
| Accepts multiple input iterables. |
| |
| .. method:: symmetric_difference_update(other) |
| set ^= other |
| |
| Update the set, keeping only elements found in either set, but not in both. |
| |
| .. method:: add(elem) |
| |
| Add element *elem* to the set. |
| |
| .. method:: remove(elem) |
| |
| Remove element *elem* from the set. Raises :exc:`KeyError` if *elem* is |
| not contained in the set. |
| |
| .. method:: discard(elem) |
| |
| Remove element *elem* from the set if it is present. |
| |
| .. method:: pop() |
| |
| Remove and return an arbitrary element from the set. Raises |
| :exc:`KeyError` if the set is empty. |
| |
| .. method:: clear() |
| |
| Remove all elements from the set. |
| |
| |
| Note, the non-operator versions of the :meth:`update`, |
| Note, the non-operator versions of the :meth:`update`, |
| :meth:`intersection_update`, :meth:`difference_update`, and |
| :meth:`intersection_update`, :meth:`difference_update`, and |
| :meth:`symmetric_difference_update` methods will accept any iterable as an |
| :meth:`symmetric_difference_update` methods will accept any iterable as an |
| argument. |
| argument. |
| |
n | The design of the set types was based on lessons learned from the :mod:`sets` |
n | Note, the *elem* argument to the :meth:`__contains__`, :meth:`remove`, and |
| module. |
| :meth:`discard` methods may be a set. To support searching for an equivalent |
| frozenset, the *elem* set is temporarily mutated during the search and then |
| restored. During the search, the *elem* set should not be read or mutated |
| since it does not have a meaningful value. |
| |
| |
| .. seealso:: |
| |
n | `Comparison to the built-in set types <comparison-to-builtin-set.html>`_ |
n | :ref:`comparison-to-builtin-set` |
| Differences between the :mod:`sets` module and the built-in set types. |
| |
| |
| .. _typesmapping: |
| |
| Mapping Types --- :class:`dict` |
| =============================== |
| |
| .. index:: |
| object: mapping |
| object: dictionary |
n | |
| A :dfn:`mapping` object maps immutable values to arbitrary objects. Mappings |
| are mutable objects. There is currently only one standard mapping type, the |
| :dfn:`dictionary`. A dictionary's keys are almost arbitrary values. Only |
| values containing lists, dictionaries or other mutable types (that are compared |
| by value rather than by object identity) may not be used as keys. Numeric types |
| used for keys obey the normal rules for numeric comparison: if two numbers |
| compare equal (such as ``1`` and ``1.0``) then they can be used interchangeably |
| to index the same dictionary entry. |
| |
| Dictionaries are created by placing a comma-separated list of ``key: value`` |
| pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098: |
| 'jack', 4127: 'sjoerd'}``. |
| |
| .. index:: |
| triple: operations on; mapping; types |
| triple: operations on; dictionary; type |
| statement: del |
| builtin: len |
n | single: clear() (dictionary method) |
| single: copy() (dictionary method) |
| single: has_key() (dictionary method) |
| single: fromkeys() (dictionary method) |
| single: items() (dictionary method) |
| single: keys() (dictionary method) |
| single: update() (dictionary method) |
| single: values() (dictionary method) |
| single: get() (dictionary method) |
| single: setdefault() (dictionary method) |
| single: pop() (dictionary method) |
| single: popitem() (dictionary method) |
| single: iteritems() (dictionary method) |
| single: iterkeys() (dictionary method) |
| single: itervalues() (dictionary method) |
| |
n | The following operations are defined on mappings (where *a* and *b* are |
n | A :dfn:`mapping` object maps :term:`hashable` values to arbitrary objects. |
| mappings, *k* is a key, and *v* and *x* are arbitrary objects): |
| Mappings are mutable objects. There is currently only one standard mapping |
| type, the :dfn:`dictionary`. (For other containers see the built in |
| :class:`list`, :class:`set`, and :class:`tuple` classes, and the |
| :mod:`collections` module.) |
| |
n | +--------------------------------+---------------------------------+-----------+ |
n | A dictionary's keys are *almost* arbitrary values. Values that are not |
| | Operation | Result | Notes | |
| :term:`hashable`, that is, values containing lists, dictionaries or other |
| +================================+=================================+===========+ |
| mutable types (that are compared by value rather than by object identity) may |
| | ``len(a)`` | the number of items in *a* | | |
| not be used as keys. Numeric types used for keys obey the normal rules for |
| +--------------------------------+---------------------------------+-----------+ |
| numeric comparison: if two numbers compare equal (such as ``1`` and ``1.0``) |
| | ``a[k]`` | the item of *a* with key *k* | (1), (10) | |
| then they can be used interchangeably to index the same dictionary entry. (Note |
| +--------------------------------+---------------------------------+-----------+ |
| however, that since computers store floating-point numbers as approximations it |
| | ``a[k] = v`` | set ``a[k]`` to *v* | | |
| is usually unwise to use them as dictionary keys.) |
| +--------------------------------+---------------------------------+-----------+ |
| | ``del a[k]`` | remove ``a[k]`` from *a* | \(1) | |
| +--------------------------------+---------------------------------+-----------+ |
| | ``a.clear()`` | remove all items from ``a`` | | |
| +--------------------------------+---------------------------------+-----------+ |
| | ``a.copy()`` | a (shallow) copy of ``a`` | | |
| +--------------------------------+---------------------------------+-----------+ |
| | ``k in a`` | ``True`` if *a* has a key *k*, | \(2) | |
| | | else ``False`` | | |
| +--------------------------------+---------------------------------+-----------+ |
| | ``k not in a`` | Equivalent to ``not`` *k* in | \(2) | |
| | | *a* | | |
| +--------------------------------+---------------------------------+-----------+ |
| | ``a.has_key(k)`` | Equivalent to *k* ``in`` *a*, | | |
| | | use that form in new code | | |
| +--------------------------------+---------------------------------+-----------+ |
| | ``a.items()`` | a copy of *a*'s list of (*key*, | \(3) | |
| | | *value*) pairs | | |
| +--------------------------------+---------------------------------+-----------+ |
| | ``a.keys()`` | a copy of *a*'s list of keys | \(3) | |
| +--------------------------------+---------------------------------+-----------+ |
| | ``a.update([*b*])`` | updates (and overwrites) | \(9) | |
| | | key/value pairs from *b* | | |
| +--------------------------------+---------------------------------+-----------+ |
| | ``a.fromkeys(seq[, *value*])`` | Creates a new dictionary with | \(7) | |
| | | keys from *seq* and values set | | |
| | | to *value* | | |
| +--------------------------------+---------------------------------+-----------+ |
| | ``a.values()`` | a copy of *a*'s list of values | \(3) | |
| +--------------------------------+---------------------------------+-----------+ |
| | ``a.get(k[, *x*])`` | ``a[k]`` if ``k in a``, else | \(4) | |
| | | *x* | | |
| +--------------------------------+---------------------------------+-----------+ |
| | ``a.setdefault(k[, *x*])`` | ``a[k]`` if ``k in a``, else | \(5) | |
| | | *x* (also setting it) | | |
| +--------------------------------+---------------------------------+-----------+ |
| | ``a.pop(k[, *x*])`` | ``a[k]`` if ``k in a``, else | \(8) | |
| | | *x* (and remove k) | | |
| +--------------------------------+---------------------------------+-----------+ |
| | ``a.popitem()`` | remove and return an arbitrary | \(6) | |
| | | (*key*, *value*) pair | | |
| +--------------------------------+---------------------------------+-----------+ |
| | ``a.iteritems()`` | return an iterator over (*key*, | (2), (3) | |
| | | *value*) pairs | | |
| +--------------------------------+---------------------------------+-----------+ |
| | ``a.iterkeys()`` | return an iterator over the | (2), (3) | |
| | | mapping's keys | | |
| +--------------------------------+---------------------------------+-----------+ |
| | ``a.itervalues()`` | return an iterator over the | (2), (3) | |
| | | mapping's values | | |
| +--------------------------------+---------------------------------+-----------+ |
| |
n | Notes: |
n | Dictionaries can be created by placing a comma-separated list of ``key: value`` |
| pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098: |
| 'jack', 4127: 'sjoerd'}``, or by the :class:`dict` constructor. |
| |
n | (1) |
n | .. class:: dict([arg]) |
| Raises a :exc:`KeyError` exception if *k* is not in the map. |
| |
n | (2) |
n | Return a new dictionary initialized from an optional positional argument or from |
| a set of keyword arguments. If no arguments are given, return a new empty |
| dictionary. If the positional argument *arg* is a mapping object, return a |
| dictionary mapping the same keys to the same values as does the mapping object. |
| Otherwise the positional argument must be a sequence, a container that supports |
| iteration, or an iterator object. The elements of the argument must each also |
| be of one of those kinds, and each must in turn contain exactly two objects. |
| The first is used as a key in the new dictionary, and the second as the key's |
| value. If a given key is seen more than once, the last value associated with it |
| is retained in the new dictionary. |
| |
| If keyword arguments are given, the keywords themselves with their associated |
| values are added as items to the dictionary. If a key is specified both in the |
| positional argument and as a keyword argument, the value associated with the |
| keyword is retained in the dictionary. For example, these all return a |
| dictionary equal to ``{"one": 2, "two": 3}``: |
| |
| * ``dict(one=2, two=3)`` |
| |
| * ``dict({'one': 2, 'two': 3})`` |
| |
| * ``dict(zip(('one', 'two'), (2, 3)))`` |
| |
| * ``dict([['two', 3], ['one', 2]])`` |
| |
| The first example only works for keys that are valid Python |
| identifiers; the others work with any valid keys. |
| |
| .. versionadded:: 2.2 |
| |
n | (3) |
n | .. versionchanged:: 2.3 |
| Keys and values are listed in an arbitrary order which is non-random, varies |
| Support for building a dictionary from keyword arguments added. |
| across Python implementations, and depends on the dictionary's history of |
| insertions and deletions. If :meth:`items`, :meth:`keys`, :meth:`values`, |
| :meth:`iteritems`, :meth:`iterkeys`, and :meth:`itervalues` are called with no |
| intervening modifications to the dictionary, the lists will directly correspond. |
| This allows the creation of ``(value, key)`` pairs using :func:`zip`: ``pairs = |
| zip(a.values(), a.keys())``. The same relationship holds for the |
| :meth:`iterkeys` and :meth:`itervalues` methods: ``pairs = zip(a.itervalues(), |
| a.iterkeys())`` provides the same value for ``pairs``. Another way to create the |
| same list is ``pairs = [(v, k) for (k, v) in a.iteritems()]``. |
| |
n | (4) |
| Never raises an exception if *k* is not in the map, instead it returns *x*. *x* |
| is optional; when *x* is not provided and *k* is not in the map, ``None`` is |
| returned. |
| |
n | (5) |
n | These are the operations that dictionaries support (and therefore, custom |
| :func:`setdefault` is like :func:`get`, except that if *k* is missing, *x* is |
| mapping types should support too): |
| both returned and inserted into the dictionary as the value of *k*. *x* defaults |
| to *None*. |
| |
n | (6) |
n | .. describe:: len(d) |
| :func:`popitem` is useful to destructively iterate over a dictionary, as often |
| used in set algorithms. If the dictionary is empty, calling :func:`popitem` |
| raises a :exc:`KeyError`. |
| |
n | (7) |
n | Return the number of items in the dictionary *d*. |
| |
| .. describe:: d[key] |
| |
| Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key* |
| is not in the map. |
| |
| .. versionadded:: 2.5 |
| If a subclass of dict defines a method :meth:`__missing__`, if the key |
| *key* is not present, the ``d[key]`` operation calls that method with |
| the key *key* as argument. The ``d[key]`` operation then returns or |
| raises whatever is returned or raised by the ``__missing__(key)`` call |
| if the key is not present. No other operations or methods invoke |
| :meth:`__missing__`. If :meth:`__missing__` is not defined, |
| :exc:`KeyError` is raised. :meth:`__missing__` must be a method; it |
| cannot be an instance variable. For an example, see |
| :class:`collections.defaultdict`. |
| |
| .. describe:: d[key] = value |
| |
| Set ``d[key]`` to *value*. |
| |
| .. describe:: del d[key] |
| |
| Remove ``d[key]`` from *d*. Raises a :exc:`KeyError` if *key* is not in the |
| map. |
| |
| .. describe:: key in d |
| |
| Return ``True`` if *d* has a key *key*, else ``False``. |
| |
| .. versionadded:: 2.2 |
| |
| .. describe:: key not in d |
| |
| Equivalent to ``not key in d``. |
| |
| .. versionadded:: 2.2 |
| |
| .. describe:: iter(d) |
| |
| Return an iterator over the keys of the dictionary. This is a shortcut |
| for :meth:`iterkeys`. |
| |
| .. method:: clear() |
| |
| Remove all items from the dictionary. |
| |
| .. method:: copy() |
| |
| Return a shallow copy of the dictionary. |
| |
| .. method:: fromkeys(seq[, value]) |
| |
| Create a new dictionary with keys from *seq* and values set to *value*. |
| |
| :func:`fromkeys` is a class method that returns a new dictionary. *value* |
| :func:`fromkeys` is a class method that returns a new dictionary. *value* |
| defaults to ``None``. |
| defaults to ``None``. |
| |
n | .. versionadded:: 2.3 |
n | .. versionadded:: 2.3 |
| |
n | (8) |
n | .. method:: get(key[, default]) |
| :func:`pop` raises a :exc:`KeyError` when no default value is given and the key |
| is not found. |
| |
n | Return the value for *key* if *key* is in the dictionary, else *default*. |
| If *default* is not given, it defaults to ``None``, so that this method |
| never raises a :exc:`KeyError`. |
| |
| .. method:: has_key(key) |
| |
| Test for the presence of *key* in the dictionary. :meth:`has_key` is |
| deprecated in favor of ``key in d``. |
| |
| .. method:: items() |
| |
| Return a copy of the dictionary's list of ``(key, value)`` pairs. |
| |
| .. note:: |
| |
| Keys and values are listed in an arbitrary order which is non-random, |
| varies across Python implementations, and depends on the dictionary's |
| history of insertions and deletions. If :meth:`items`, :meth:`keys`, |
| :meth:`values`, :meth:`iteritems`, :meth:`iterkeys`, and |
| :meth:`itervalues` are called with no intervening modifications to the |
| dictionary, the lists will directly correspond. This allows the |
| creation of ``(value, key)`` pairs using :func:`zip`: ``pairs = |
| zip(d.values(), d.keys())``. The same relationship holds for the |
| :meth:`iterkeys` and :meth:`itervalues` methods: ``pairs = |
| zip(d.itervalues(), d.iterkeys())`` provides the same value for |
| ``pairs``. Another way to create the same list is ``pairs = [(v, k) for |
| (k, v) in d.iteritems()]``. |
| |
| .. method:: iteritems() |
| |
| Return an iterator over the dictionary's ``(key, value)`` pairs. See the |
| note for :meth:`dict.items`. |
| |
| Using :meth:`iteritems` while adding or deleting entries in the dictionary |
| will raise a :exc:`RuntimeError`. |
| |
| .. versionadded:: 2.2 |
| |
| .. method:: iterkeys() |
| |
| Return an iterator over the dictionary's keys. See the note for |
| :meth:`dict.items`. |
| |
| Using :meth:`iterkeys` while adding or deleting entries in the dictionary |
| will raise a :exc:`RuntimeError`. |
| |
| .. versionadded:: 2.2 |
| |
| .. method:: itervalues() |
| |
| Return an iterator over the dictionary's values. See the note for |
| :meth:`dict.items`. |
| |
| Using :meth:`itervalues` while adding or deleting entries in the |
| dictionary will raise a :exc:`RuntimeError`. |
| |
| .. versionadded:: 2.2 |
| |
| .. method:: keys() |
| |
| Return a copy of the dictionary's list of keys. See the note for |
| :meth:`dict.items`. |
| |
| .. method:: pop(key[, default]) |
| |
| If *key* is in the dictionary, remove it and return its value, else return |
| *default*. If *default* is not given and *key* is not in the dictionary, |
| a :exc:`KeyError` is raised. |
| |
| .. versionadded:: 2.3 |
| .. versionadded:: 2.3 |
| |
n | (9) |
n | .. method:: popitem() |
| |
| Remove and return an arbitrary ``(key, value)`` pair from the dictionary. |
| |
| :func:`popitem` is useful to destructively iterate over a dictionary, as |
| often used in set algorithms. If the dictionary is empty, calling |
| :func:`popitem` raises a :exc:`KeyError`. |
| |
| .. method:: setdefault(key[, default]) |
| |
| If *key* is in the dictionary, return its value. If not, insert *key* |
| with a value of *default* and return *default*. *default* defaults to |
| ``None``. |
| |
| .. method:: update([other]) |
| |
| Update the dictionary with the key/value pairs from *other*, overwriting |
| existing keys. Return ``None``. |
| |
| :func:`update` accepts either another mapping object or an iterable of key/value |
| :func:`update` accepts either another dictionary object or an iterable of |
| pairs (as a tuple or other iterable of length two). If keyword arguments are |
| key/value pairs (as a tuple or other iterable of length two). If keyword |
| specified, the mapping is then is updated with those key/value pairs: |
| arguments are specified, the dictionary is then is updated with those |
| ``d.update(red=1, blue=2)``. |
| key/value pairs: ``d.update(red=1, blue=2)``. |
| |
n | .. versionchanged:: 2.4 |
n | .. versionchanged:: 2.4 |
| Allowed the argument to be an iterable of key/value pairs and allowed keyword |
| Allowed the argument to be an iterable of key/value pairs and allowed |
| arguments. |
| keyword arguments. |
| |
n | (10) |
n | .. method:: values() |
| If a subclass of dict defines a method :meth:`__missing__`, if the key *k* is |
| not present, the *a*[*k*] operation calls that method with the key *k* as |
| argument. The *a*[*k*] operation then returns or raises whatever is returned or |
| raised by the :func:`__missing__`\ (*k*) call if the key is not present. No |
| other operations or methods invoke :meth:`__missing__`\ (). If |
| :meth:`__missing__` is not defined, :exc:`KeyError` is raised. |
| :meth:`__missing__` must be a method; it cannot be an instance variable. For an |
| example, see :mod:`collections`.\ :class:`defaultdict`. |
| |
n | .. versionadded:: 2.5 |
n | Return a copy of the dictionary's list of values. See the note for |
| :meth:`dict.items`. |
| |
| |
| .. _bltin-file-objects: |
| |
| File Objects |
| ============ |
| |
| .. index:: |
| object: file |
| builtin: file |
| module: os |
| module: socket |
| |
n | File objects are implemented using C's ``stdio`` package and can be created with |
n | File objects are implemented using C's ``stdio`` package and can be |
| the built-in constructor :func:`file` described in section |
| created with the built-in :func:`open` function. File |
| :ref:`built-in-funcs`, "Built-in Functions." [#]_ File objects are also |
| objects are also returned by some other built-in functions and methods, |
| returned by some other built-in functions and methods, such as :func:`os.popen` |
| such as :func:`os.popen` and :func:`os.fdopen` and the :meth:`makefile` |
| and :func:`os.fdopen` and the :meth:`makefile` method of socket objects. |
| method of socket objects. Temporary files can be created using the |
| :mod:`tempfile` module, and high-level file operations such as copying, |
| moving, and deleting files and directories can be achieved with the |
| :mod:`shutil` module. |
| |
| When a file operation fails for an I/O-related reason, the exception |
| :exc:`IOError` is raised. This includes situations where the operation is not |
| defined for some reason, like :meth:`seek` on a tty device or writing a file |
| opened for reading. |
| |
| Files have the following methods: |
| |