/Doc/library/stdtypes.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 2723 lines · 1927 code · 796 blank · 0 comment · 0 complexity · b712e452ec171c361e2db790d841e54a MD5 · raw file

Large files are truncated click here to view the full file

  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 positiv