PageRenderTime 68ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/Doc/library/stdtypes.rst

http://unladen-swallow.googlecode.com/
ReStructuredText | 2723 lines | 1927 code | 796 blank | 0 comment | 0 complexity | b712e452ec171c361e2db790d841e54a MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause
  1. .. XXX: reference/datamodel and this have quite a few overlaps!
  2. .. _bltin-types:
  3. **************
  4. Built-in Types
  5. **************
  6. The following sections describe the standard types that are built into the
  7. interpreter.
  8. .. note::
  9. Historically (until release 2.2), Python's built-in types have differed from
  10. user-defined types because it was not possible to use the built-in types as the
  11. basis for object-oriented inheritance. This limitation no longer
  12. exists.
  13. .. index:: pair: built-in; types
  14. The principal built-in types are numerics, sequences, mappings, files, classes,
  15. instances and exceptions.
  16. .. index:: statement: print
  17. Some operations are supported by several object types; in particular,
  18. practically all objects can be compared, tested for truth value, and converted
  19. to a string (with the :func:`repr` function or the slightly different
  20. :func:`str` function). The latter function is implicitly used when an object is
  21. written by the :func:`print` function.
  22. .. _truth:
  23. Truth Value Testing
  24. ===================
  25. .. index::
  26. statement: if
  27. statement: while
  28. pair: truth; value
  29. pair: Boolean; operations
  30. single: false
  31. Any object can be tested for truth value, for use in an :keyword:`if` or
  32. :keyword:`while` condition or as operand of the Boolean operations below. The
  33. following values are considered false:
  34. .. index:: single: None (Built-in object)
  35. * ``None``
  36. .. index:: single: False (Built-in object)
  37. * ``False``
  38. * zero of any numeric type, for example, ``0``, ``0L``, ``0.0``, ``0j``.
  39. * any empty sequence, for example, ``''``, ``()``, ``[]``.
  40. * any empty mapping, for example, ``{}``.
  41. * instances of user-defined classes, if the class defines a :meth:`__nonzero__`
  42. or :meth:`__len__` method, when that method returns the integer zero or
  43. :class:`bool` value ``False``. [#]_
  44. .. index:: single: true
  45. All other values are considered true --- so objects of many types are always
  46. true.
  47. .. index::
  48. operator: or
  49. operator: and
  50. single: False
  51. single: True
  52. Operations and built-in functions that have a Boolean result always return ``0``
  53. or ``False`` for false and ``1`` or ``True`` for true, unless otherwise stated.
  54. (Important exception: the Boolean operations ``or`` and ``and`` always return
  55. one of their operands.)
  56. .. _boolean:
  57. Boolean Operations --- :keyword:`and`, :keyword:`or`, :keyword:`not`
  58. ====================================================================
  59. .. index:: pair: Boolean; operations
  60. These are the Boolean operations, ordered by ascending priority:
  61. +-------------+---------------------------------+-------+
  62. | Operation | Result | Notes |
  63. +=============+=================================+=======+
  64. | ``x or y`` | if *x* is false, then *y*, else | \(1) |
  65. | | *x* | |
  66. +-------------+---------------------------------+-------+
  67. | ``x and y`` | if *x* is false, then *x*, else | \(2) |
  68. | | *y* | |
  69. +-------------+---------------------------------+-------+
  70. | ``not x`` | if *x* is false, then ``True``, | \(3) |
  71. | | else ``False`` | |
  72. +-------------+---------------------------------+-------+
  73. .. index::
  74. operator: and
  75. operator: or
  76. operator: not
  77. Notes:
  78. (1)
  79. This is a short-circuit operator, so it only evaluates the second
  80. argument if the first one is :const:`False`.
  81. (2)
  82. This is a short-circuit operator, so it only evaluates the second
  83. argument if the first one is :const:`True`.
  84. (3)
  85. ``not`` has a lower priority than non-Boolean operators, so ``not a == b`` is
  86. interpreted as ``not (a == b)``, and ``a == not b`` is a syntax error.
  87. .. _stdcomparisons:
  88. Comparisons
  89. ===========
  90. .. index:: pair: chaining; comparisons
  91. Comparison operations are supported by all objects. They all have the same
  92. priority (which is higher than that of the Boolean operations). Comparisons can
  93. be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and
  94. y <= z``, except that *y* is evaluated only once (but in both cases *z* is not
  95. evaluated at all when ``x < y`` is found to be false).
  96. This table summarizes the comparison operations:
  97. +------------+-------------------------+-------+
  98. | Operation | Meaning | Notes |
  99. +============+=========================+=======+
  100. | ``<`` | strictly less than | |
  101. +------------+-------------------------+-------+
  102. | ``<=`` | less than or equal | |
  103. +------------+-------------------------+-------+
  104. | ``>`` | strictly greater than | |
  105. +------------+-------------------------+-------+
  106. | ``>=`` | greater than or equal | |
  107. +------------+-------------------------+-------+
  108. | ``==`` | equal | |
  109. +------------+-------------------------+-------+
  110. | ``!=`` | not equal | \(1) |
  111. +------------+-------------------------+-------+
  112. | ``is`` | object identity | |
  113. +------------+-------------------------+-------+
  114. | ``is not`` | negated object identity | |
  115. +------------+-------------------------+-------+
  116. .. index::
  117. pair: operator; comparison
  118. operator: ==
  119. operator: <
  120. operator: <=
  121. operator: >
  122. operator: >=
  123. operator: !=
  124. operator: is
  125. operator: is not
  126. Notes:
  127. (1)
  128. ``!=`` can also be written ``<>``, but this is an obsolete usage
  129. kept for backwards compatibility only. New code should always use
  130. ``!=``.
  131. .. index::
  132. pair: object; numeric
  133. pair: objects; comparing
  134. Objects of different types, except different numeric types and different string
  135. types, never compare equal; such objects are ordered consistently but
  136. arbitrarily (so that sorting a heterogeneous array yields a consistent result).
  137. Furthermore, some types (for example, file objects) support only a degenerate
  138. notion of comparison where any two objects of that type are unequal. Again,
  139. such objects are ordered arbitrarily but consistently. The ``<``, ``<=``, ``>``
  140. and ``>=`` operators will raise a :exc:`TypeError` exception when any operand is
  141. a complex number.
  142. .. index:: single: __cmp__() (instance method)
  143. Instances of a class normally compare as non-equal unless the class defines the
  144. :meth:`__cmp__` method. Refer to :ref:`customization`) for information on the
  145. use of this method to effect object comparisons.
  146. **Implementation note:** Objects of different types except numbers are ordered
  147. by their type names; objects of the same types that don't support proper
  148. comparison are ordered by their address.
  149. .. index::
  150. operator: in
  151. operator: not in
  152. Two more operations with the same syntactic priority, ``in`` and ``not in``, are
  153. supported only by sequence types (below).
  154. .. _typesnumeric:
  155. Numeric Types --- :class:`int`, :class:`float`, :class:`long`, :class:`complex`
  156. ===============================================================================
  157. .. index::
  158. object: numeric
  159. object: Boolean
  160. object: integer
  161. object: long integer
  162. object: floating point
  163. object: complex number
  164. pair: C; language
  165. There are four distinct numeric types: :dfn:`plain integers`, :dfn:`long
  166. integers`, :dfn:`floating point numbers`, and :dfn:`complex numbers`. In
  167. addition, Booleans are a subtype of plain integers. Plain integers (also just
  168. called :dfn:`integers`) are implemented using :ctype:`long` in C, which gives
  169. them at least 32 bits of precision (``sys.maxint`` is always set to the maximum
  170. plain integer value for the current platform, the minimum value is
  171. ``-sys.maxint - 1``). Long integers have unlimited precision. Floating point
  172. numbers are implemented using :ctype:`double` in C. All bets on their precision
  173. are off unless you happen to know the machine you are working with.
  174. Complex numbers have a real and imaginary part, which are each implemented using
  175. :ctype:`double` in C. To extract these parts from a complex number *z*, use
  176. ``z.real`` and ``z.imag``.
  177. .. index::
  178. pair: numeric; literals
  179. pair: integer; literals
  180. triple: long; integer; literals
  181. pair: floating point; literals
  182. pair: complex number; literals
  183. pair: hexadecimal; literals
  184. pair: octal; literals
  185. Numbers are created by numeric literals or as the result of built-in functions
  186. and operators. Unadorned integer literals (including binary, hex, and octal
  187. numbers) yield plain integers unless the value they denote is too large to be
  188. represented as a plain integer, in which case they yield a long integer.
  189. Integer literals with an ``'L'`` or ``'l'`` suffix yield long integers (``'L'``
  190. is preferred because ``1l`` looks too much like eleven!). Numeric literals
  191. containing a decimal point or an exponent sign yield floating point numbers.
  192. Appending ``'j'`` or ``'J'`` to a numeric literal yields a complex number with a
  193. zero real part. A complex numeric literal is the sum of a real and an imaginary
  194. part.
  195. .. index::
  196. single: arithmetic
  197. builtin: int
  198. builtin: long
  199. builtin: float
  200. builtin: complex
  201. Python fully supports mixed arithmetic: when a binary arithmetic operator has
  202. operands of different numeric types, the operand with the "narrower" type is
  203. widened to that of the other, where plain integer is narrower than long integer
  204. is narrower than floating point is narrower than complex. Comparisons between
  205. numbers of mixed type use the same rule. [#]_ The constructors :func:`int`,
  206. :func:`long`, :func:`float`, and :func:`complex` can be used to produce numbers
  207. of a specific type.
  208. All builtin numeric types support the following operations. See
  209. :ref:`power` and later sections for the operators' priorities.
  210. +--------------------+---------------------------------+--------+
  211. | Operation | Result | Notes |
  212. +====================+=================================+========+
  213. | ``x + y`` | sum of *x* and *y* | |
  214. +--------------------+---------------------------------+--------+
  215. | ``x - y`` | difference of *x* and *y* | |
  216. +--------------------+---------------------------------+--------+
  217. | ``x * y`` | product of *x* and *y* | |
  218. +--------------------+---------------------------------+--------+
  219. | ``x / y`` | quotient of *x* and *y* | \(1) |
  220. +--------------------+---------------------------------+--------+
  221. | ``x // y`` | (floored) quotient of *x* and | (4)(5) |
  222. | | *y* | |
  223. +--------------------+---------------------------------+--------+
  224. | ``x % y`` | remainder of ``x / y`` | \(4) |
  225. +--------------------+---------------------------------+--------+
  226. | ``-x`` | *x* negated | |
  227. +--------------------+---------------------------------+--------+
  228. | ``+x`` | *x* unchanged | |
  229. +--------------------+---------------------------------+--------+
  230. | ``abs(x)`` | absolute value or magnitude of | \(3) |
  231. | | *x* | |
  232. +--------------------+---------------------------------+--------+
  233. | ``int(x)`` | *x* converted to integer | \(2) |
  234. +--------------------+---------------------------------+--------+
  235. | ``long(x)`` | *x* converted to long integer | \(2) |
  236. +--------------------+---------------------------------+--------+
  237. | ``float(x)`` | *x* converted to floating point | \(6) |
  238. +--------------------+---------------------------------+--------+
  239. | ``complex(re,im)`` | a complex number with real part | |
  240. | | *re*, imaginary part *im*. | |
  241. | | *im* defaults to zero. | |
  242. +--------------------+---------------------------------+--------+
  243. | ``c.conjugate()`` | conjugate of the complex number | |
  244. | | *c*. (Identity on real numbers) | |
  245. +--------------------+---------------------------------+--------+
  246. | ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | (3)(4) |
  247. +--------------------+---------------------------------+--------+
  248. | ``pow(x, y)`` | *x* to the power *y* | (3)(7) |
  249. +--------------------+---------------------------------+--------+
  250. | ``x ** y`` | *x* to the power *y* | \(7) |
  251. +--------------------+---------------------------------+--------+
  252. .. index::
  253. triple: operations on; numeric; types
  254. single: conjugate() (complex number method)
  255. Notes:
  256. (1)
  257. .. index::
  258. pair: integer; division
  259. triple: long; integer; division
  260. For (plain or long) integer division, the result is an integer. The result is
  261. always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and
  262. (-1)/(-2) is 0. Note that the result is a long integer if either operand is a
  263. long integer, regardless of the numeric value.
  264. (2)
  265. .. index::
  266. module: math
  267. single: floor() (in module math)
  268. single: ceil() (in module math)
  269. single: trunc() (in module math)
  270. pair: numeric; conversions
  271. Conversion from floats using :func:`int` or :func:`long` truncates toward
  272. zero like the related function, :func:`math.trunc`. Use the function
  273. :func:`math.floor` to round downward and :func:`math.ceil` to round
  274. upward.
  275. (3)
  276. See :ref:`built-in-funcs` for a full description.
  277. (4)
  278. Complex floor division operator, modulo operator, and :func:`divmod`.
  279. .. deprecated:: 2.3
  280. Instead convert to float using :func:`abs` if appropriate.
  281. (5)
  282. Also referred to as integer division. The resultant value is a whole integer,
  283. though the result's type is not necessarily int.
  284. (6)
  285. float also accepts the strings "nan" and "inf" with an optional prefix "+"
  286. or "-" for Not a Number (NaN) and positive or negative infinity.
  287. .. versionadded:: 2.6
  288. (7)
  289. Python defines ``pow(0, 0)`` and ``0 ** 0`` to be ``1``, as is common for
  290. programming languages.
  291. All :class:`numbers.Real` types (:class:`int`, :class:`long`, and
  292. :class:`float`) also include the following operations:
  293. +--------------------+------------------------------------+--------+
  294. | Operation | Result | Notes |
  295. +====================+====================================+========+
  296. | ``math.trunc(x)`` | *x* truncated to Integral | |
  297. +--------------------+------------------------------------+--------+
  298. | ``round(x[, n])`` | *x* rounded to n digits, | |
  299. | | rounding half to even. If n is | |
  300. | | omitted, it defaults to 0. | |
  301. +--------------------+------------------------------------+--------+
  302. | ``math.floor(x)`` | the greatest integral float <= *x* | |
  303. +--------------------+------------------------------------+--------+
  304. | ``math.ceil(x)`` | the least integral float >= *x* | |
  305. +--------------------+------------------------------------+--------+
  306. .. XXXJH exceptions: overflow (when? what operations?) zerodivision
  307. .. _bitstring-ops:
  308. Bit-string Operations on Integer Types
  309. --------------------------------------
  310. .. _bit-string-operations:
  311. Plain and long integer types support additional operations that make sense only
  312. for bit-strings. Negative numbers are treated as their 2's complement value
  313. (for long integers, this assumes a sufficiently large number of bits that no
  314. overflow occurs during the operation).
  315. The priorities of the binary bitwise operations are all lower than the numeric
  316. operations and higher than the comparisons; the unary operation ``~`` has the
  317. same priority as the other unary numeric operations (``+`` and ``-``).
  318. This table lists the bit-string operations sorted in ascending priority:
  319. +------------+--------------------------------+----------+
  320. | Operation | Result | Notes |
  321. +============+================================+==========+
  322. | ``x | y`` | bitwise :dfn:`or` of *x* and | |
  323. | | *y* | |
  324. +------------+--------------------------------+----------+
  325. | ``x ^ y`` | bitwise :dfn:`exclusive or` of | |
  326. | | *x* and *y* | |
  327. +------------+--------------------------------+----------+
  328. | ``x & y`` | bitwise :dfn:`and` of *x* and | |
  329. | | *y* | |
  330. +------------+--------------------------------+----------+
  331. | ``x << n`` | *x* shifted left by *n* bits | (1)(2) |
  332. +------------+--------------------------------+----------+
  333. | ``x >> n`` | *x* shifted right by *n* bits | (1)(3) |
  334. +------------+--------------------------------+----------+
  335. | ``~x`` | the bits of *x* inverted | |
  336. +------------+--------------------------------+----------+
  337. .. index::
  338. triple: operations on; integer; types
  339. pair: bit-string; operations
  340. pair: shifting; operations
  341. pair: masking; operations
  342. Notes:
  343. (1)
  344. Negative shift counts are illegal and cause a :exc:`ValueError` to be raised.
  345. (2)
  346. A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)``. A
  347. long integer is returned if the result exceeds the range of plain integers.
  348. (3)
  349. A right shift by *n* bits is equivalent to division by ``pow(2, n)``.
  350. Additional Methods on Float
  351. ---------------------------
  352. The float type has some additional methods.
  353. .. method:: float.as_integer_ratio()
  354. Return a pair of integers whose ratio is exactly equal to the
  355. original float and with a positive denominator. Raises
  356. :exc:`OverflowError` on infinities and a :exc:`ValueError` on
  357. NaNs.
  358. .. versionadded:: 2.6
  359. Two methods support conversion to
  360. and from hexadecimal strings. Since Python's floats are stored
  361. internally as binary numbers, converting a float to or from a
  362. *decimal* string usually involves a small rounding error. In
  363. contrast, hexadecimal strings allow exact representation and
  364. specification of floating-point numbers. This can be useful when
  365. debugging, and in numerical work.
  366. .. method:: float.hex()
  367. Return a representation of a floating-point number as a hexadecimal
  368. string. For finite floating-point numbers, this representation
  369. will always include a leading ``0x`` and a trailing ``p`` and
  370. exponent.
  371. .. versionadded:: 2.6
  372. .. method:: float.fromhex(s)
  373. Class method to return the float represented by a hexadecimal
  374. string *s*. The string *s* may have leading and trailing
  375. whitespace.
  376. .. versionadded:: 2.6
  377. Note that :meth:`float.hex` is an instance method, while
  378. :meth:`float.fromhex` is a class method.
  379. A hexadecimal string takes the form::
  380. [sign] ['0x'] integer ['.' fraction] ['p' exponent]
  381. where the optional ``sign`` may by either ``+`` or ``-``, ``integer``
  382. and ``fraction`` are strings of hexadecimal digits, and ``exponent``
  383. is a decimal integer with an optional leading sign. Case is not
  384. significant, and there must be at least one hexadecimal digit in
  385. either the integer or the fraction. This syntax is similar to the
  386. syntax specified in section 6.4.4.2 of the C99 standard, and also to
  387. the syntax used in Java 1.5 onwards. In particular, the output of
  388. :meth:`float.hex` is usable as a hexadecimal floating-point literal in
  389. C or Java code, and hexadecimal strings produced by C's ``%a`` format
  390. character or Java's ``Double.toHexString`` are accepted by
  391. :meth:`float.fromhex`.
  392. Note that the exponent is written in decimal rather than hexadecimal,
  393. and that it gives the power of 2 by which to multiply the coefficient.
  394. For example, the hexadecimal string ``0x3.a7p10`` represents the
  395. floating-point number ``(3 + 10./16 + 7./16**2) * 2.0**10``, or
  396. ``3740.0``::
  397. >>> float.fromhex('0x3.a7p10')
  398. 3740.0
  399. Applying the reverse conversion to ``3740.0`` gives a different
  400. hexadecimal string representing the same number::
  401. >>> float.hex(3740.0)
  402. '0x1.d380000000000p+11'
  403. .. _typeiter:
  404. Iterator Types
  405. ==============
  406. .. versionadded:: 2.2
  407. .. index::
  408. single: iterator protocol
  409. single: protocol; iterator
  410. single: sequence; iteration
  411. single: container; iteration over
  412. Python supports a concept of iteration over containers. This is implemented
  413. using two distinct methods; these are used to allow user-defined classes to
  414. support iteration. Sequences, described below in more detail, always support
  415. the iteration methods.
  416. One method needs to be defined for container objects to provide iteration
  417. support:
  418. .. XXX duplicated in reference/datamodel!
  419. .. method:: container.__iter__()
  420. Return an iterator object. The object is required to support the iterator
  421. protocol described below. If a container supports different types of
  422. iteration, additional methods can be provided to specifically request
  423. iterators for those iteration types. (An example of an object supporting
  424. multiple forms of iteration would be a tree structure which supports both
  425. breadth-first and depth-first traversal.) This method corresponds to the
  426. :attr:`tp_iter` slot of the type structure for Python objects in the Python/C
  427. API.
  428. The iterator objects themselves are required to support the following two
  429. methods, which together form the :dfn:`iterator protocol`:
  430. .. method:: iterator.__iter__()
  431. Return the iterator object itself. This is required to allow both containers
  432. and iterators to be used with the :keyword:`for` and :keyword:`in` statements.
  433. This method corresponds to the :attr:`tp_iter` slot of the type structure for
  434. Python objects in the Python/C API.
  435. .. method:: iterator.next()
  436. Return the next item from the container. If there are no further items, raise
  437. the :exc:`StopIteration` exception. This method corresponds to the
  438. :attr:`tp_iternext` slot of the type structure for Python objects in the
  439. Python/C API.
  440. Python defines several iterator objects to support iteration over general and
  441. specific sequence types, dictionaries, and other more specialized forms. The
  442. specific types are not important beyond their implementation of the iterator
  443. protocol.
  444. The intention of the protocol is that once an iterator's :meth:`next` method
  445. raises :exc:`StopIteration`, it will continue to do so on subsequent calls.
  446. Implementations that do not obey this property are deemed broken. (This
  447. constraint was added in Python 2.3; in Python 2.2, various iterators are broken
  448. according to this rule.)
  449. Python's :term:`generator`\s provide a convenient way to implement the iterator
  450. protocol. If a container object's :meth:`__iter__` method is implemented as a
  451. generator, it will automatically return an iterator object (technically, a
  452. generator object) supplying the :meth:`__iter__` and :meth:`next` methods.
  453. .. _typesseq:
  454. Sequence Types --- :class:`str`, :class:`unicode`, :class:`list`, :class:`tuple`, :class:`buffer`, :class:`xrange`
  455. ==================================================================================================================
  456. There are six sequence types: strings, Unicode strings, lists, tuples, buffers,
  457. and xrange objects.
  458. For other containers see the built in :class:`dict` and :class:`set` classes,
  459. and the :mod:`collections` module.
  460. .. index::
  461. object: sequence
  462. object: string
  463. object: Unicode
  464. object: tuple
  465. object: list
  466. object: buffer
  467. object: xrange
  468. String literals are written in single or double quotes: ``'xyzzy'``,
  469. ``"frobozz"``. See :ref:`strings` for more about string literals.
  470. Unicode strings are much like strings, but are specified in the syntax
  471. using a preceding ``'u'`` character: ``u'abc'``, ``u"def"``. In addition
  472. to the functionality described here, there are also string-specific
  473. methods described in the :ref:`string-methods` section. Lists are
  474. constructed with square brackets, separating items with commas: ``[a, b, c]``.
  475. Tuples are constructed by the comma operator (not within square
  476. brackets), with or without enclosing parentheses, but an empty tuple
  477. must have the enclosing parentheses, such as ``a, b, c`` or ``()``. A
  478. single item tuple must have a trailing comma, such as ``(d,)``.
  479. Buffer objects are not directly supported by Python syntax, but can be created
  480. by calling the builtin function :func:`buffer`. They don't support
  481. concatenation or repetition.
  482. Objects of type xrange are similar to buffers in that there is no specific syntax to
  483. create them, but they are created using the :func:`xrange` function. They don't
  484. support slicing, concatenation or repetition, and using ``in``, ``not in``,
  485. :func:`min` or :func:`max` on them is inefficient.
  486. Most sequence types support the following operations. The ``in`` and ``not in``
  487. operations have the same priorities as the comparison operations. The ``+`` and
  488. ``*`` operations have the same priority as the corresponding numeric operations.
  489. [#]_ Additional methods are provided for :ref:`typesseq-mutable`.
  490. This table lists the sequence operations sorted in ascending priority
  491. (operations in the same box have the same priority). In the table, *s* and *t*
  492. are sequences of the same type; *n*, *i* and *j* are integers:
  493. +------------------+--------------------------------+----------+
  494. | Operation | Result | Notes |
  495. +==================+================================+==========+
  496. | ``x in s`` | ``True`` if an item of *s* is | \(1) |
  497. | | equal to *x*, else ``False`` | |
  498. +------------------+--------------------------------+----------+
  499. | ``x not in s`` | ``False`` if an item of *s* is | \(1) |
  500. | | equal to *x*, else ``True`` | |
  501. +------------------+--------------------------------+----------+
  502. | ``s + t`` | the concatenation of *s* and | \(6) |
  503. | | *t* | |
  504. +------------------+--------------------------------+----------+
  505. | ``s * n, n * s`` | *n* shallow copies of *s* | \(2) |
  506. | | concatenated | |
  507. +------------------+--------------------------------+----------+
  508. | ``s[i]`` | *i*'th item of *s*, origin 0 | \(3) |
  509. +------------------+--------------------------------+----------+
  510. | ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) |
  511. +------------------+--------------------------------+----------+
  512. | ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) |
  513. | | with step *k* | |
  514. +------------------+--------------------------------+----------+
  515. | ``len(s)`` | length of *s* | |
  516. +------------------+--------------------------------+----------+
  517. | ``min(s)`` | smallest item of *s* | |
  518. +------------------+--------------------------------+----------+
  519. | ``max(s)`` | largest item of *s* | |
  520. +------------------+--------------------------------+----------+
  521. Sequence types also support comparisons. In particular, tuples and lists
  522. are compared lexicographically by comparing corresponding
  523. elements. This means that to compare equal, every element must compare
  524. equal and the two sequences must be of the same type and have the same
  525. length. (For full details see :ref:`comparisons` in the language
  526. reference.)
  527. .. index::
  528. triple: operations on; sequence; types
  529. builtin: len
  530. builtin: min
  531. builtin: max
  532. pair: concatenation; operation
  533. pair: repetition; operation
  534. pair: subscript; operation
  535. pair: slice; operation
  536. pair: extended slice; operation
  537. operator: in
  538. operator: not in
  539. Notes:
  540. (1)
  541. When *s* is a string or Unicode string object the ``in`` and ``not in``
  542. operations act like a substring test. In Python versions before 2.3, *x* had to
  543. be a string of length 1. In Python 2.3 and beyond, *x* may be a string of any
  544. length.
  545. (2)
  546. Values of *n* less than ``0`` are treated as ``0`` (which yields an empty
  547. sequence of the same type as *s*). Note also that the copies are shallow;
  548. nested structures are not copied. This often haunts new Python programmers;
  549. consider:
  550. >>> lists = [[]] * 3
  551. >>> lists
  552. [[], [], []]
  553. >>> lists[0].append(3)
  554. >>> lists
  555. [[3], [3], [3]]
  556. What has happened is that ``[[]]`` is a one-element list containing an empty
  557. list, so all three elements of ``[[]] * 3`` are (pointers to) this single empty
  558. list. Modifying any of the elements of ``lists`` modifies this single list.
  559. You can create a list of different lists this way:
  560. >>> lists = [[] for i in range(3)]
  561. >>> lists[0].append(3)
  562. >>> lists[1].append(5)
  563. >>> lists[2].append(7)
  564. >>> lists
  565. [[3], [5], [7]]
  566. (3)
  567. If *i* or *j* is negative, the index is relative to the end of the string:
  568. ``len(s) + i`` or ``len(s) + j`` is substituted. But note that ``-0`` is still
  569. ``0``.
  570. (4)
  571. The slice of *s* from *i* to *j* is defined as the sequence of items with index
  572. *k* such that ``i <= k < j``. If *i* or *j* is greater than ``len(s)``, use
  573. ``len(s)``. If *i* is omitted or ``None``, use ``0``. If *j* is omitted or
  574. ``None``, use ``len(s)``. If *i* is greater than or equal to *j*, the slice is
  575. empty.
  576. (5)
  577. The slice of *s* from *i* to *j* with step *k* is defined as the sequence of
  578. items with index ``x = i + n*k`` such that ``0 <= n < (j-i)/k``. In other words,
  579. the indices are ``i``, ``i+k``, ``i+2*k``, ``i+3*k`` and so on, stopping when
  580. *j* is reached (but never including *j*). If *i* or *j* is greater than
  581. ``len(s)``, use ``len(s)``. If *i* or *j* are omitted or ``None``, they become
  582. "end" values (which end depends on the sign of *k*). Note, *k* cannot be zero.
  583. If *k* is ``None``, it is treated like ``1``.
  584. (6)
  585. If *s* and *t* are both strings, some Python implementations such as CPython can
  586. usually perform an in-place optimization for assignments of the form ``s=s+t``
  587. or ``s+=t``. When applicable, this optimization makes quadratic run-time much
  588. less likely. This optimization is both version and implementation dependent.
  589. For performance sensitive code, it is preferable to use the :meth:`str.join`
  590. method which assures consistent linear concatenation performance across versions
  591. and implementations.
  592. .. versionchanged:: 2.4
  593. Formerly, string concatenation never occurred in-place.
  594. .. _string-methods:
  595. String Methods
  596. --------------
  597. .. index:: pair: string; methods
  598. Below are listed the string methods which both 8-bit strings and Unicode objects
  599. support. Note that none of these methods take keyword arguments.
  600. In addition, Python's strings support the sequence type methods
  601. described in the :ref:`typesseq` section. To output formatted strings
  602. use template strings or the ``%`` operator described in the
  603. :ref:`string-formatting` section. Also, see the :mod:`re` module for
  604. string functions based on regular expressions.
  605. .. method:: str.capitalize()
  606. Return a copy of the string with only its first character capitalized.
  607. For 8-bit strings, this method is locale-dependent.
  608. .. method:: str.center(width[, fillchar])
  609. Return centered in a string of length *width*. Padding is done using the
  610. specified *fillchar* (default is a space).
  611. .. versionchanged:: 2.4
  612. Support for the *fillchar* argument.
  613. .. method:: str.count(sub[, start[, end]])
  614. Return the number of non-overlapping occurrences of substring *sub* in the
  615. range [*start*, *end*]. Optional arguments *start* and *end* are
  616. interpreted as in slice notation.
  617. .. method:: str.decode([encoding[, errors]])
  618. Decodes the string using the codec registered for *encoding*. *encoding*
  619. defaults to the default string encoding. *errors* may be given to set a
  620. different error handling scheme. The default is ``'strict'``, meaning that
  621. encoding errors raise :exc:`UnicodeError`. Other possible values are
  622. ``'ignore'``, ``'replace'`` and any other name registered via
  623. :func:`codecs.register_error`, see section :ref:`codec-base-classes`.
  624. .. versionadded:: 2.2
  625. .. versionchanged:: 2.3
  626. Support for other error handling schemes added.
  627. .. method:: str.encode([encoding[,errors]])
  628. Return an encoded version of the string. Default encoding is the current
  629. default string encoding. *errors* may be given to set a different error
  630. handling scheme. The default for *errors* is ``'strict'``, meaning that
  631. encoding errors raise a :exc:`UnicodeError`. Other possible values are
  632. ``'ignore'``, ``'replace'``, ``'xmlcharrefreplace'``, ``'backslashreplace'`` and
  633. any other name registered via :func:`codecs.register_error`, see section
  634. :ref:`codec-base-classes`. For a list of possible encodings, see section
  635. :ref:`standard-encodings`.
  636. .. versionadded:: 2.0
  637. .. versionchanged:: 2.3
  638. Support for ``'xmlcharrefreplace'`` and ``'backslashreplace'`` and other error
  639. handling schemes added.
  640. .. method:: str.endswith(suffix[, start[, end]])
  641. Return ``True`` if the string ends with the specified *suffix*, otherwise return
  642. ``False``. *suffix* can also be a tuple of suffixes to look for. With optional
  643. *start*, test beginning at that position. With optional *end*, stop comparing
  644. at that position.
  645. .. versionchanged:: 2.5
  646. Accept tuples as *suffix*.
  647. .. method:: str.expandtabs([tabsize])
  648. Return a copy of the string where all tab characters are replaced by one or
  649. more spaces, depending on the current column and the given tab size. The
  650. column number is reset to zero after each newline occurring in the string.
  651. If *tabsize* is not given, a tab size of ``8`` characters is assumed. This
  652. doesn't understand other non-printing characters or escape sequences.
  653. .. method:: str.find(sub[, start[, end]])
  654. Return the lowest index in the string where substring *sub* is found, such that
  655. *sub* is contained in the range [*start*, *end*]. Optional arguments *start*
  656. and *end* are interpreted as in slice notation. Return ``-1`` if *sub* is not
  657. found.
  658. .. method:: str.format(format_string, *args, **kwargs)
  659. Perform a string formatting operation. The *format_string* argument can
  660. contain literal text or replacement fields delimited by braces ``{}``. Each
  661. replacement field contains either the numeric index of a positional argument,
  662. or the name of a keyword argument. Returns a copy of *format_string* where
  663. each replacement field is replaced with the string value of the corresponding
  664. argument.
  665. >>> "The sum of 1 + 2 is {0}".format(1+2)
  666. 'The sum of 1 + 2 is 3'
  667. See :ref:`formatstrings` for a description of the various formatting options
  668. that can be specified in format strings.
  669. This method of string formatting is the new standard in Python 3.0, and
  670. should be preferred to the ``%`` formatting described in
  671. :ref:`string-formatting` in new code.
  672. .. versionadded:: 2.6
  673. .. method:: str.index(sub[, start[, end]])
  674. Like :meth:`find`, but raise :exc:`ValueError` when the substring is not found.
  675. .. method:: str.isalnum()
  676. Return true if all characters in the string are alphanumeric and there is at
  677. least one character, false otherwise.
  678. For 8-bit strings, this method is locale-dependent.
  679. .. method:: str.isalpha()
  680. Return true if all characters in the string are alphabetic and there is at least
  681. one character, false otherwise.
  682. For 8-bit strings, this method is locale-dependent.
  683. .. method:: str.isdigit()
  684. Return true if all characters in the string are digits and there is at least one
  685. character, false otherwise.
  686. For 8-bit strings, this method is locale-dependent.
  687. .. method:: str.islower()
  688. Return true if all cased characters in the string are lowercase and there is at
  689. least one cased character, false otherwise.
  690. For 8-bit strings, this method is locale-dependent.
  691. .. method:: str.isspace()
  692. Return true if there are only whitespace characters in the string and there is
  693. at least one character, false otherwise.
  694. For 8-bit strings, this method is locale-dependent.
  695. .. method:: str.istitle()
  696. Return true if the string is a titlecased string and there is at least one
  697. character, for example uppercase characters may only follow uncased characters
  698. and lowercase characters only cased ones. Return false otherwise.
  699. For 8-bit strings, this method is locale-dependent.
  700. .. method:: str.isupper()
  701. Return true if all cased characters in the string are uppercase and there is at
  702. least one cased character, false otherwise.
  703. For 8-bit strings, this method is locale-dependent.
  704. .. method:: str.join(seq)
  705. Return a string which is the concatenation of the strings in the sequence *seq*.
  706. The separator between elements is the string providing this method.
  707. .. method:: str.ljust(width[, fillchar])
  708. Return the string left justified in a string of length *width*. Padding is done
  709. using the specified *fillchar* (default is a space). The original string is
  710. returned if *width* is less than ``len(s)``.
  711. .. versionchanged:: 2.4
  712. Support for the *fillchar* argument.
  713. .. method:: str.lower()
  714. Return a copy of the string converted to lowercase.
  715. For 8-bit strings, this method is locale-dependent.
  716. .. method:: str.lstrip([chars])
  717. Return a copy of the string with leading characters removed. The *chars*
  718. argument is a string specifying the set of characters to be removed. If omitted
  719. or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
  720. argument is not a prefix; rather, all combinations of its values are stripped:
  721. >>> ' spacious '.lstrip()
  722. 'spacious '
  723. >>> 'www.example.com'.lstrip('cmowz.')
  724. 'example.com'
  725. .. versionchanged:: 2.2.2
  726. Support for the *chars* argument.
  727. .. method:: str.partition(sep)
  728. Split the string at the first occurrence of *sep*, and return a 3-tuple
  729. containing the part before the separator, the separator itself, and the part
  730. after the separator. If the separator is not found, return a 3-tuple containing
  731. the string itself, followed by two empty strings.
  732. .. versionadded:: 2.5
  733. .. method:: str.replace(old, new[, count])
  734. Return a copy of the string with all occurrences of substring *old* replaced by
  735. *new*. If the optional argument *count* is given, only the first *count*
  736. occurrences are replaced.
  737. .. method:: str.rfind(sub [,start [,end]])
  738. Return the highest index in the string where substring *sub* is found, such that
  739. *sub* is contained within s[start,end]. Optional arguments *start* and *end*
  740. are interpreted as in slice notation. Return ``-1`` on failure.
  741. .. method:: str.rindex(sub[, start[, end]])
  742. Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not
  743. found.
  744. .. method:: str.rjust(width[, fillchar])
  745. Return the string right justified in a string of length *width*. Padding is done
  746. using the specified *fillchar* (default is a space). The original string is
  747. returned if *width* is less than ``len(s)``.
  748. .. versionchanged:: 2.4
  749. Support for the *fillchar* argument.
  750. .. method:: str.rpartition(sep)
  751. Split the string at the last occurrence of *sep*, and return a 3-tuple
  752. containing the part before the separator, the separator itself, and the part
  753. after the separator. If the separator is not found, return a 3-tuple containing
  754. two empty strings, followed by the string itself.
  755. .. versionadded:: 2.5
  756. .. method:: str.rsplit([sep [,maxsplit]])
  757. Return a list of the words in the string, using *sep* as the delimiter string.
  758. If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost*
  759. ones. If *sep* is not specified or ``None``, any whitespace string is a
  760. separator. Except for splitting from the right, :meth:`rsplit` behaves like
  761. :meth:`split` which is described in detail below.
  762. .. versionadded:: 2.4
  763. .. method:: str.rstrip([chars])
  764. Return a copy of the string with trailing characters removed. The *chars*
  765. argument is a string specifying the set of characters to be removed. If omitted
  766. or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
  767. argument is not a suffix; rather, all combinations of its values are stripped:
  768. >>> ' spacious '.rstrip()
  769. ' spacious'
  770. >>> 'mississippi'.rstrip('ipz')
  771. 'mississ'
  772. .. versionchanged:: 2.2.2
  773. Support for the *chars* argument.
  774. .. method:: str.split([sep[, maxsplit]])
  775. Return a list of the words in the string, using *sep* as the delimiter
  776. string. If *maxsplit* is given, at most *maxsplit* splits are done (thus,
  777. the list will have at most ``maxsplit+1`` elements). If *maxsplit* is not
  778. specified, then there is no limit on the number of splits (all possible
  779. splits are made).
  780. If *sep* is given, consecutive delimiters are not grouped together and are
  781. deemed to delimit empty strings (for example, ``'1,,2'.split(',')`` returns
  782. ``['1', '', '2']``). The *sep* argument may consist of multiple characters
  783. (for example, ``'1<>2<>3'.split('<>')`` returns ``['1', '2', '3']``).
  784. Splitting an empty string with a specified separator returns ``['']``.
  785. If *sep* is not specified or is ``None``, a different splitting algorithm is
  786. applied: runs of consecutive whitespace are regarded as a single separator,
  787. and the result will contain no empty strings at the start or end if the
  788. string has leading or trailing whitespace. Consequently, splitting an empty
  789. string or a string consisting of just whitespace with a ``None`` separator
  790. returns ``[]``.
  791. For example, ``' 1 2 3 '.split()`` returns ``['1', '2', '3']``, and
  792. ``' 1 2 3 '.split(None, 1)`` returns ``['1', '2 3 ']``.
  793. .. method:: str.splitlines([keepends])
  794. Return a list of the lines in the string, breaking at line boundaries. Line
  795. breaks are not included in the resulting list unless *keepends* is given and
  796. true.
  797. .. method:: str.startswith(prefix[, start[, end]])
  798. Return ``True`` if string starts with the *prefix*, otherwise return ``False``.
  799. *prefix* can also be a tuple of prefixes to look for. With optional *start*,
  800. test string beginning at that position. With optional *end*, stop comparing
  801. string at that position.
  802. .. versionchanged:: 2.5
  803. Accept tuples as *prefix*.
  804. .. method:: str.strip([chars])
  805. Return a copy of the string with the leading and trailing characters removed.
  806. The *chars* argument is a string specifying the set of characters to be removed.
  807. If omitted or ``None``, the *chars* argument defaults to removing whitespace.
  808. The *chars* argument is not a prefix or suffix; rather, all combinations of its
  809. values are stripped:
  810. >>> ' spacious '.strip()
  811. 'spacious'
  812. >>> 'www.example.com'.strip('cmowz.')
  813. 'example'
  814. .. versionchanged:: 2.2.2
  815. Support for the *chars* argument.
  816. .. method:: str.swapcase()
  817. Return a copy of the string with uppercase characters converted to lowercase and
  818. vice versa.
  819. For 8-bit strings, this method is locale-dependent.
  820. .. method:: str.title()
  821. Return a titlecased version of the string where words start with an uppercase
  822. character and the remaining characters are lowercase.
  823. The algorithm uses a simple language-independent definition of a word as
  824. groups of consecutive letters. The definition works in many contexts but
  825. it means that apostrophes in contractions and possessives form word
  826. boundaries, which may not be the desired result::
  827. >>> "they're bill's friends from the UK".title()
  828. "They'Re Bill'S Friends From The Uk"
  829. A workaround for apostrophes can be constructed using regular expressions::
  830. >>> import re
  831. >>> def titlecase(s):
  832. return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
  833. lambda mo: mo.group(0)[0].upper() +
  834. mo.group(0)[1:].lower(),
  835. s)
  836. >>> titlecase("they're bill's friends.")
  837. "They're Bill's Friends."
  838. For 8-bit strings, this method is locale-dependent.
  839. .. method:: str.translate(table[, deletechars])
  840. Return a copy of the string where all characters occurring in the optional
  841. argument *deletechars* are removed, and the remaining characters have been
  842. mapped through the given translation table, which must be a string of length
  843. 256.
  844. You can use the :func:`maketrans` helper function in the :mod:`string` module to
  845. create a translation table. For string objects, set the *table* argument to
  846. ``None`` for translations that only delete characters:
  847. >>> 'read this short text'.translate(None, 'aeiou')
  848. 'rd ths shrt txt'
  849. .. versionadded:: 2.6
  850. Support for a ``None`` *table* argument.
  851. For Unicode objects, the :meth:`translate` method does not accept the optional
  852. *deletechars* argument. Instead, it returns a copy of the *s* where all
  853. characters have been mapped through the given translation table which must be a
  854. mapping of Unicode ordinals to Unicode ordinals, Unicode strings or ``None``.
  855. Unmapped characters are left untouched. Characters mapped to ``None`` are
  856. deleted. Note, a more flexible approach is to create a custom character mapping
  857. codec using the :mod:`codecs` module (see :mod:`encodings.cp1251` for an
  858. example).
  859. .. method:: str.upper()
  860. Return a copy of the string converted to uppercase.
  861. For 8-bit strings, this method is locale-dependent.
  862. .. method:: str.zfill(width)
  863. Return the numeric string left filled with zeros in a string of length
  864. *width*. A sign prefix is handled correctly. The original string is
  865. returned if *width* is less than ``len(s)``.
  866. .. versionadded:: 2.2.2
  867. The following methods are present only on unicode objects:
  868. .. method:: unicode.isnumeric()
  869. Return ``True`` if there are only numeric characters in S, ``False``
  870. otherwise. Numeric characters include digit characters, and all characters
  871. that have the Unicode numeric value property, e.g. U+2155,
  872. VULGAR FRACTION ONE FIFTH.
  873. .. method:: unicode.isdecimal()
  874. Return ``True`` if there are only decimal characters in S, ``False``
  875. otherwise. Decimal characters include digit characters, and all characters
  876. that that can be used to form decimal-radix numbers, e.g. U+0660,
  877. ARABIC-INDIC DIGIT ZERO.
  878. .. _string-formatting:
  879. String Formatting Operations
  880. ----------------------------
  881. .. index::
  882. single: formatting, string (%)
  883. single: interpolation, string (%)
  884. single: string; formatting
  885. single: string; interpolation
  886. single: printf-style formatting
  887. single: sprintf-style formatting
  888. single: % formatting
  889. single: % interpolation
  890. String and Unicode objects have one unique built-in operation: the ``%``
  891. operator (modulo). This is also known as the string *formatting* or
  892. *interpolation* operator. Given ``format % values`` (where *format* is a string
  893. or Unicode object), ``%`` conversion specifications in *format* are replaced
  894. with zero or more elements of *values*. The effect is similar to the using
  895. :cfunc:`sprintf` in the C language. If *format* is a Unicode object, or if any
  896. of the objects being converted using the ``%s`` conversion are Unicode objects,
  897. the result will also be a Unicode object.
  898. If *format* requires a single argument, *values* may be a single non-tuple
  899. object. [#]_ Otherwise, *values* must be a tuple with exactly the number of
  900. items specified by the format string, or a single mapping object (for example, a
  901. dictionary).
  902. A conversion specifier contains two or more characters and has the following
  903. components, which must occur in this order:
  904. #. The ``'%'`` character, which marks the start of the specifier.
  905. #. Mapping key (optional), consisting of a parenthesised sequence of characters
  906. (for example, ``(somename)``).
  907. #. Conversion flags (optional), which affect the result of some conversion
  908. types.
  909. #. Minimum field width (optional). If specified as an ``'*'`` (asterisk), the
  910. actual width is read from the next element of the tuple in *values*, and the
  911. object to convert comes after the minimum field width and optional precision.
  912. #. Precision (optional), given as a ``'.'`` (dot) followed by the precision. If
  913. specified as ``'*'`` (an asterisk), the actual width is read from the next
  914. element of the tuple in *values*, and the value to convert comes after the
  915. precision.
  916. #. Length modifier (optional).
  917. #. Conversion type.
  918. When the right argument is a dictionary (or other mapping type), then the
  919. formats in the string *must* include a parenthesised mapping key into that
  920. dictionary inserted immediately after the ``'%'`` character. The mapping key
  921. selects the value to be formatted from the mapping. For example:
  922. >>> print '%(language)s has %(#)03d quote types.' % \
  923. ... {'language': "Python", "#": 2}
  924. Python has 002 quote types.
  925. In this case no ``*`` specifiers may occur in a format (since they require a
  926. sequential parameter list).
  927. The conversion flag characters are:
  928. +---------+---------------------------------------------------------------------+
  929. | Flag | Meaning |
  930. +=========+=====================================================================+
  931. | ``'#'`` | The value conversion will use the "alternate form" (where defined |
  932. | | below). |
  933. +---------+---------------------------------------------------------------------+
  934. | ``'0'`` | The conversion will be zero padded for numeric values. |
  935. +---------+---------------------------------------------------------------------+
  936. | ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` |
  937. | | conversion if both are given). |
  938. +---------+---------------------------------------------------------------------+
  939. | ``' '`` | (a space) A blank should be left before a positive number (or empty |
  940. | | string) produced by a signed conversion. |
  941. +---------+---------------------------------------------------------------------+
  942. | ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion |
  943. | | (overrides a "space" flag). |
  944. +---------+---------------------------------------------------------------------+
  945. A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it
  946. is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``.
  947. The conversion types are:
  948. +------------+-----------------------------------------------------+-------+
  949. | Conversion | Meaning | Notes |
  950. +============+=====================================================+=======+
  951. | ``'d'`` | Signed integer decimal. | |
  952. +------------+-----------------------------------------------------+-------+
  953. | ``'i'`` | Signed integer decimal. | |
  954. +------------+-----------------------------------------------------+-------+
  955. | ``'o'`` | Signed octal value. | \(1) |
  956. +------------+-----------------------------------------------------+-------+
  957. | ``'u'`` | Obsolete type -- it is identical to ``'d'``. | \(7) |
  958. +------------+-----------------------------------------------------+-------+
  959. | ``'x'`` | Signed hexadecimal (lowercase). | \(2) |
  960. +------------+-----------------------------------------------------+-------+
  961. | ``'X'`` | Signed hexadecimal (uppercase). | \(2) |
  962. +------------+-----------------------------------------------------+-------+
  963. | ``'e'`` | Floating point exponential format (lowercase). | \(3) |
  964. +------------+-----------------------------------------------------+-------+
  965. | ``'E'`` | Floating point exponential format (uppercase). | \(3) |
  966. +------------+-----------------------------------------------------+-------+
  967. | ``'f'`` | Floating point decimal format. | \(3) |
  968. +------------+-----------------------------------------------------+-------+
  969. | ``'F'`` | Floating point decimal format. | \(3) |
  970. +------------+-----------------------------------------------------+-------+
  971. | ``'g'`` | Floating point format. Uses lowercase exponential | \(4) |
  972. | | format if exponent is less than -4 or not less than | |
  973. | | precision, decimal format otherwise. | |
  974. +------------+-----------------------------------------------------+-------+
  975. | ``'G'`` | Floating point format. Uses uppercase exponential | \(4) |
  976. | | format if exponent is less than -4 or not less than | |
  977. | | precision, decimal format otherwise. | |
  978. +------------+-----------------------------------------------------+-------+
  979. | ``'c'`` | Single character (accepts integer or single | |
  980. | | character string). | |
  981. +------------+-----------------------------------------------------+-------+
  982. | ``'r'`` | String (converts any python object using | \(5) |
  983. | | :func:`repr`). | |
  984. +------------+-----------------------------------------------------+-------+
  985. | ``'s'`` | String (converts any python object using | \(6) |
  986. | | :func:`str`). | |
  987. +------------+-----------------------------------------------------+-------+
  988. | ``'%'`` | No argument is converted, results in a ``'%'`` | |
  989. | | character in the result. | |
  990. +------------+-----------------------------------------------------+-------+
  991. Notes:
  992. (1)
  993. The alternate form causes a leading zero (``'0'``) to be inserted between
  994. left-hand padding and the formatting of the number if the leading character
  995. of the result is not already a zero.
  996. (2)
  997. The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether
  998. the ``'x'`` or ``'X'`` format was used) to be inserted between left-hand padding
  999. and the formatting of the number if the leading character of the result is not
  1000. already a zero.
  1001. (3)
  1002. The alternate form causes the result to always contain a decimal point, even if
  1003. no digits follow it.
  1004. The precision determines the number of digits after the decimal point and
  1005. defaults to 6.
  1006. (4)
  1007. The alternate form causes the result to always contain a decimal point, and
  1008. trailing zeroes are not removed as they would otherwise be.
  1009. The precision determines the number of significant digits before and after the
  1010. decimal point and defaults to 6.
  1011. (5)
  1012. The ``%r`` conversion was added in Python 2.0.
  1013. The precision determines the maximal number of characters used.
  1014. (6)
  1015. If the object or format provided is a :class:`unicode` string, the resulting
  1016. string will also be :class:`unicode`.
  1017. The precision determines the maximal number of characters used.
  1018. (7)
  1019. See :pep:`237`.
  1020. Since Python strings have an explicit length, ``%s`` conversions do not assume
  1021. that ``'\0'`` is the end of the string.
  1022. .. XXX Examples?
  1023. For safety reasons, floating point precisions are clipped to 50; ``%f``
  1024. conversions for numbers whose absolute value is over 1e50 are replaced by ``%g``
  1025. conversions. [#]_ All other errors raise exceptions.
  1026. .. index::
  1027. module: string
  1028. module: re
  1029. Additional string operations are defined in standard modules :mod:`string` and
  1030. :mod:`re`.
  1031. .. _typesseq-xrange:
  1032. XRange Type
  1033. -----------
  1034. .. index:: object: xrange
  1035. The :class:`xrange` type is an immutable sequence which is commonly used for
  1036. looping. The advantage of the :class:`xrange` type is that an :class:`xrange`
  1037. object will always take the same amount of memory, no matter the size of the
  1038. range it represents. There are no consistent performance advantages.
  1039. XRange objects have very little behavior: they only support indexing, iteration,
  1040. and the :func:`len` function.
  1041. .. _typesseq-mutable:
  1042. Mutable Sequence Types
  1043. ----------------------
  1044. .. index::
  1045. triple: mutable; sequence; types
  1046. object: list
  1047. List objects support additional operations that allow in-place modification of
  1048. the object. Other mutable sequence types (when added to the language) should
  1049. also support these operations. Strings and tuples are immutable sequence types:
  1050. such objects cannot be modified once created. The following operations are
  1051. defined on mutable sequence types (where *x* is an arbitrary object):
  1052. +------------------------------+--------------------------------+---------------------+
  1053. | Operation | Result | Notes |
  1054. +==============================+================================+=====================+
  1055. | ``s[i] = x`` | item *i* of *s* is replaced by | |
  1056. | | *x* | |
  1057. +------------------------------+--------------------------------+---------------------+
  1058. | ``s[i:j] = t`` | slice of *s* from *i* to *j* | |
  1059. | | is replaced by the contents of | |
  1060. | | the iterable *t* | |
  1061. +------------------------------+--------------------------------+---------------------+
  1062. | ``del s[i:j]`` | same as ``s[i:j] = []`` | |
  1063. +------------------------------+--------------------------------+---------------------+
  1064. | ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` | \(1) |
  1065. | | are replaced by those of *t* | |
  1066. +------------------------------+--------------------------------+---------------------+
  1067. | ``del s[i:j:k]`` | removes the elements of | |
  1068. | | ``s[i:j:k]`` from the list | |
  1069. +------------------------------+--------------------------------+---------------------+
  1070. | ``s.append(x)`` | same as ``s[len(s):len(s)] = | \(2) |
  1071. | | [x]`` | |
  1072. +------------------------------+--------------------------------+---------------------+
  1073. | ``s.extend(x)`` | same as ``s[len(s):len(s)] = | \(3) |
  1074. | | x`` | |
  1075. +------------------------------+--------------------------------+---------------------+
  1076. | ``s.count(x)`` | return number of *i*'s for | |
  1077. | | which ``s[i] == x`` | |
  1078. +------------------------------+--------------------------------+---------------------+
  1079. | ``s.index(x[, i[, j]])`` | return smallest *k* such that | \(4) |
  1080. | | ``s[k] == x`` and ``i <= k < | |
  1081. | | j`` | |
  1082. +------------------------------+--------------------------------+---------------------+
  1083. | ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | \(5) |
  1084. +------------------------------+--------------------------------+---------------------+
  1085. | ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | \(6) |
  1086. | | return x`` | |
  1087. +------------------------------+--------------------------------+---------------------+
  1088. | ``s.remove(x)`` | same as ``del s[s.index(x)]`` | \(4) |
  1089. +------------------------------+--------------------------------+---------------------+
  1090. | ``s.reverse()`` | reverses the items of *s* in | \(7) |
  1091. | | place | |
  1092. +------------------------------+--------------------------------+---------------------+
  1093. | ``s.sort([cmp[, key[, | sort the items of *s* in place | (7)(8)(9)(10) |
  1094. | reverse]]])`` | | |
  1095. +------------------------------+--------------------------------+---------------------+
  1096. .. index::
  1097. triple: operations on; sequence; types
  1098. triple: operations on; list; type
  1099. pair: subscript; assignment
  1100. pair: slice; assignment
  1101. pair: extended slice; assignment
  1102. statement: del
  1103. single: append() (list method)
  1104. single: extend() (list method)
  1105. single: count() (list method)
  1106. single: index() (list method)
  1107. single: insert() (list method)
  1108. single: pop() (list method)
  1109. single: remove() (list method)
  1110. single: reverse() (list method)
  1111. single: sort() (list method)
  1112. Notes:
  1113. (1)
  1114. *t* must have the same length as the slice it is replacing.
  1115. (2)
  1116. The C implementation of Python has historically accepted multiple parameters and
  1117. implicitly joined them into a tuple; this no longer works in Python 2.0. Use of
  1118. this misfeature has been deprecated since Python 1.4.
  1119. (3)
  1120. *x* can be any iterable object.
  1121. (4)
  1122. Raises :exc:`ValueError` when *x* is not found in *s*. When a negative index is
  1123. passed as the second or third parameter to the :meth:`index` method, the list
  1124. length is added, as for slice indices. If it is still negative, it is truncated
  1125. to zero, as for slice indices.
  1126. .. versionchanged:: 2.3
  1127. Previously, :meth:`index` didn't have arguments for specifying start and stop
  1128. positions.
  1129. (5)
  1130. When a negative index is passed as the first parameter to the :meth:`insert`
  1131. method, the list length is added, as for slice indices. If it is still
  1132. negative, it is truncated to zero, as for slice indices.
  1133. .. versionchanged:: 2.3
  1134. Previously, all negative indices were truncated to zero.
  1135. (6)
  1136. The :meth:`pop` method is only supported by the list and array types. The
  1137. optional argument *i* defaults to ``-1``, so that by default the last item is
  1138. removed and returned.
  1139. (7)
  1140. The :meth:`sort` and :meth:`reverse` methods modify the list in place for
  1141. economy of space when sorting or reversing a large list. To remind you that
  1142. they operate by side effect, they don't return the sorted or reversed list.
  1143. (8)
  1144. The :meth:`sort` method takes optional arguments for controlling the
  1145. comparisons.
  1146. *cmp* specifies a custom comparison function of two arguments (list items) which
  1147. should return a negative, zero or positive number depending on whether the first
  1148. argument is considered smaller than, equal to, or larger than the second
  1149. argument: ``cmp=lambda x,y: cmp(x.lower(), y.lower())``. The default value
  1150. is ``None``.
  1151. *key* specifies a function of one argument that is used to extract a comparison
  1152. key from each list element: ``key=str.lower``. The default value is ``None``.
  1153. *reverse* is a boolean value. If set to ``True``, then the list elements are
  1154. sorted as if each comparison were reversed.
  1155. In general, the *key* and *reverse* conversion processes are much faster than
  1156. specifying an equivalent *cmp* function. This is because *cmp* is called
  1157. multiple times for each list element while *key* and *reverse* touch each
  1158. element only once.
  1159. .. versionchanged:: 2.3
  1160. Support for ``None`` as an equivalent to omitting *cmp* was added.
  1161. .. versionchanged:: 2.4
  1162. Support for *key* and *reverse* was added.
  1163. (9)
  1164. Starting with Python 2.3, the :meth:`sort` method is guaranteed to be stable. A
  1165. sort is stable if it guarantees not to change the relative order of elements
  1166. that compare equal --- this is helpful for sorting in multiple passes (for
  1167. example, sort by department, then by salary grade).
  1168. (10)
  1169. While a list is being sorted, the effect of attempting to mutate, or even
  1170. inspect, the list is undefined. The C implementation of Python 2.3 and newer
  1171. makes the list appear empty for the duration, and raises :exc:`ValueError` if it
  1172. can detect that the list has been mutated during a sort.
  1173. .. _types-set:
  1174. Set Types --- :class:`set`, :class:`frozenset`
  1175. ==============================================
  1176. .. index:: object: set
  1177. A :dfn:`set` object is an unordered collection of distinct :term:`hashable` objects.
  1178. Common uses include membership testing, removing duplicates from a sequence, and
  1179. computing mathematical operations such as intersection, union, difference, and
  1180. symmetric difference.
  1181. (For other containers see the built in :class:`dict`, :class:`list`,
  1182. and :class:`tuple` classes, and the :mod:`collections` module.)
  1183. .. versionadded:: 2.4
  1184. Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in
  1185. set``. Being an unordered collection, sets do not record element position or
  1186. order of insertion. Accordingly, sets do not support indexing, slicing, or
  1187. other sequence-like behavior.
  1188. There are currently two builtin set types, :class:`set` and :class:`frozenset`.
  1189. The :class:`set` type is mutable --- the contents can be changed using methods
  1190. like :meth:`add` and :meth:`remove`. Since it is mutable, it has no hash value
  1191. and cannot be used as either a dictionary key or as an element of another set.
  1192. The :class:`frozenset` type is immutable and :term:`hashable` --- its contents cannot be
  1193. altered after it is created; it can therefore be used as a dictionary key or as
  1194. an element of another set.
  1195. The constructors for both classes work the same:
  1196. .. class:: set([iterable])
  1197. frozenset([iterable])
  1198. Return a new set or frozenset object whose elements are taken from
  1199. *iterable*. The elements of a set must be hashable. To represent sets of
  1200. sets, the inner sets must be :class:`frozenset` objects. If *iterable* is
  1201. not specified, a new empty set is returned.
  1202. Instances of :class:`set` and :class:`frozenset` provide the following
  1203. operations:
  1204. .. describe:: len(s)
  1205. Return the cardinality of set *s*.
  1206. .. describe:: x in s
  1207. Test *x* for membership in *s*.
  1208. .. describe:: x not in s
  1209. Test *x* for non-membership in *s*.
  1210. .. method:: isdisjoint(other)
  1211. Return True if the set has no elements in common with *other*. Sets are
  1212. disjoint if and only if their intersection is the empty set.
  1213. .. versionadded:: 2.6
  1214. .. method:: issubset(other)
  1215. set <= other
  1216. Test whether every element in the set is in *other*.
  1217. .. method:: set < other
  1218. Test whether the set is a true subset of *other*, that is,
  1219. ``set <= other and set != other``.
  1220. .. method:: issuperset(other)
  1221. set >= other
  1222. Test whether every element in *other* is in the set.
  1223. .. method:: set > other
  1224. Test whether the set is a true superset of *other*, that is, ``set >=
  1225. other and set != other``.
  1226. .. method:: union(other, ...)
  1227. set | other | ...
  1228. Return a new set with elements from the set and all others.
  1229. .. versionchanged:: 2.6
  1230. Accepts multiple input iterables.
  1231. .. method:: intersection(other, ...)
  1232. set & other & ...
  1233. Return a new set with elements common to the set and all others.
  1234. .. versionchanged:: 2.6
  1235. Accepts multiple input iterables.
  1236. .. method:: difference(other, ...)
  1237. set - other - ...
  1238. Return a new set with elements in the set that are not in the others.
  1239. .. versionchanged:: 2.6
  1240. Accepts multiple input iterables.
  1241. .. method:: symmetric_difference(other)
  1242. set ^ other
  1243. Return a new set with elements in either the set or *other* but not both.
  1244. .. method:: copy()
  1245. Return a new set with a shallow copy of *s*.
  1246. Note, the non-operator versions of :meth:`union`, :meth:`intersection`,
  1247. :meth:`difference`, and :meth:`symmetric_difference`, :meth:`issubset`, and
  1248. :meth:`issuperset` methods will accept any iterable as an argument. In
  1249. contrast, their operator based counterparts require their arguments to be
  1250. sets. This precludes error-prone constructions like ``set('abc') & 'cbs'``
  1251. in favor of the more readable ``set('abc').intersection('cbs')``.
  1252. Both :class:`set` and :class:`frozenset` support set to set comparisons. Two
  1253. sets are equal if and only if every element of each set is contained in the
  1254. other (each is a subset of the other). A set is less than another set if and
  1255. only if the first set is a proper subset of the second set (is a subset, but
  1256. is not equal). A set is greater than another set if and only if the first set
  1257. is a proper superset of the second set (is a superset, but is not equal).
  1258. Instances of :class:`set` are compared to instances of :class:`frozenset`
  1259. based on their members. For example, ``set('abc') == frozenset('abc')``
  1260. returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``.
  1261. The subset and equality comparisons do not generalize to a complete ordering
  1262. function. For example, any two disjoint sets are not equal and are not
  1263. subsets of each other, so *all* of the following return ``False``: ``a<b``,
  1264. ``a==b``, or ``a>b``. Accordingly, sets do not implement the :meth:`__cmp__`
  1265. method.
  1266. Since sets only define partial ordering (subset relationships), the output of
  1267. the :meth:`list.sort` method is undefined for lists of sets.
  1268. Set elements, like dictionary keys, must be :term:`hashable`.
  1269. Binary operations that mix :class:`set` instances with :class:`frozenset`
  1270. return the type of the first operand. For example: ``frozenset('ab') |
  1271. set('bc')`` returns an instance of :class:`frozenset`.
  1272. The following table lists operations available for :class:`set` that do not
  1273. apply to immutable instances of :class:`frozenset`:
  1274. .. method:: update(other, ...)
  1275. set |= other | ...
  1276. Update the set, adding elements from *other*.
  1277. .. versionchanged:: 2.6
  1278. Accepts multiple input iterables.
  1279. .. method:: intersection_update(other, ...)
  1280. set &= other & ...
  1281. Update the set, keeping only elements found in it and *other*.
  1282. .. versionchanged:: 2.6
  1283. Accepts multiple input iterables.
  1284. .. method:: difference_update(other, ...)
  1285. set -= other | ...
  1286. Update the set, removing elements found in others.
  1287. .. versionchanged:: 2.6
  1288. Accepts multiple input iterables.
  1289. .. method:: symmetric_difference_update(other)
  1290. set ^= other
  1291. Update the set, keeping only elements found in either set, but not in both.
  1292. .. method:: add(elem)
  1293. Add element *elem* to the set.
  1294. .. method:: remove(elem)
  1295. Remove element *elem* from the set. Raises :exc:`KeyError` if *elem* is
  1296. not contained in the set.
  1297. .. method:: discard(elem)
  1298. Remove element *elem* from the set if it is present.
  1299. .. method:: pop()
  1300. Remove and return an arbitrary element from the set. Raises
  1301. :exc:`KeyError` if the set is empty.
  1302. .. method:: clear()
  1303. Remove all elements from the set.
  1304. Note, the non-operator versions of the :meth:`update`,
  1305. :meth:`intersection_update`, :meth:`difference_update`, and
  1306. :meth:`symmetric_difference_update` methods will accept any iterable as an
  1307. argument.
  1308. Note, the *elem* argument to the :meth:`__contains__`, :meth:`remove`, and
  1309. :meth:`discard` methods may be a set. To support searching for an equivalent
  1310. frozenset, the *elem* set is temporarily mutated during the search and then
  1311. restored. During the search, the *elem* set should not be read or mutated
  1312. since it does not have a meaningful value.
  1313. .. seealso::
  1314. :ref:`comparison-to-builtin-set`
  1315. Differences between the :mod:`sets` module and the built-in set types.
  1316. .. _typesmapping:
  1317. Mapping Types --- :class:`dict`
  1318. ===============================
  1319. .. index::
  1320. object: mapping
  1321. object: dictionary
  1322. triple: operations on; mapping; types
  1323. triple: operations on; dictionary; type
  1324. statement: del
  1325. builtin: len
  1326. A :dfn:`mapping` object maps :term:`hashable` values to arbitrary objects.
  1327. Mappings are mutable objects. There is currently only one standard mapping
  1328. type, the :dfn:`dictionary`. (For other containers see the built in
  1329. :class:`list`, :class:`set`, and :class:`tuple` classes, and the
  1330. :mod:`collections` module.)
  1331. A dictionary's keys are *almost* arbitrary values. Values that are not
  1332. :term:`hashable`, that is, values containing lists, dictionaries or other
  1333. mutable types (that are compared by value rather than by object identity) may
  1334. not be used as keys. Numeric types used for keys obey the normal rules for
  1335. numeric comparison: if two numbers compare equal (such as ``1`` and ``1.0``)
  1336. then they can be used interchangeably to index the same dictionary entry. (Note
  1337. however, that since computers store floating-point numbers as approximations it
  1338. is usually unwise to use them as dictionary keys.)
  1339. Dictionaries can be created by placing a comma-separated list of ``key: value``
  1340. pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098:
  1341. 'jack', 4127: 'sjoerd'}``, or by the :class:`dict` constructor.
  1342. .. class:: dict([arg])
  1343. Return a new dictionary initialized from an optional positional argument or from
  1344. a set of keyword arguments. If no arguments are given, return a new empty
  1345. dictionary. If the positional argument *arg* is a mapping object, return a
  1346. dictionary mapping the same keys to the same values as does the mapping object.
  1347. Otherwise the positional argument must be a sequence, a container that supports
  1348. iteration, or an iterator object. The elements of the argument must each also
  1349. be of one of those kinds, and each must in turn contain exactly two objects.
  1350. The first is used as a key in the new dictionary, and the second as the key's
  1351. value. If a given key is seen more than once, the last value associated with it
  1352. is retained in the new dictionary.
  1353. If keyword arguments are given, the keywords themselves with their associated
  1354. values are added as items to the dictionary. If a key is specified both in the
  1355. positional argument and as a keyword argument, the value associated with the
  1356. keyword is retained in the dictionary. For example, these all return a
  1357. dictionary equal to ``{"one": 2, "two": 3}``:
  1358. * ``dict(one=2, two=3)``
  1359. * ``dict({'one': 2, 'two': 3})``
  1360. * ``dict(zip(('one', 'two'), (2, 3)))``
  1361. * ``dict([['two', 3], ['one', 2]])``
  1362. The first example only works for keys that are valid Python
  1363. identifiers; the others work with any valid keys.
  1364. .. versionadded:: 2.2
  1365. .. versionchanged:: 2.3
  1366. Support for building a dictionary from keyword arguments added.
  1367. These are the operations that dictionaries support (and therefore, custom
  1368. mapping types should support too):
  1369. .. describe:: len(d)
  1370. Return the number of items in the dictionary *d*.
  1371. .. describe:: d[key]
  1372. Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key*
  1373. is not in the map.
  1374. .. versionadded:: 2.5
  1375. If a subclass of dict defines a method :meth:`__missing__`, if the key
  1376. *key* is not present, the ``d[key]`` operation calls that method with
  1377. the key *key* as argument. The ``d[key]`` operation then returns or
  1378. raises whatever is returned or raised by the ``__missing__(key)`` call
  1379. if the key is not present. No other operations or methods invoke
  1380. :meth:`__missing__`. If :meth:`__missing__` is not defined,
  1381. :exc:`KeyError` is raised. :meth:`__missing__` must be a method; it
  1382. cannot be an instance variable. For an example, see
  1383. :class:`collections.defaultdict`.
  1384. .. describe:: d[key] = value
  1385. Set ``d[key]`` to *value*.
  1386. .. describe:: del d[key]
  1387. Remove ``d[key]`` from *d*. Raises a :exc:`KeyError` if *key* is not in the
  1388. map.
  1389. .. describe:: key in d
  1390. Return ``True`` if *d* has a key *key*, else ``False``.
  1391. .. versionadded:: 2.2
  1392. .. describe:: key not in d
  1393. Equivalent to ``not key in d``.
  1394. .. versionadded:: 2.2
  1395. .. describe:: iter(d)
  1396. Return an iterator over the keys of the dictionary. This is a shortcut
  1397. for :meth:`iterkeys`.
  1398. .. method:: clear()
  1399. Remove all items from the dictionary.
  1400. .. method:: copy()
  1401. Return a shallow copy of the dictionary.
  1402. .. method:: fromkeys(seq[, value])
  1403. Create a new dictionary with keys from *seq* and values set to *value*.
  1404. :func:`fromkeys` is a class method that returns a new dictionary. *value*
  1405. defaults to ``None``.
  1406. .. versionadded:: 2.3
  1407. .. method:: get(key[, default])
  1408. Return the value for *key* if *key* is in the dictionary, else *default*.
  1409. If *default* is not given, it defaults to ``None``, so that this method
  1410. never raises a :exc:`KeyError`.
  1411. .. method:: has_key(key)
  1412. Test for the presence of *key* in the dictionary. :meth:`has_key` is
  1413. deprecated in favor of ``key in d``.
  1414. .. method:: items()
  1415. Return a copy of the dictionary's list of ``(key, value)`` pairs.
  1416. .. note::
  1417. Keys and values are listed in an arbitrary order which is non-random,
  1418. varies across Python implementations, and depends on the dictionary's
  1419. history of insertions and deletions. If :meth:`items`, :meth:`keys`,
  1420. :meth:`values`, :meth:`iteritems`, :meth:`iterkeys`, and
  1421. :meth:`itervalues` are called with no intervening modifications to the
  1422. dictionary, the lists will directly correspond. This allows the
  1423. creation of ``(value, key)`` pairs using :func:`zip`: ``pairs =
  1424. zip(d.values(), d.keys())``. The same relationship holds for the
  1425. :meth:`iterkeys` and :meth:`itervalues` methods: ``pairs =
  1426. zip(d.itervalues(), d.iterkeys())`` provides the same value for
  1427. ``pairs``. Another way to create the same list is ``pairs = [(v, k) for
  1428. (k, v) in d.iteritems()]``.
  1429. .. method:: iteritems()
  1430. Return an iterator over the dictionary's ``(key, value)`` pairs. See the
  1431. note for :meth:`dict.items`.
  1432. Using :meth:`iteritems` while adding or deleting entries in the dictionary
  1433. may raise a :exc:`RuntimeError` or fail to iterate over all entries.
  1434. .. versionadded:: 2.2
  1435. .. method:: iterkeys()
  1436. Return an iterator over the dictionary's keys. See the note for
  1437. :meth:`dict.items`.
  1438. Using :meth:`iterkeys` while adding or deleting entries in the dictionary
  1439. may raise a :exc:`RuntimeError` or fail to iterate over all entries.
  1440. .. versionadded:: 2.2
  1441. .. method:: itervalues()
  1442. Return an iterator over the dictionary's values. See the note for
  1443. :meth:`dict.items`.
  1444. Using :meth:`itervalues` while adding or deleting entries in the
  1445. dictionary may raise a :exc:`RuntimeError` or fail to iterate over all
  1446. entries.
  1447. .. versionadded:: 2.2
  1448. .. method:: keys()
  1449. Return a copy of the dictionary's list of keys. See the note for
  1450. :meth:`dict.items`.
  1451. .. method:: pop(key[, default])
  1452. If *key* is in the dictionary, remove it and return its value, else return
  1453. *default*. If *default* is not given and *key* is not in the dictionary,
  1454. a :exc:`KeyError` is raised.
  1455. .. versionadded:: 2.3
  1456. .. method:: popitem()
  1457. Remove and return an arbitrary ``(key, value)`` pair from the dictionary.
  1458. :func:`popitem` is useful to destructively iterate over a dictionary, as
  1459. often used in set algorithms. If the dictionary is empty, calling
  1460. :func:`popitem` raises a :exc:`KeyError`.
  1461. .. method:: setdefault(key[, default])
  1462. If *key* is in the dictionary, return its value. If not, insert *key*
  1463. with a value of *default* and return *default*. *default* defaults to
  1464. ``None``.
  1465. .. method:: update([other])
  1466. Update the dictionary with the key/value pairs from *other*, overwriting
  1467. existing keys. Return ``None``.
  1468. :func:`update` accepts either another dictionary object or an iterable of
  1469. key/value pairs (as a tuple or other iterable of length two). If keyword
  1470. arguments are specified, the dictionary is then is updated with those
  1471. key/value pairs: ``d.update(red=1, blue=2)``.
  1472. .. versionchanged:: 2.4
  1473. Allowed the argument to be an iterable of key/value pairs and allowed
  1474. keyword arguments.
  1475. .. method:: values()
  1476. Return a copy of the dictionary's list of values. See the note for
  1477. :meth:`dict.items`.
  1478. .. _bltin-file-objects:
  1479. File Objects
  1480. ============
  1481. .. index::
  1482. object: file
  1483. builtin: file
  1484. module: os
  1485. module: socket
  1486. File objects are implemented using C's ``stdio`` package and can be
  1487. created with the built-in :func:`open` function. File
  1488. objects are also returned by some other built-in functions and methods,
  1489. such as :func:`os.popen` and :func:`os.fdopen` and the :meth:`makefile`
  1490. method of socket objects. Temporary files can be created using the
  1491. :mod:`tempfile` module, and high-level file operations such as copying,
  1492. moving, and deleting files and directories can be achieved with the
  1493. :mod:`shutil` module.
  1494. When a file operation fails for an I/O-related reason, the exception
  1495. :exc:`IOError` is raised. This includes situations where the operation is not
  1496. defined for some reason, like :meth:`seek` on a tty device or writing a file
  1497. opened for reading.
  1498. Files have the following methods:
  1499. .. method:: file.close()
  1500. Close the file. A closed file cannot be read or written any more. Any operation
  1501. which requires that the file be open will raise a :exc:`ValueError` after the
  1502. file has been closed. Calling :meth:`close` more than once is allowed.
  1503. As of Python 2.5, you can avoid having to call this method explicitly if you use
  1504. the :keyword:`with` statement. For example, the following code will
  1505. automatically close *f* when the :keyword:`with` block is exited::
  1506. from __future__ import with_statement # This isn't required in Python 2.6
  1507. with open("hello.txt") as f:
  1508. for line in f:
  1509. print line
  1510. In older versions of Python, you would have needed to do this to get the same
  1511. effect::
  1512. f = open("hello.txt")
  1513. try:
  1514. for line in f:
  1515. print line
  1516. finally:
  1517. f.close()
  1518. .. note::
  1519. Not all "file-like" types in Python support use as a context manager for the
  1520. :keyword:`with` statement. If your code is intended to work with any file-like
  1521. object, you can use the function :func:`contextlib.closing` instead of using
  1522. the object directly.
  1523. .. method:: file.flush()
  1524. Flush the internal buffer, like ``stdio``'s :cfunc:`fflush`. This may be a
  1525. no-op on some file-like objects.
  1526. .. method:: file.fileno()
  1527. .. index::
  1528. pair: file; descriptor
  1529. module: fcntl
  1530. Return the integer "file descriptor" that is used by the underlying
  1531. implementation to request I/O operations from the operating system. This can be
  1532. useful for other, lower level interfaces that use file descriptors, such as the
  1533. :mod:`fcntl` module or :func:`os.read` and friends.
  1534. .. note::
  1535. File-like objects which do not have a real file descriptor should *not* provide
  1536. this method!
  1537. .. method:: file.isatty()
  1538. Return ``True`` if the file is connected to a tty(-like) device, else ``False``.
  1539. .. note::
  1540. If a file-like object is not associated with a real file, this method should
  1541. *not* be implemented.
  1542. .. method:: file.next()
  1543. A file object is its own iterator, for example ``iter(f)`` returns *f* (unless
  1544. *f* is closed). When a file is used as an iterator, typically in a
  1545. :keyword:`for` loop (for example, ``for line in f: print line``), the
  1546. :meth:`next` method is called repeatedly. This method returns the next input
  1547. line, or raises :exc:`StopIteration` when EOF is hit when the file is open for
  1548. reading (behavior is undefined when the file is open for writing). In order to
  1549. make a :keyword:`for` loop the most efficient way of looping over the lines of a
  1550. file (a very common operation), the :meth:`next` method uses a hidden read-ahead
  1551. buffer. As a consequence of using a read-ahead buffer, combining :meth:`next`
  1552. with other file methods (like :meth:`readline`) does not work right. However,
  1553. using :meth:`seek` to reposition the file to an absolute position will flush the
  1554. read-ahead buffer.
  1555. .. versionadded:: 2.3
  1556. .. method:: file.read([size])
  1557. Read at most *size* bytes from the file (less if the read hits EOF before
  1558. obtaining *size* bytes). If the *size* argument is negative or omitted, read
  1559. all data until EOF is reached. The bytes are returned as a string object. An
  1560. empty string is returned when EOF is encountered immediately. (For certain
  1561. files, like ttys, it makes sense to continue reading after an EOF is hit.) Note
  1562. that this method may call the underlying C function :cfunc:`fread` more than
  1563. once in an effort to acquire as close to *size* bytes as possible. Also note
  1564. that when in non-blocking mode, less data than was requested may be
  1565. returned, even if no *size* parameter was given.
  1566. .. note::
  1567. This function is simply a wrapper for the underlying
  1568. :cfunc:`fread` C function, and will behave the same in corner cases,
  1569. such as whether the EOF value is cached.
  1570. .. method:: file.readline([size])
  1571. Read one entire line from the file. A trailing newline character is kept in the
  1572. string (but may be absent when a file ends with an incomplete line). [#]_ If
  1573. the *size* argument is present and non-negative, it is a maximum byte count
  1574. (including the trailing newline) and an incomplete line may be returned. An
  1575. empty string is returned *only* when EOF is encountered immediately.
  1576. .. note::
  1577. Unlike ``stdio``'s :cfunc:`fgets`, the returned string contains null characters
  1578. (``'\0'``) if they occurred in the input.
  1579. .. method:: file.readlines([sizehint])
  1580. Read until EOF using :meth:`readline` and return a list containing the lines
  1581. thus read. If the optional *sizehint* argument is present, instead of
  1582. reading up to EOF, whole lines totalling approximately *sizehint* bytes
  1583. (possibly after rounding up to an internal buffer size) are read. Objects
  1584. implementing a file-like interface may choose to ignore *sizehint* if it
  1585. cannot be implemented, or cannot be implemented efficiently.
  1586. .. method:: file.xreadlines()
  1587. This method returns the same thing as ``iter(f)``.
  1588. .. versionadded:: 2.1
  1589. .. deprecated:: 2.3
  1590. Use ``for line in file`` instead.
  1591. .. method:: file.seek(offset[, whence])
  1592. Set the file's current position, like ``stdio``'s :cfunc:`fseek`. The *whence*
  1593. argument is optional and defaults to ``os.SEEK_SET`` or ``0`` (absolute file
  1594. positioning); other values are ``os.SEEK_CUR`` or ``1`` (seek relative to the
  1595. current position) and ``os.SEEK_END`` or ``2`` (seek relative to the file's
  1596. end). There is no return value.
  1597. For example, ``f.seek(2, os.SEEK_CUR)`` advances the position by two and
  1598. ``f.seek(-3, os.SEEK_END)`` sets the position to the third to last.
  1599. Note that if the file is opened for appending
  1600. (mode ``'a'`` or ``'a+'``), any :meth:`seek` operations will be undone at the
  1601. next write. If the file is only opened for writing in append mode (mode
  1602. ``'a'``), this method is essentially a no-op, but it remains useful for files
  1603. opened in append mode with reading enabled (mode ``'a+'``). If the file is
  1604. opened in text mode (without ``'b'``), only offsets returned by :meth:`tell` are
  1605. legal. Use of other offsets causes undefined behavior.
  1606. Note that not all file objects are seekable.
  1607. .. versionchanged:: 2.6
  1608. Passing float values as offset has been deprecated.
  1609. .. method:: file.tell()
  1610. Return the file's current position, like ``stdio``'s :cfunc:`ftell`.
  1611. .. note::
  1612. On Windows, :meth:`tell` can return illegal values (after an :cfunc:`fgets`)
  1613. when reading files with Unix-style line-endings. Use binary mode (``'rb'``) to
  1614. circumvent this problem.
  1615. .. method:: file.truncate([size])
  1616. Truncate the file's size. If the optional *size* argument is present, the file
  1617. is truncated to (at most) that size. The size defaults to the current position.
  1618. The current file position is not changed. Note that if a specified size exceeds
  1619. the file's current size, the result is platform-dependent: possibilities
  1620. include that the file may remain unchanged, increase to the specified size as if
  1621. zero-filled, or increase to the specified size with undefined new content.
  1622. Availability: Windows, many Unix variants.
  1623. .. method:: file.write(str)
  1624. Write a string to the file. There is no return value. Due to buffering, the
  1625. string may not actually show up in the file until the :meth:`flush` or
  1626. :meth:`close` method is called.
  1627. .. method:: file.writelines(sequence)
  1628. Write a sequence of strings to the file. The sequence can be any iterable
  1629. object producing strings, typically a list of strings. There is no return value.
  1630. (The name is intended to match :meth:`readlines`; :meth:`writelines` does not
  1631. add line separators.)
  1632. Files support the iterator protocol. Each iteration returns the same result as
  1633. ``file.readline()``, and iteration ends when the :meth:`readline` method returns
  1634. an empty string.
  1635. File objects also offer a number of other interesting attributes. These are not
  1636. required for file-like objects, but should be implemented if they make sense for
  1637. the particular object.
  1638. .. attribute:: file.closed
  1639. bool indicating the current state of the file object. This is a read-only
  1640. attribute; the :meth:`close` method changes the value. It may not be available
  1641. on all file-like objects.
  1642. .. attribute:: file.encoding
  1643. The encoding that this file uses. When Unicode strings are written to a file,
  1644. they will be converted to byte strings using this encoding. In addition, when
  1645. the file is connected to a terminal, the attribute gives the encoding that the
  1646. terminal is likely to use (that information might be incorrect if the user has
  1647. misconfigured the terminal). The attribute is read-only and may not be present
  1648. on all file-like objects. It may also be ``None``, in which case the file uses
  1649. the system default encoding for converting Unicode strings.
  1650. .. versionadded:: 2.3
  1651. .. attribute:: file.errors
  1652. The Unicode error handler used along with the encoding.
  1653. .. versionadded:: 2.6
  1654. .. attribute:: file.mode
  1655. The I/O mode for the file. If the file was created using the :func:`open`
  1656. built-in function, this will be the value of the *mode* parameter. This is a
  1657. read-only attribute and may not be present on all file-like objects.
  1658. .. attribute:: file.name
  1659. If the file object was created using :func:`open`, the name of the file.
  1660. Otherwise, some string that indicates the source of the file object, of the
  1661. form ``<...>``. This is a read-only attribute and may not be present on all
  1662. file-like objects.
  1663. .. attribute:: file.newlines
  1664. If Python was built with the :option:`--with-universal-newlines` option to
  1665. :program:`configure` (the default) this read-only attribute exists, and for
  1666. files opened in universal newline read mode it keeps track of the types of
  1667. newlines encountered while reading the file. The values it can take are
  1668. ``'\r'``, ``'\n'``, ``'\r\n'``, ``None`` (unknown, no newlines read yet) or a
  1669. tuple containing all the newline types seen, to indicate that multiple newline
  1670. conventions were encountered. For files not opened in universal newline read
  1671. mode the value of this attribute will be ``None``.
  1672. .. attribute:: file.softspace
  1673. Boolean that indicates whether a space character needs to be printed before
  1674. another value when using the :keyword:`print` statement. Classes that are trying
  1675. to simulate a file object should also have a writable :attr:`softspace`
  1676. attribute, which should be initialized to zero. This will be automatic for most
  1677. classes implemented in Python (care may be needed for objects that override
  1678. attribute access); types implemented in C will have to provide a writable
  1679. :attr:`softspace` attribute.
  1680. .. note::
  1681. This attribute is not used to control the :keyword:`print` statement, but to
  1682. allow the implementation of :keyword:`print` to keep track of its internal
  1683. state.
  1684. .. _typecontextmanager:
  1685. Context Manager Types
  1686. =====================
  1687. .. versionadded:: 2.5
  1688. .. index::
  1689. single: context manager
  1690. single: context management protocol
  1691. single: protocol; context management
  1692. Python's :keyword:`with` statement supports the concept of a runtime context
  1693. defined by a context manager. This is implemented using two separate methods
  1694. that allow user-defined classes to define a runtime context that is entered
  1695. before the statement body is executed and exited when the statement ends.
  1696. The :dfn:`context management protocol` consists of a pair of methods that need
  1697. to be provided for a context manager object to define a runtime context:
  1698. .. method:: contextmanager.__enter__()
  1699. Enter the runtime context and return either this object or another object
  1700. related to the runtime context. The value returned by this method is bound to
  1701. the identifier in the :keyword:`as` clause of :keyword:`with` statements using
  1702. this context manager.
  1703. An example of a context manager that returns itself is a file object. File
  1704. objects return themselves from __enter__() to allow :func:`open` to be used as
  1705. the context expression in a :keyword:`with` statement.
  1706. An example of a context manager that returns a related object is the one
  1707. returned by :func:`decimal.localcontext`. These managers set the active
  1708. decimal context to a copy of the original decimal context and then return the
  1709. copy. This allows changes to be made to the current decimal context in the body
  1710. of the :keyword:`with` statement without affecting code outside the
  1711. :keyword:`with` statement.
  1712. .. method:: contextmanager.__exit__(exc_type, exc_val, exc_tb)
  1713. Exit the runtime context and return a Boolean flag indicating if any exception
  1714. that occurred should be suppressed. If an exception occurred while executing the
  1715. body of the :keyword:`with` statement, the arguments contain the exception type,
  1716. value and traceback information. Otherwise, all three arguments are ``None``.
  1717. Returning a true value from this method will cause the :keyword:`with` statement
  1718. to suppress the exception and continue execution with the statement immediately
  1719. following the :keyword:`with` statement. Otherwise the exception continues
  1720. propagating after this method has finished executing. Exceptions that occur
  1721. during execution of this method will replace any exception that occurred in the
  1722. body of the :keyword:`with` statement.
  1723. The exception passed in should never be reraised explicitly - instead, this
  1724. method should return a false value to indicate that the method completed
  1725. successfully and does not want to suppress the raised exception. This allows
  1726. context management code (such as ``contextlib.nested``) to easily detect whether
  1727. or not an :meth:`__exit__` method has actually failed.
  1728. Python defines several context managers to support easy thread synchronisation,
  1729. prompt closure of files or other objects, and simpler manipulation of the active
  1730. decimal arithmetic context. The specific types are not treated specially beyond
  1731. their implementation of the context management protocol. See the
  1732. :mod:`contextlib` module for some examples.
  1733. Python's :term:`generator`\s and the ``contextlib.contextfactory`` :term:`decorator`
  1734. provide a convenient way to implement these protocols. If a generator function is
  1735. decorated with the ``contextlib.contextfactory`` decorator, it will return a
  1736. context manager implementing the necessary :meth:`__enter__` and
  1737. :meth:`__exit__` methods, rather than the iterator produced by an undecorated
  1738. generator function.
  1739. Note that there is no specific slot for any of these methods in the type
  1740. structure for Python objects in the Python/C API. Extension types wanting to
  1741. define these methods must provide them as a normal Python accessible method.
  1742. Compared to the overhead of setting up the runtime context, the overhead of a
  1743. single class dictionary lookup is negligible.
  1744. .. _typesother:
  1745. Other Built-in Types
  1746. ====================
  1747. The interpreter supports several other kinds of objects. Most of these support
  1748. only one or two operations.
  1749. .. _typesmodules:
  1750. Modules
  1751. -------
  1752. The only special operation on a module is attribute access: ``m.name``, where
  1753. *m* is a module and *name* accesses a name defined in *m*'s symbol table.
  1754. Module attributes can be assigned to. (Note that the :keyword:`import`
  1755. statement is not, strictly speaking, an operation on a module object; ``import
  1756. foo`` does not require a module object named *foo* to exist, rather it requires
  1757. an (external) *definition* for a module named *foo* somewhere.)
  1758. A special member of every module is :attr:`__dict__`. This is the dictionary
  1759. containing the module's symbol table. Modifying this dictionary will actually
  1760. change the module's symbol table, but direct assignment to the :attr:`__dict__`
  1761. attribute is not possible (you can write ``m.__dict__['a'] = 1``, which defines
  1762. ``m.a`` to be ``1``, but you can't write ``m.__dict__ = {}``). Modifying
  1763. :attr:`__dict__` directly is not recommended.
  1764. Modules built into the interpreter are written like this: ``<module 'sys'
  1765. (built-in)>``. If loaded from a file, they are written as ``<module 'os' from
  1766. '/usr/local/lib/pythonX.Y/os.pyc'>``.
  1767. .. _typesobjects:
  1768. Classes and Class Instances
  1769. ---------------------------
  1770. See :ref:`objects` and :ref:`class` for these.
  1771. .. _typesfunctions:
  1772. Functions
  1773. ---------
  1774. Function objects are created by function definitions. The only operation on a
  1775. function object is to call it: ``func(argument-list)``.
  1776. There are really two flavors of function objects: built-in functions and
  1777. user-defined functions. Both support the same operation (to call the function),
  1778. but the implementation is different, hence the different object types.
  1779. See :ref:`function` for more information.
  1780. .. _typesmethods:
  1781. Methods
  1782. -------
  1783. .. index:: object: method
  1784. Methods are functions that are called using the attribute notation. There are
  1785. two flavors: built-in methods (such as :meth:`append` on lists) and class
  1786. instance methods. Built-in methods are described with the types that support
  1787. them.
  1788. The implementation adds two special read-only attributes to class instance
  1789. methods: ``m.im_self`` is the object on which the method operates, and
  1790. ``m.im_func`` is the function implementing the method. Calling ``m(arg-1,
  1791. arg-2, ..., arg-n)`` is completely equivalent to calling ``m.im_func(m.im_self,
  1792. arg-1, arg-2, ..., arg-n)``.
  1793. Class instance methods are either *bound* or *unbound*, referring to whether the
  1794. method was accessed through an instance or a class, respectively. When a method
  1795. is unbound, its ``im_self`` attribute will be ``None`` and if called, an
  1796. explicit ``self`` object must be passed as the first argument. In this case,
  1797. ``self`` must be an instance of the unbound method's class (or a subclass of
  1798. that class), otherwise a :exc:`TypeError` is raised.
  1799. Like function objects, methods objects support getting arbitrary attributes.
  1800. However, since method attributes are actually stored on the underlying function
  1801. object (``meth.im_func``), setting method attributes on either bound or unbound
  1802. methods is disallowed. Attempting to set a method attribute results in a
  1803. :exc:`TypeError` being raised. In order to set a method attribute, you need to
  1804. explicitly set it on the underlying function object::
  1805. class C:
  1806. def method(self):
  1807. pass
  1808. c = C()
  1809. c.method.im_func.whoami = 'my name is c'
  1810. See :ref:`types` for more information.
  1811. .. _bltin-code-objects:
  1812. Code Objects
  1813. ------------
  1814. .. index:: object: code
  1815. .. index::
  1816. builtin: compile
  1817. single: func_code (function object attribute)
  1818. Code objects are used by the implementation to represent "pseudo-compiled"
  1819. executable Python code such as a function body. They differ from function
  1820. objects because they don't contain a reference to their global execution
  1821. environment. Code objects are returned by the built-in :func:`compile` function
  1822. and can be extracted from function objects through their :attr:`func_code`
  1823. attribute. See also the :mod:`code` module.
  1824. .. index::
  1825. statement: exec
  1826. builtin: eval
  1827. A code object can be executed or evaluated by passing it (instead of a source
  1828. string) to the :keyword:`exec` statement or the built-in :func:`eval` function.
  1829. See :ref:`types` for more information.
  1830. .. _bltin-type-objects:
  1831. Type Objects
  1832. ------------
  1833. .. index::
  1834. builtin: type
  1835. module: types
  1836. Type objects represent the various object types. An object's type is accessed
  1837. by the built-in function :func:`type`. There are no special operations on
  1838. types. The standard module :mod:`types` defines names for all standard built-in
  1839. types.
  1840. Types are written like this: ``<type 'int'>``.
  1841. .. _bltin-null-object:
  1842. The Null Object
  1843. ---------------
  1844. This object is returned by functions that don't explicitly return a value. It
  1845. supports no special operations. There is exactly one null object, named
  1846. ``None`` (a built-in name).
  1847. It is written as ``None``.
  1848. .. _bltin-ellipsis-object:
  1849. The Ellipsis Object
  1850. -------------------
  1851. This object is used by extended slice notation (see :ref:`slicings`). It
  1852. supports no special operations. There is exactly one ellipsis object, named
  1853. :const:`Ellipsis` (a built-in name).
  1854. It is written as ``Ellipsis``.
  1855. Boolean Values
  1856. --------------
  1857. Boolean values are the two constant objects ``False`` and ``True``. They are
  1858. used to represent truth values (although other values can also be considered
  1859. false or true). In numeric contexts (for example when used as the argument to
  1860. an arithmetic operator), they behave like the integers 0 and 1, respectively.
  1861. The built-in function :func:`bool` can be used to cast any value to a Boolean,
  1862. if the value can be interpreted as a truth value (see section Truth Value
  1863. Testing above).
  1864. .. index::
  1865. single: False
  1866. single: True
  1867. pair: Boolean; values
  1868. They are written as ``False`` and ``True``, respectively.
  1869. .. _typesinternal:
  1870. Internal Objects
  1871. ----------------
  1872. See :ref:`types` for this information. It describes stack frame objects,
  1873. traceback objects, and slice objects.
  1874. .. _specialattrs:
  1875. Special Attributes
  1876. ==================
  1877. The implementation adds a few special read-only attributes to several object
  1878. types, where they are relevant. Some of these are not reported by the
  1879. :func:`dir` built-in function.
  1880. .. attribute:: object.__dict__
  1881. A dictionary or other mapping object used to store an object's (writable)
  1882. attributes.
  1883. .. attribute:: object.__methods__
  1884. .. deprecated:: 2.2
  1885. Use the built-in function :func:`dir` to get a list of an object's attributes.
  1886. This attribute is no longer available.
  1887. .. attribute:: object.__members__
  1888. .. deprecated:: 2.2
  1889. Use the built-in function :func:`dir` to get a list of an object's attributes.
  1890. This attribute is no longer available.
  1891. .. attribute:: instance.__class__
  1892. The class to which a class instance belongs.
  1893. .. attribute:: class.__bases__
  1894. The tuple of base classes of a class object. If there are no base classes, this
  1895. will be an empty tuple.
  1896. .. attribute:: class.__name__
  1897. The name of the class or type.
  1898. The following attributes are only supported by :term:`new-style class`\ es.
  1899. .. attribute:: class.__mro__
  1900. This attribute is a tuple of classes that are considered when looking for
  1901. base classes during method resolution.
  1902. .. method:: class.mro()
  1903. This method can be overridden by a metaclass to customize the method
  1904. resolution order for its instances. It is called at class instantiation, and
  1905. its result is stored in :attr:`__mro__`.
  1906. .. method:: class.__subclasses__
  1907. Each new-style class keeps a list of weak references to its immediate
  1908. subclasses. This method returns a list of all those references still alive.
  1909. Example::
  1910. >>> int.__subclasses__()
  1911. [<type 'bool'>]
  1912. .. rubric:: Footnotes
  1913. .. [#] Additional information on these special methods may be found in the Python
  1914. Reference Manual (:ref:`customization`).
  1915. .. [#] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and
  1916. similarly for tuples.
  1917. .. [#] They must have since the parser can't tell the type of the operands.
  1918. .. [#] To format only a tuple you should therefore provide a singleton tuple whose only
  1919. element is the tuple to be formatted.
  1920. .. [#] These numbers are fairly arbitrary. They are intended to avoid printing endless
  1921. strings of meaningless digits without hampering correct use and without having
  1922. to know the exact precision of floating point values on a particular machine.
  1923. .. [#] The advantage of leaving the newline on is that returning an empty string is
  1924. then an unambiguous EOF indication. It is also possible (in cases where it
  1925. might matter, for example, if you want to make an exact copy of a file while
  1926. scanning its lines) to tell whether the last line of a file ended in a newline
  1927. or not (yes this happens!).