The following sections describe the standard types that are built into theinterpreter.
Note
Historically (until release 2.2), Python’s built-in types have differed fromuser-defined types because it was not possible to use the built-in types as thebasis for object-oriented inheritance. This limitation no longerexists.
The principal built-in types are numerics, sequences, mappings, files, classes,instances and exceptions.
Some operations are supported by several object types; in particular,practically all objects can be compared, tested for truth value, and convertedto a string (with therepr() function or the slightly differentstr() function). The latter function is implicitly used when an object iswritten by theprint() function.
Any object can be tested for truth value, for use in anif orwhile condition or as operand of the Boolean operations below. Thefollowing values are considered false:
None
False
zero of any numeric type, for example,0,0L,0.0,0j.
any empty sequence, for example,'',(),[].
any empty mapping, for example,{}.
instances of user-defined classes, if the class defines a__nonzero__()or__len__() method, when that method returns the integer zero orbool valueFalse.[1]
All other values are considered true — so objects of many types are alwaystrue.
Operations and built-in functions that have a Boolean result always return0orFalse for false and1 orTrue for true, unless otherwise stated.(Important exception: the Boolean operationsor andand always returnone of their operands.)
These are the Boolean operations, ordered by ascending priority:
| Operation | Result | Notes |
|---|---|---|
| xory | ifx is false, theny, elsex | (1) |
| xandy | ifx is false, thenx, elsey | (2) |
| notx | ifx is false, thenTrue,elseFalse | (3) |
Notes:
Comparison operations are supported by all objects. They all have the samepriority (which is higher than that of the Boolean operations). Comparisons canbe chained arbitrarily; for example,x<y<=z is equivalent tox<yandy<=z, except thaty is evaluated only once (but in both casesz is notevaluated at all whenx<y is found to be false).
This table summarizes the comparison operations:
| Operation | Meaning | Notes |
|---|---|---|
| < | strictly less than | |
| <= | less than or equal | |
| > | strictly greater than | |
| >= | greater than or equal | |
| == | equal | |
| != | not equal | (1) |
| is | object identity | |
| isnot | negated object identity |
Notes:
Objects of different types, except different numeric types and different stringtypes, never compare equal; such objects are ordered consistently butarbitrarily (so that sorting a heterogeneous array yields a consistent result).Furthermore, some types (for example, file objects) support only a degeneratenotion of comparison where any two objects of that type are unequal. Again,such objects are ordered arbitrarily but consistently. The<,<=,>and>= operators will raise aTypeError exception when any operand isa complex number.
Instances of a class normally compare as non-equal unless the class defines the__cmp__() method. Refer toBasic customization) for information on theuse of this method to effect object comparisons.
Implementation note: Objects of different types except numbers are orderedby their type names; objects of the same types that don’t support propercomparison are ordered by their address.
Two more operations with the same syntactic priority,in andnotin, aresupported only by sequence types (below).
There are four distinct numeric types:plain integers,longintegers,floating point numbers, andcomplex numbers. Inaddition, Booleans are a subtype of plain integers. Plain integers (also justcalledintegers) are implemented usinglong in C, which givesthem at least 32 bits of precision (sys.maxint is always set to the maximumplain integer value for the current platform, the minimum value is-sys.maxint-1). Long integers have unlimited precision. Floating pointnumbers are implemented usingdouble in C. All bets on their precisionare off unless you happen to know the machine you are working with.
Complex numbers have a real and imaginary part, which are each implemented usingdouble in C. To extract these parts from a complex numberz, usez.real andz.imag.
Numbers are created by numeric literals or as the result of built-in functionsand operators. Unadorned integer literals (including hex and octal numbers)yield plain integers unless the value they denote is too large to be representedas a plain integer, in which case they yield a long integer. Integer literalswith an'L' or'l' suffix yield long integers ('L' is preferredbecause1l looks too much like eleven!). Numeric literals containing adecimal point or an exponent sign yield floating point numbers. Appending'j' or'J' to a numeric literal yields a complex number with a zero realpart. A complex numeric literal is the sum of a real and an imaginary part.
Python fully supports mixed arithmetic: when a binary arithmetic operator hasoperands of different numeric types, the operand with the “narrower” type iswidened to that of the other, where plain integer is narrower than long integeris narrower than floating point is narrower than complex. Comparisons betweennumbers of mixed type use the same rule.[2] The constructorsint(),long(),float(), andcomplex() can be used to produce numbersof a specific type.
All builtin numeric types support the following operations. SeeThe power operator and later sections for the operators’ priorities.
| Operation | Result | Notes |
|---|---|---|
| x+y | sum ofx andy | |
| x-y | difference ofx andy | |
| x*y | product ofx andy | |
| x/y | quotient ofx andy | (1) |
| x//y | (floored) quotient ofx andy | (4)(5) |
| x%y | remainder ofx/y | (4) |
| -x | x negated | |
| +x | x unchanged | |
| abs(x) | absolute value or magnitude ofx | (3) |
| int(x) | x converted to integer | (2) |
| long(x) | x converted to long integer | (2) |
| float(x) | x converted to floating point | (6) |
| complex(re,im) | a complex number with real partre, imaginary partim.im defaults to zero. | |
| c.conjugate() | conjugate of the complex numberc. (Identity on real numbers) | |
| divmod(x,y) | the pair(x//y,x%y) | (3)(4) |
| pow(x,y) | x to the powery | (3)(7) |
| x**y | x to the powery | (7) |
Notes:
For (plain or long) integer division, the result is an integer. The result isalways rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and(-1)/(-2) is 0. Note that the result is a long integer if either operand is along integer, regardless of the numeric value.
Conversion from floating point to (long or plain) integer may round ortruncate as in C; see functionsmath.floor() andmath.ceil() forwell-defined conversions.
Deprecated since version 2.6:Instead, convert floats to long explicitly withtrunc().
SeeBuilt-in Functions for a full description.
Complex floor division operator, modulo operator, anddivmod().
Deprecated since version 2.3:Instead convert to float usingabs() if appropriate.
Also referred to as integer division. The resultant value is a whole integer,though the result’s type is not necessarily int.
float also accepts the strings “nan” and “inf” with an optional prefix “+”or “-” for Not a Number (NaN) and positive or negative infinity.
New in version 2.6.
Python definespow(0,0) and0**0 to be1, as is common forprogramming languages.
Allnumbers.Real types (int,long, andfloat) also include the following operations:
| Operation | Result | Notes |
|---|---|---|
| trunc(x) | x truncated to Integral | |
| round(x[,n]) | x rounded to n digits,rounding half to even. If n isomitted, it defaults to 0. | |
| math.floor(x) | the greatest integral float <=x | |
| math.ceil(x) | the least integral float >=x |
Plain and long integer types support additional operations that make sense onlyfor bit-strings. Negative numbers are treated as their 2’s complement value(for long integers, this assumes a sufficiently large number of bits that nooverflow occurs during the operation).
The priorities of the binary bitwise operations are all lower than the numericoperations and higher than the comparisons; the unary operation~ has thesame priority as the other unary numeric operations (+ and-).
This table lists the bit-string operations sorted in ascending priority:
| Operation | Result | Notes |
|---|---|---|
| x|y | bitwiseor ofx andy | |
| x^y | bitwiseexclusive or ofx andy | |
| x&y | bitwiseand ofx andy | |
| x<<n | x shifted left byn bits | (1)(2) |
| x>>n | x shifted right byn bits | (1)(3) |
| ~x | the bits ofx inverted |
Notes:
The float type has some additional methods.
Return a pair of integers whose ratio is exactly equal to theoriginal float and with a positive denominator. RaisesOverflowError on infinities and aValueError onNaNs.
New in version 2.6.
Two methods support conversion toand from hexadecimal strings. Since Python’s floats are storedinternally as binary numbers, converting a float to or from adecimal string usually involves a small rounding error. Incontrast, hexadecimal strings allow exact representation andspecification of floating-point numbers. This can be useful whendebugging, and in numerical work.
Return a representation of a floating-point number as a hexadecimalstring. For finite floating-point numbers, this representationwill always include a leading0x and a trailingp andexponent.
New in version 2.6.
Class method to return the float represented by a hexadecimalstrings. The strings may have leading and trailingwhitespace.
New in version 2.6.
Note thatfloat.hex() is an instance method, whilefloat.fromhex() is a class method.
A hexadecimal string takes the form:
[sign] ['0x'] integer ['.' fraction] ['p' exponent]
where the optionalsign may by either+ or-,integerandfraction are strings of hexadecimal digits, andexponentis a decimal integer with an optional leading sign. Case is notsignificant, and there must be at least one hexadecimal digit ineither the integer or the fraction. This syntax is similar to thesyntax specified in section 6.4.4.2 of the C99 standard, and also tothe syntax used in Java 1.5 onwards. In particular, the output offloat.hex() is usable as a hexadecimal floating-point literal inC or Java code, and hexadecimal strings produced by C’s%a formatcharacter or Java’sDouble.toHexString are accepted byfloat.fromhex().
Note that the exponent is written in decimal rather than hexadecimal,and that it gives the power of 2 by which to multiply the coefficient.For example, the hexadecimal string0x3.a7p10 represents thefloating-point number(3+10./16+7./16**2)*2.0**10, or3740.0:
>>>float.fromhex('0x3.a7p10')3740.0
Applying the reverse conversion to3740.0 gives a differenthexadecimal string representing the same number:
>>>float.hex(3740.0)'0x1.d380000000000p+11'
New in version 2.2.
Python supports a concept of iteration over containers. This is implementedusing two distinct methods; these are used to allow user-defined classes tosupport iteration. Sequences, described below in more detail, always supportthe iteration methods.
One method needs to be defined for container objects to provide iterationsupport:
The iterator objects themselves are required to support the following twomethods, which together form theiterator protocol:
Python defines several iterator objects to support iteration over general andspecific sequence types, dictionaries, and other more specialized forms. Thespecific types are not important beyond their implementation of the iteratorprotocol.
The intention of the protocol is that once an iterator’snext() methodraisesStopIteration, it will continue to do so on subsequent calls.Implementations that do not obey this property are deemed broken. (Thisconstraint was added in Python 2.3; in Python 2.2, various iterators are brokenaccording to this rule.)
Python’sgenerators provide a convenient way to implement the iteratorprotocol. If a container object’s__iter__() method is implemented as agenerator, it will automatically return an iterator object (technically, agenerator object) supplying the__iter__() andnext() methods.
There are six sequence types: strings, Unicode strings, lists, tuples, buffers,and xrange objects.(For other containers see the built indict,list,set, andtuple classes, and thecollectionsmodule.)
String literals are written in single or double quotes:'xyzzy',"frobozz". SeeString literals for more about string literals.Unicode strings are much like strings, but are specified in the syntaxusing a preceding'u' character:u'abc',u"def". In additionto the functionality described here, there are also string-specificmethods described in theString Methods section. Lists areconstructed with square brackets, separating items with commas:[a,b,c].Tuples are constructed by the comma operator (not within squarebrackets), with or without enclosing parentheses, but an empty tuplemust have the enclosing parentheses, such asa,b,c or(). Asingle item tuple must have a trailing comma, such as(d,).
Buffer objects are not directly supported by Python syntax, but can be createdby calling the builtin functionbuffer(). They don’t supportconcatenation or repetition.
Objects of type xrange are similar to buffers in that there is no specific syntax tocreate them, but they are created using thexrange() function. They don’tsupport slicing, concatenation or repetition, and usingin,notin,min() ormax() on them is inefficient.
Most sequence types support the following operations. Thein andnotinoperations have the same priorities as the comparison operations. The+ and* operations have the same priority as the corresponding numeric operations.[3] Additional methods are provided forMutable Sequence Types.
This table lists the sequence operations sorted in ascending priority(operations in the same box have the same priority). In the table,s andtare sequences of the same type;n,i andj are integers:
| Operation | Result | Notes |
|---|---|---|
| xins | True if an item ofs isequal tox, elseFalse | (1) |
| xnotins | False if an item ofs isequal tox, elseTrue | (1) |
| s+t | the concatenation ofs andt | (6) |
| s*n,n*s | n shallow copies ofsconcatenated | (2) |
| s[i] | i‘th item ofs, origin 0 | (3) |
| s[i:j] | slice ofs fromi toj | (3)(4) |
| s[i:j:k] | slice ofs fromi tojwith stepk | (3)(5) |
| len(s) | length ofs | |
| min(s) | smallest item ofs | |
| max(s) | largest item ofs |
Sequence types also support comparisons. In particular, tuples and listsare compared lexicographically by comparing correspondingelements. This means that to compare equal, every element must compareequal and the two sequences must be of the same type and have the samelength. (For full details seeComparisons in the languagereference.)
Notes:
Whens is a string or Unicode string object thein andnotinoperations act like a substring test. In Python versions before 2.3,x had tobe a string of length 1. In Python 2.3 and beyond,x may be a string of anylength.
Values ofn less than0 are treated as0 (which yields an emptysequence of the same type ass). Note also that the copies are shallow;nested structures are not copied. This often haunts new Python programmers;consider:
>>>lists=[[]]*3>>>lists[[], [], []]>>>lists[0].append(3)>>>lists[[3], [3], [3]]
What has happened is that[[]] is a one-element list containing an emptylist, so all three elements of[[]]*3 are (pointers to) this single emptylist. Modifying any of the elements oflists modifies this single list.You can create a list of different lists this way:
>>>lists=[[]foriinrange(3)]>>>lists[0].append(3)>>>lists[1].append(5)>>>lists[2].append(7)>>>lists[[3], [5], [7]]
Ifi orj is negative, the index is relative to the end of the string:len(s)+i orlen(s)+j is substituted. But note that-0 is still0.
The slice ofs fromi toj is defined as the sequence of items with indexk such thati<=k<j. Ifi orj is greater thanlen(s), uselen(s). Ifi is omitted orNone, use0. Ifj is omitted orNone, uselen(s). Ifi is greater than or equal toj, the slice isempty.
The slice ofs fromi toj with stepk is defined as the sequence ofitems with indexx=i+n*k such that0<=n<(j-i)/k. In other words,the indices arei,i+k,i+2*k,i+3*k and so on, stopping whenj is reached (but never includingj). Ifi orj is greater thanlen(s), uselen(s). Ifi orj are omitted orNone, they become“end” values (which end depends on the sign ofk). Note,k cannot be zero.Ifk isNone, it is treated like1.
Ifs andt are both strings, some Python implementations such as CPython canusually perform an in-place optimization for assignments of the forms=s+tors+=t. When applicable, this optimization makes quadratic run-time muchless likely. This optimization is both version and implementation dependent.For performance sensitive code, it is preferable to use thestr.join()method which assures consistent linear concatenation performance across versionsand implementations.
Changed in version 2.4:Formerly, string concatenation never occurred in-place.
Below are listed the string methods which both 8-bit strings and Unicode objectssupport. Note that none of these methods take keyword arguments.
In addition, Python’s strings support the sequence type methodsdescribed in theSequence Types — str, unicode, list, tuple, buffer, xrange section. To output formatted stringsuse template strings or the% operator described in theString Formatting Operations section. Also, see there module forstring functions based on regular expressions.
Return a copy of the string with only its first character capitalized.
For 8-bit strings, this method is locale-dependent.
Return centered in a string of lengthwidth. Padding is done using thespecifiedfillchar (default is a space).
Changed in version 2.4:Support for thefillchar argument.
Decodes the string using the codec registered forencoding.encodingdefaults to the default string encoding.errors may be given to set adifferent error handling scheme. The default is'strict', meaning thatencoding errors raiseUnicodeError. Other possible values are'ignore','replace' and any other name registered viacodecs.register_error(), see sectionCodec Base Classes.
New in version 2.2.
Changed in version 2.3:Support for other error handling schemes added.
Return an encoded version of the string. Default encoding is the currentdefault string encoding.errors may be given to set a different errorhandling scheme. The default forerrors is'strict', meaning thatencoding errors raise aUnicodeError. Other possible values are'ignore','replace','xmlcharrefreplace','backslashreplace' andany other name registered viacodecs.register_error(), see sectionCodec Base Classes. For a list of possible encodings, see sectionStandard Encodings.
New in version 2.0.
Changed in version 2.3:Support for'xmlcharrefreplace' and'backslashreplace' and other errorhandling schemes added.
ReturnTrue if the string ends with the specifiedsuffix, otherwise returnFalse.suffix can also be a tuple of suffixes to look for. With optionalstart, test beginning at that position. With optionalend, stop comparingat that position.
Changed in version 2.5:Accept tuples assuffix.
Perform a string formatting operation. Theformat_string argument cancontain literal text or replacement fields delimited by braces{}. Eachreplacement field contains either the numeric index of a positional argument,or the name of a keyword argument. Returns a copy offormat_string whereeach replacement field is replaced with the string value of the correspondingargument.
>>>"The sum of 1 + 2 is {0}".format(1+2)'The sum of 1 + 2 is 3'
SeeFormat String Syntax for a description of the various formatting optionsthat can be specified in format strings.
This method of string formatting is the new standard in Python 3.0, andshould be preferred to the% formatting described inString Formatting Operations in new code.
New in version 2.6.
Return true if all characters in the string are alphanumeric and there is atleast one character, false otherwise.
For 8-bit strings, this method is locale-dependent.
Return true if all characters in the string are alphabetic and there is at leastone character, false otherwise.
For 8-bit strings, this method is locale-dependent.
Return true if all characters in the string are digits and there is at least onecharacter, false otherwise.
For 8-bit strings, this method is locale-dependent.
Return true if all cased characters in the string are lowercase and there is atleast one cased character, false otherwise.
For 8-bit strings, this method is locale-dependent.
Return true if there are only whitespace characters in the string and there isat least one character, false otherwise.
For 8-bit strings, this method is locale-dependent.
Return true if the string is a titlecased string and there is at least onecharacter, for example uppercase characters may only follow uncased charactersand lowercase characters only cased ones. Return false otherwise.
For 8-bit strings, this method is locale-dependent.
Return true if all cased characters in the string are uppercase and there is atleast one cased character, false otherwise.
For 8-bit strings, this method is locale-dependent.
Return the string left justified in a string of lengthwidth. Padding is doneusing the specifiedfillchar (default is a space). The original string isreturned ifwidth is less thanlen(s).
Changed in version 2.4:Support for thefillchar argument.
Return a copy of the string converted to lowercase.
For 8-bit strings, this method is locale-dependent.
Return a copy of the string with leading characters removed. Thecharsargument is a string specifying the set of characters to be removed. If omittedorNone, thechars argument defaults to removing whitespace. Thecharsargument is not a prefix; rather, all combinations of its values are stripped:
>>>' spacious '.lstrip()'spacious '>>>'www.example.com'.lstrip('cmowz.')'example.com'
Changed in version 2.2.2:Support for thechars argument.
Split the string at the first occurrence ofsep, and return a 3-tuplecontaining the part before the separator, the separator itself, and the partafter the separator. If the separator is not found, return a 3-tuple containingthe string itself, followed by two empty strings.
New in version 2.5.
Return the string right justified in a string of lengthwidth. Padding is doneusing the specifiedfillchar (default is a space). The original string isreturned ifwidth is less thanlen(s).
Changed in version 2.4:Support for thefillchar argument.
Split the string at the last occurrence ofsep, and return a 3-tuplecontaining the part before the separator, the separator itself, and the partafter the separator. If the separator is not found, return a 3-tuple containingtwo empty strings, followed by the string itself.
New in version 2.5.
Return a list of the words in the string, usingsep as the delimiter string.Ifmaxsplit is given, at mostmaxsplit splits are done, therightmostones. Ifsep is not specified orNone, any whitespace string is aseparator. Except for splitting from the right,rsplit() behaves likesplit() which is described in detail below.
New in version 2.4.
Return a copy of the string with trailing characters removed. Thecharsargument is a string specifying the set of characters to be removed. If omittedorNone, thechars argument defaults to removing whitespace. Thecharsargument is not a suffix; rather, all combinations of its values are stripped:
>>>' spacious '.rstrip()' spacious'>>>'mississippi'.rstrip('ipz')'mississ'
Changed in version 2.2.2:Support for thechars argument.
Return a list of the words in the string, usingsep as the delimiterstring. Ifmaxsplit is given, at mostmaxsplit splits are done (thus,the list will have at mostmaxsplit+1 elements). Ifmaxsplit is notspecified, then there is no limit on the number of splits (all possiblesplits are made).
Ifsep is given, consecutive delimiters are not grouped together and aredeemed to delimit empty strings (for example,'1,,2'.split(',') returns['1','','2']). Thesep argument may consist of multiple characters(for example,'1<>2<>3'.split('<>') returns['1','2','3']).Splitting an empty string with a specified separator returns[''].
Ifsep is not specified or isNone, a different splitting algorithm isapplied: runs of consecutive whitespace are regarded as a single separator,and the result will contain no empty strings at the start or end if thestring has leading or trailing whitespace. Consequently, splitting an emptystring or a string consisting of just whitespace with aNone separatorreturns[].
For example,'1 2 3 '.split() returns['1','2','3'], and' 1 2 3 '.split(None,1) returns['1','2 3 '].
ReturnTrue if string starts with theprefix, otherwise returnFalse.prefix can also be a tuple of prefixes to look for. With optionalstart,test string beginning at that position. With optionalend, stop comparingstring at that position.
Changed in version 2.5:Accept tuples asprefix.
Return a copy of the string with the leading and trailing characters removed.Thechars argument is a string specifying the set of characters to be removed.If omitted orNone, thechars argument defaults to removing whitespace.Thechars argument is not a prefix or suffix; rather, all combinations of itsvalues are stripped:
>>>' spacious '.strip()'spacious'>>>'www.example.com'.strip('cmowz.')'example'
Changed in version 2.2.2:Support for thechars argument.
Return a copy of the string with uppercase characters converted to lowercase andvice versa.
For 8-bit strings, this method is locale-dependent.
Return a titlecased version of the string: words start with uppercasecharacters, all remaining cased characters are lowercase.
For 8-bit strings, this method is locale-dependent.
Return a copy of the string where all characters occurring in the optionalargumentdeletechars are removed, and the remaining characters have beenmapped through the given translation table, which must be a string of length256.
You can use themaketrans() helper function in thestring module tocreate a translation table. For string objects, set thetable argument toNone for translations that only delete characters:
>>>'read this short text'.translate(None,'aeiou')'rd ths shrt txt'
New in version 2.6:Support for aNonetable argument.
For Unicode objects, thetranslate() method does not accept the optionaldeletechars argument. Instead, it returns a copy of thes where allcharacters have been mapped through the given translation table which must be amapping of Unicode ordinals to Unicode ordinals, Unicode strings orNone.Unmapped characters are left untouched. Characters mapped toNone aredeleted. Note, a more flexible approach is to create a custom character mappingcodec using thecodecs module (seeencodings.cp1251 for anexample).
Return a copy of the string converted to uppercase.
For 8-bit strings, this method is locale-dependent.
Return the numeric string left filled with zeros in a string of lengthwidth. A sign prefix is handled correctly. The original string isreturned ifwidth is less thanlen(s).
New in version 2.2.2.
The following methods are present only on unicode objects:
String and Unicode objects have one unique built-in operation: the%operator (modulo). This is also known as the stringformatting orinterpolation operator. Givenformat%values (whereformat is a stringor Unicode object),% conversion specifications informat are replacedwith zero or more elements ofvalues. The effect is similar to the usingsprintf in the C language. Ifformat is a Unicode object, or if anyof the objects being converted using the%s conversion are Unicode objects,the result will also be a Unicode object.
Ifformat requires a single argument,values may be a single non-tupleobject.[4] Otherwise,values must be a tuple with exactly the number ofitems specified by the format string, or a single mapping object (for example, adictionary).
A conversion specifier contains two or more characters and has the followingcomponents, which must occur in this order:
When the right argument is a dictionary (or other mapping type), then theformats in the stringmust include a parenthesised mapping key into thatdictionary inserted immediately after the'%' character. The mapping keyselects the value to be formatted from the mapping. For example:
>>>print'%(language)s has %(#)03d quote types.'% \...{'language':"Python","#":2}Python has 002 quote types.
In this case no* specifiers may occur in a format (since they require asequential parameter list).
The conversion flag characters are:
| Flag | Meaning |
|---|---|
| '#' | The value conversion will use the “alternate form” (where definedbelow). |
| '0' | The conversion will be zero padded for numeric values. |
| '-' | The converted value is left adjusted (overrides the'0'conversion if both are given). |
| '' | (a space) A blank should be left before a positive number (or emptystring) produced by a signed conversion. |
| '+' | A sign character ('+' or'-') will precede the conversion(overrides a “space” flag). |
A length modifier (h,l, orL) may be present, but is ignored as itis not necessary for Python – so e.g.%ld is identical to%d.
The conversion types are:
| Conversion | Meaning | Notes |
|---|---|---|
| 'd' | Signed integer decimal. | |
| 'i' | Signed integer decimal. | |
| 'o' | Signed octal value. | (1) |
| 'u' | Obselete type – it is identical to'd'. | (7) |
| 'x' | Signed hexadecimal (lowercase). | (2) |
| 'X' | Signed hexadecimal (uppercase). | (2) |
| 'e' | Floating point exponential format (lowercase). | (3) |
| 'E' | Floating point exponential format (uppercase). | (3) |
| 'f' | Floating point decimal format. | (3) |
| 'F' | Floating point decimal format. | (3) |
| 'g' | Floating point format. Uses lowercase exponentialformat if exponent is less than -4 or not less thanprecision, decimal format otherwise. | (4) |
| 'G' | Floating point format. Uses uppercase exponentialformat if exponent is less than -4 or not less thanprecision, decimal format otherwise. | (4) |
| 'c' | Single character (accepts integer or singlecharacter string). | |
| 'r' | String (converts any python object usingrepr()). | (5) |
| 's' | String (converts any python object usingstr()). | (6) |
| '%' | No argument is converted, results in a'%'character in the result. |
Notes:
The alternate form causes a leading zero ('0') to be inserted betweenleft-hand padding and the formatting of the number if the leading characterof the result is not already a zero.
The alternate form causes a leading'0x' or'0X' (depending on whetherthe'x' or'X' format was used) to be inserted between left-hand paddingand the formatting of the number if the leading character of the result is notalready a zero.
The alternate form causes the result to always contain a decimal point, even ifno digits follow it.
The precision determines the number of digits after the decimal point anddefaults to 6.
The alternate form causes the result to always contain a decimal point, andtrailing zeroes are not removed as they would otherwise be.
The precision determines the number of significant digits before and after thedecimal point and defaults to 6.
The%r conversion was added in Python 2.0.
The precision determines the maximal number of characters used.
If the object or format provided is aunicode string, the resultingstring will also beunicode.
The precision determines the maximal number of characters used.
SeePEP 237.
Since Python strings have an explicit length,%s conversions do not assumethat'\0' is the end of the string.
For safety reasons, floating point precisions are clipped to 50;%fconversions for numbers whose absolute value is over 1e25 are replaced by%gconversions.[5] All other errors raise exceptions.
Additional string operations are defined in standard modulesstring andre.
Thexrange type is an immutable sequence which is commonly used forlooping. The advantage of thexrange type is that anxrangeobject will always take the same amount of memory, no matter the size of therange it represents. There are no consistent performance advantages.
XRange objects have very little behavior: they only support indexing, iteration,and thelen() function.
List objects support additional operations that allow in-place modification ofthe object. Other mutable sequence types (when added to the language) shouldalso support these operations. Strings and tuples are immutable sequence types:such objects cannot be modified once created. The following operations aredefined on mutable sequence types (wherex is an arbitrary object):
| Operation | Result | Notes |
|---|---|---|
| s[i]=x | itemi ofs is replaced byx | |
| s[i:j]=t | slice ofs fromi tojis replaced by the contents ofthe iterablet | |
| dels[i:j] | same ass[i:j]=[] | |
| s[i:j:k]=t | the elements ofs[i:j:k]are replaced by those oft | (1) |
| dels[i:j:k] | removes the elements ofs[i:j:k] from the list | |
| s.append(x) | same ass[len(s):len(s)]=[x] | (2) |
| s.extend(x) | same ass[len(s):len(s)]=x | (3) |
| s.count(x) | return number ofi‘s forwhichs[i]==x | |
| s.index(x[,i[,j]]) | return smallestk such thats[k]==x andi<=k<j | (4) |
| s.insert(i,x) | same ass[i:i]=[x] | (5) |
| s.pop([i]) | same asx=s[i];dels[i];returnx | (6) |
| s.remove(x) | same asdels[s.index(x)] | (4) |
| s.reverse() | reverses the items ofs inplace | (7) |
| s.sort([cmp[,key[,reverse]]]) | sort the items ofs in place | (7)(8)(9)(10) |
Notes:
t must have the same length as the slice it is replacing.
The C implementation of Python has historically accepted multiple parameters andimplicitly joined them into a tuple; this no longer works in Python 2.0. Use ofthis misfeature has been deprecated since Python 1.4.
x can be any iterable object.
RaisesValueError whenx is not found ins. When a negative index ispassed as the second or third parameter to theindex() method, the listlength is added, as for slice indices. If it is still negative, it is truncatedto zero, as for slice indices.
Changed in version 2.3:Previously,index() didn’t have arguments for specifying start and stoppositions.
When a negative index is passed as the first parameter to theinsert()method, the list length is added, as for slice indices. If it is stillnegative, it is truncated to zero, as for slice indices.
Changed in version 2.3:Previously, all negative indices were truncated to zero.
Thepop() method is only supported by the list and array types. Theoptional argumenti defaults to-1, so that by default the last item isremoved and returned.
Thesort() andreverse() methods modify the list in place foreconomy of space when sorting or reversing a large list. To remind you thatthey operate by side effect, they don’t return the sorted or reversed list.
Thesort() method takes optional arguments for controlling thecomparisons.
cmp specifies a custom comparison function of two arguments (list items) whichshould return a negative, zero or positive number depending on whether the firstargument is considered smaller than, equal to, or larger than the secondargument:cmp=lambdax,y:cmp(x.lower(),y.lower()). The default valueisNone.
key specifies a function of one argument that is used to extract a comparisonkey from each list element:key=str.lower. The default value isNone.
reverse is a boolean value. If set toTrue, then the list elements aresorted as if each comparison were reversed.
In general, thekey andreverse conversion processes are much faster thanspecifying an equivalentcmp function. This is becausecmp is calledmultiple times for each list element whilekey andreverse touch eachelement only once.
Changed in version 2.3:Support forNone as an equivalent to omittingcmp was added.
Changed in version 2.4:Support forkey andreverse was added.
Starting with Python 2.3, thesort() method is guaranteed to be stable. Asort is stable if it guarantees not to change the relative order of elementsthat compare equal — this is helpful for sorting in multiple passes (forexample, sort by department, then by salary grade).
While a list is being sorted, the effect of attempting to mutate, or eveninspect, the list is undefined. The C implementation of Python 2.3 and newermakes the list appear empty for the duration, and raisesValueError if itcan detect that the list has been mutated during a sort.
Aset object is an unordered collection of distincthashable objects.Common uses include membership testing, removing duplicates from a sequence, andcomputing mathematical operations such as intersection, union, difference, andsymmetric difference.(For other containers see the built indict,list,andtuple classes, and thecollections module.)
New in version 2.4.
Like other collections, sets supportxinset,len(set), andforxinset. Being an unordered collection, sets do not record element position ororder of insertion. Accordingly, sets do not support indexing, slicing, orother sequence-like behavior.
There are currently two builtin set types,set andfrozenset.Theset type is mutable — the contents can be changed using methodslikeadd() andremove(). Since it is mutable, it has no hash valueand cannot be used as either a dictionary key or as an element of another set.Thefrozenset type is immutable andhashable — its contents cannot bealtered after it is created; it can therefore be used as a dictionary key or asan element of another set.
The constructors for both classes work the same:
Return a new set or frozenset object whose elements are taken fromiterable. The elements of a set must be hashable. To represent sets ofsets, the inner sets must befrozenset objects. Ifiterable isnot specified, a new empty set is returned.
Instances ofset andfrozenset provide the followingoperations:
Return True if the set has no elements in common withother. Sets aredisjoint if and only if their intersection is the empty set.
New in version 2.6.
Return a new set with elements from both sets.
Changed in version 2.6:Accepts multiple input iterables.
Return a new set with elements common to both sets.
Changed in version 2.6:Accepts multiple input iterables.
Return a new set with elements in the set that are not in the others.
Changed in version 2.6:Accepts multiple input iterables.
Note, the non-operator versions ofunion(),intersection(),difference(), andsymmetric_difference(),issubset(), andissuperset() methods will accept any iterable as an argument. Incontrast, their operator based counterparts require their arguments to besets. This precludes error-prone constructions likeset('abc')&'cbs'in favor of the more readableset('abc').intersection('cbs').
Bothset andfrozenset support set to set comparisons. Twosets are equal if and only if every element of each set is contained in theother (each is a subset of the other). A set is less than another set if andonly if the first set is a proper subset of the second set (is a subset, butis not equal). A set is greater than another set if and only if the first setis a proper superset of the second set (is a superset, but is not equal).
Instances ofset are compared to instances offrozensetbased on their members. For example,set('abc')==frozenset('abc')returnsTrue and so doesset('abc')inset([frozenset('abc')]).
The subset and equality comparisons do not generalize to a complete orderingfunction. For example, any two disjoint sets are not equal and are notsubsets of each other, soall of the following returnFalse:a<b,a==b, ora>b. Accordingly, sets do not implement the__cmp__()method.
Since sets only define partial ordering (subset relationships), the output ofthelist.sort() method is undefined for lists of sets.
Set elements, like dictionary keys, must behashable.
Binary operations that mixset instances withfrozensetreturn the type of the first operand. For example:frozenset('ab')|set('bc') returns an instance offrozenset.
The following table lists operations available forset that do notapply to immutable instances offrozenset:
Update the set, adding elements fromother.
Changed in version 2.6:Accepts multiple input iterables.
Update the set, keeping only elements found in it andother.
Changed in version 2.6:Accepts multiple input iterables.
Update the set, removing elements found in others.
Changed in version 2.6:Accepts multiple input iterables.
Note, the non-operator versions of theupdate(),intersection_update(),difference_update(), andsymmetric_difference_update() methods will accept any iterable as anargument.
Note, theelem argument to the__contains__(),remove(), anddiscard() methods may be a set. To support searching for an equivalentfrozenset, theelem set is temporarily mutated during the search and thenrestored. During the search, theelem set should not be read or mutatedsince it does not have a meaningful value.
See also
Amapping object mapshashable values to arbitrary objects.Mappings are mutable objects. There is currently only one standard mappingtype, thedictionary. (For other containers see the built inlist,set, andtuple classes, and thecollections module.)
A dictionary’s keys arealmost arbitrary values. Values that are nothashable, that is, values containing lists, dictionaries or othermutable types (that are compared by value rather than by object identity) maynot be used as keys. Numeric types used for keys obey the normal rules fornumeric comparison: if two numbers compare equal (such as1 and1.0)then they can be used interchangeably to index the same dictionary entry. (Notehowever, that since computers store floating-point numbers as approximations itis usually unwise to use them as dictionary keys.)
Dictionaries can be created by placing a comma-separated list ofkey:valuepairs within braces, for example:{'jack':4098,'sjoerd':4127} or{4098:'jack',4127:'sjoerd'}, or by thedict constructor.
Return a new dictionary initialized from an optional positional argument or froma set of keyword arguments. If no arguments are given, return a new emptydictionary. If the positional argumentarg is a mapping object, return adictionary mapping the same keys to the same values as does the mapping object.Otherwise the positional argument must be a sequence, a container that supportsiteration, or an iterator object. The elements of the argument must each alsobe of one of those kinds, and each must in turn contain exactly two objects.The first is used as a key in the new dictionary, and the second as the key’svalue. If a given key is seen more than once, the last value associated with itis retained in the new dictionary.
If keyword arguments are given, the keywords themselves with their associatedvalues are added as items to the dictionary. If a key is specified both in thepositional argument and as a keyword argument, the value associated with thekeyword is retained in the dictionary. For example, these all return adictionary equal to{"one":2,"two":3}:
The first example only works for keys that are valid Pythonidentifiers; the others work with any valid keys.
New in version 2.2.
Changed in version 2.3:Support for building a dictionary from keyword arguments added.
These are the operations that dictionaries support (and therefore, custommapping types should support too):
Return the item ofd with keykey. Raises aKeyError ifkeyis not in the map.
New in version 2.5:If a subclass of dict defines a method__missing__(), if the keykey is not present, thed[key] operation calls that method withthe keykey as argument. Thed[key] operation then returns orraises whatever is returned or raised by the__missing__(key) callif the key is not present. No other operations or methods invoke__missing__(). If__missing__() is not defined,KeyError is raised.__missing__() must be a method; itcannot be an instance variable. For an example, seecollections.defaultdict.
ReturnTrue ifd has a keykey, elseFalse.
New in version 2.2.
Equivalent tonotkeyind.
New in version 2.2.
Create a new dictionary with keys fromseq and values set tovalue.
fromkeys() is a class method that returns a new dictionary.valuedefaults toNone.
New in version 2.3.
Return a copy of the dictionary’s list of(key,value) pairs.
Note
Keys and values are listed in an arbitrary order which is non-random,varies across Python implementations, and depends on the dictionary’shistory of insertions and deletions. Ifitems(),keys(),values(),iteritems(),iterkeys(), anditervalues() are called with no intervening modifications to thedictionary, the lists will directly correspond. This allows thecreation of(value,key) pairs usingzip():pairs=zip(d.values(),d.keys()). The same relationship holds for theiterkeys() anditervalues() methods:pairs=zip(d.itervalues(),d.iterkeys()) provides the same value forpairs. Another way to create the same list ispairs=[(v,k)for(k,v)ind.iteritems()].
Return an iterator over the dictionary’s(key,value) pairs. See thenote fordict.items().
New in version 2.2.
Return an iterator over the dictionary’s keys. See the note fordict.items().
New in version 2.2.
Return an iterator over the dictionary’s values. See the note fordict.items().
New in version 2.2.
Ifkey is in the dictionary, remove it and return its value, else returndefault. Ifdefault is not given andkey is not in the dictionary,aKeyError is raised.
New in version 2.3.
Remove and return an arbitrary(key,value) pair from the dictionary.
popitem() is useful to destructively iterate over a dictionary, asoften used in set algorithms. If the dictionary is empty, callingpopitem() raises aKeyError.
Update the dictionary with the key/value pairs fromother, overwritingexisting keys. ReturnNone.
update() accepts either another dictionary object or an iterable ofkey/value pairs (as a tuple or other iterable of length two). If keywordarguments are specified, the dictionary is then is updated with thosekey/value pairs:d.update(red=1,blue=2).
Changed in version 2.4:Allowed the argument to be an iterable of key/value pairs and allowedkeyword arguments.
File objects are implemented using C’sstdio package and can becreated with the built-inopen() function. Fileobjects are also returned by some other built-in functions and methods,such asos.popen() andos.fdopen() and themakefile()method of socket objects. Temporary files can be created using thetempfile module, and high-level file operations such as copying,moving, and deleting files and directories can be achieved with theshutil module.
When a file operation fails for an I/O-related reason, the exceptionIOError is raised. This includes situations where the operation is notdefined for some reason, likeseek() on a tty device or writing a fileopened for reading.
Files have the following methods:
Close the file. A closed file cannot be read or written any more. Any operationwhich requires that the file be open will raise aValueError after thefile has been closed. Callingclose() more than once is allowed.
As of Python 2.5, you can avoid having to call this method explicitly if you usethewith statement. For example, the following code willautomatically closef when thewith block is exited:
from__future__importwith_statement# This isn't required in Python 2.6withopen("hello.txt")asf:forlineinf:printline
In older versions of Python, you would have needed to do this to get the sameeffect:
f=open("hello.txt")try:forlineinf:printlinefinally:f.close()
Note
Not all “file-like” types in Python support use as a context manager for thewith statement. If your code is intended to work with any file-likeobject, you can use the functioncontextlib.closing() instead of usingthe object directly.
Return the integer “file descriptor” that is used by the underlyingimplementation to request I/O operations from the operating system. This can beuseful for other, lower level interfaces that use file descriptors, such as thefcntl module oros.read() and friends.
Note
File-like objects which do not have a real file descriptor shouldnot providethis method!
ReturnTrue if the file is connected to a tty(-like) device, elseFalse.
Note
If a file-like object is not associated with a real file, this method shouldnot be implemented.
A file object is its own iterator, for exampleiter(f) returnsf (unlessf is closed). When a file is used as an iterator, typically in afor loop (for example,forlineinf:printline), thenext() method is called repeatedly. This method returns the next inputline, or raisesStopIteration when EOF is hit when the file is open forreading (behavior is undefined when the file is open for writing). In order tomake afor loop the most efficient way of looping over the lines of afile (a very common operation), thenext() method uses a hidden read-aheadbuffer. As a consequence of using a read-ahead buffer, combiningnext()with other file methods (likereadline()) does not work right. However,usingseek() to reposition the file to an absolute position will flush theread-ahead buffer.
New in version 2.3.
Read at mostsize bytes from the file (less if the read hits EOF beforeobtainingsize bytes). If thesize argument is negative or omitted, readall data until EOF is reached. The bytes are returned as a string object. Anempty string is returned when EOF is encountered immediately. (For certainfiles, like ttys, it makes sense to continue reading after an EOF is hit.) Notethat this method may call the underlying C functionfread more thanonce in an effort to acquire as close tosize bytes as possible. Also notethat when in non-blocking mode, less data than was requested may bereturned, even if nosize parameter was given.
Note
This function is simply a wrapper for the underlyingfread C function, and will behave the same in corner cases,such as whether the EOF value is cached.
Read one entire line from the file. A trailing newline character is kept in thestring (but may be absent when a file ends with an incomplete line).[6] Ifthesize argument is present and non-negative, it is a maximum byte count(including the trailing newline) and an incomplete line may be returned. Anempty string is returnedonly when EOF is encountered immediately.
Note
Unlikestdio‘sfgets, the returned string contains null characters('\0') if they occurred in the input.
This method returns the same thing asiter(f).
New in version 2.1.
Deprecated since version 2.3:Useforlineinfile instead.
Set the file’s current position, likestdio‘sfseek. Thewhenceargument is optional and defaults toos.SEEK_SET or0 (absolute filepositioning); other values areos.SEEK_CUR or1 (seek relative to thecurrent position) andos.SEEK_END or2 (seek relative to the file’send). There is no return value.
For example,f.seek(2,os.SEEK_CUR) advances the position by two andf.seek(-3,os.SEEK_END) sets the position to the third to last.
Note that if the file is opened for appending(mode'a' or'a+'), anyseek() operations will be undone at thenext write. If the file is only opened for writing in append mode (mode'a'), this method is essentially a no-op, but it remains useful for filesopened in append mode with reading enabled (mode'a+'). If the file isopened in text mode (without'b'), only offsets returned bytell() arelegal. Use of other offsets causes undefined behavior.
Note that not all file objects are seekable.
Changed in version 2.6:Passing float values as offset has been deprecated.
Return the file’s current position, likestdio‘sftell.
Note
On Windows,tell() can return illegal values (after anfgets)when reading files with Unix-style line-endings. Use binary mode ('rb') tocircumvent this problem.
Files support the iterator protocol. Each iteration returns the same result asfile.readline(), and iteration ends when thereadline() method returnsan empty string.
File objects also offer a number of other interesting attributes. These are notrequired for file-like objects, but should be implemented if they make sense forthe particular object.
The encoding that this file uses. When Unicode strings are written to a file,they will be converted to byte strings using this encoding. In addition, whenthe file is connected to a terminal, the attribute gives the encoding that theterminal is likely to use (that information might be incorrect if the user hasmisconfigured the terminal). The attribute is read-only and may not be presenton all file-like objects. It may also beNone, in which case the file usesthe system default encoding for converting Unicode strings.
New in version 2.3.
The Unicode error handler used along with the encoding.
New in version 2.6.
Boolean that indicates whether a space character needs to be printed beforeanother value when using theprint statement. Classes that are tryingto simulate a file object should also have a writablesoftspaceattribute, which should be initialized to zero. This will be automatic for mostclasses implemented in Python (care may be needed for objects that overrideattribute access); types implemented in C will have to provide a writablesoftspace attribute.
New in version 2.5.
Python’swith statement supports the concept of a runtime contextdefined by a context manager. This is implemented using two separate methodsthat allow user-defined classes to define a runtime context that is enteredbefore the statement body is executed and exited when the statement ends.
Thecontext management protocol consists of a pair of methods that needto be provided for a context manager object to define a runtime context:
Enter the runtime context and return either this object or another objectrelated to the runtime context. The value returned by this method is bound tothe identifier in theas clause ofwith statements usingthis context manager.
An example of a context manager that returns itself is a file object. Fileobjects return themselves from __enter__() to allowopen() to be used asthe context expression in awith statement.
An example of a context manager that returns a related object is the onereturned bydecimal.localcontext(). These managers set the activedecimal context to a copy of the original decimal context and then return thecopy. This allows changes to be made to the current decimal context in the bodyof thewith statement without affecting code outside thewith statement.
Exit the runtime context and return a Boolean flag indicating if any exceptionthat occurred should be suppressed. If an exception occurred while executing thebody of thewith statement, the arguments contain the exception type,value and traceback information. Otherwise, all three arguments areNone.
Returning a true value from this method will cause thewith statementto suppress the exception and continue execution with the statement immediatelyfollowing thewith statement. Otherwise the exception continuespropagating after this method has finished executing. Exceptions that occurduring execution of this method will replace any exception that occurred in thebody of thewith statement.
The exception passed in should never be reraised explicitly - instead, thismethod should return a false value to indicate that the method completedsuccessfully and does not want to suppress the raised exception. This allowscontext management code (such ascontextlib.nested) to easily detect whetheror not an__exit__() method has actually failed.
Python defines several context managers to support easy thread synchronisation,prompt closure of files or other objects, and simpler manipulation of the activedecimal arithmetic context. The specific types are not treated specially beyondtheir implementation of the context management protocol. See thecontextlib module for some examples.
Python’sgenerators and thecontextlib.contextfactorydecoratorprovide a convenient way to implement these protocols. If a generator function isdecorated with thecontextlib.contextfactory decorator, it will return acontext manager implementing the necessary__enter__() and__exit__() methods, rather than the iterator produced by an undecoratedgenerator function.
Note that there is no specific slot for any of these methods in the typestructure for Python objects in the Python/C API. Extension types wanting todefine these methods must provide them as a normal Python accessible method.Compared to the overhead of setting up the runtime context, the overhead of asingle class dictionary lookup is negligible.
The interpreter supports several other kinds of objects. Most of these supportonly one or two operations.
The only special operation on a module is attribute access:m.name, wherem is a module andname accesses a name defined inm‘s symbol table.Module attributes can be assigned to. (Note that theimportstatement is not, strictly speaking, an operation on a module object;importfoo does not require a module object namedfoo to exist, rather it requiresan (external)definition for a module namedfoo somewhere.)
A special member of every module is__dict__. This is the dictionarycontaining the module’s symbol table. Modifying this dictionary will actuallychange the module’s symbol table, but direct assignment to the__dict__attribute is not possible (you can writem.__dict__['a']=1, which definesm.a to be1, but you can’t writem.__dict__={}). Modifying__dict__ directly is not recommended.
Modules built into the interpreter are written like this:<module'sys'(built-in)>. If loaded from a file, they are written as<module'os'from'/usr/local/lib/pythonX.Y/os.pyc'>.
SeeObjects, values and types andClass definitions for these.
Function objects are created by function definitions. The only operation on afunction object is to call it:func(argument-list).
There are really two flavors of function objects: built-in functions anduser-defined functions. Both support the same operation (to call the function),but the implementation is different, hence the different object types.
SeeFunction definitions for more information.
Methods are functions that are called using the attribute notation. There aretwo flavors: built-in methods (such asappend() on lists) and classinstance methods. Built-in methods are described with the types that supportthem.
The implementation adds two special read-only attributes to class instancemethods:m.im_self is the object on which the method operates, andm.im_func is the function implementing the method. Callingm(arg-1,arg-2,...,arg-n) is completely equivalent to callingm.im_func(m.im_self,arg-1,arg-2,...,arg-n).
Class instance methods are eitherbound orunbound, referring to whether themethod was accessed through an instance or a class, respectively. When a methodis unbound, itsim_self attribute will beNone and if called, anexplicitself object must be passed as the first argument. In this case,self must be an instance of the unbound method’s class (or a subclass ofthat class), otherwise aTypeError is raised.
Like function objects, methods objects support getting arbitrary attributes.However, since method attributes are actually stored on the underlying functionobject (meth.im_func), setting method attributes on either bound or unboundmethods is disallowed. Attempting to set a method attribute results in aTypeError being raised. In order to set a method attribute, you need toexplicitly set it on the underlying function object:
classC:defmethod(self):passc=C()c.method.im_func.whoami='my name is c'
SeeThe standard type hierarchy for more information.
Code objects are used by the implementation to represent “pseudo-compiled”executable Python code such as a function body. They differ from functionobjects because they don’t contain a reference to their global executionenvironment. Code objects are returned by the built-incompile() functionand can be extracted from function objects through theirfunc_codeattribute. See also thecode module.
A code object can be executed or evaluated by passing it (instead of a sourcestring) to theexec statement or the built-ineval() function.
SeeThe standard type hierarchy for more information.
Type objects represent the various object types. An object’s type is accessedby the built-in functiontype(). There are no special operations ontypes. The standard moduletypes defines names for all standard built-intypes.
Types are written like this:<type'int'>.
This object is returned by functions that don’t explicitly return a value. Itsupports no special operations. There is exactly one null object, namedNone (a built-in name).
It is written asNone.
This object is used by extended slice notation (seeSlicings). Itsupports no special operations. There is exactly one ellipsis object, namedEllipsis (a built-in name).
It is written asEllipsis.
Boolean values are the two constant objectsFalse andTrue. They areused to represent truth values (although other values can also be consideredfalse or true). In numeric contexts (for example when used as the argument toan arithmetic operator), they behave like the integers 0 and 1, respectively.The built-in functionbool() can be used to cast any value to a Boolean,if the value can be interpreted as a truth value (see section Truth ValueTesting above).
They are written asFalse andTrue, respectively.
SeeThe standard type hierarchy for this information. It describes stack frame objects,traceback objects, and slice objects.
The implementation adds a few special read-only attributes to several objecttypes, where they are relevant. Some of these are not reported by thedir() built-in function.
Deprecated since version 2.2:Use the built-in functiondir() to get a list of an object’s attributes.This attribute is no longer available.
Deprecated since version 2.2:Use the built-in functiondir() to get a list of an object’s attributes.This attribute is no longer available.
Footnotes
| [1] | Additional information on these special methods may be found in the PythonReference Manual (Basic customization). |
| [2] | As a consequence, the list[1,2] is considered equal to[1.0,2.0], andsimilarly for tuples. |
| [3] | They must have since the parser can’t tell the type of the operands. |
| [4] | To format only a tuple you should therefore provide a singleton tuple whose onlyelement is the tuple to be formatted. |
| [5] | These numbers are fairly arbitrary. They are intended to avoid printing endlessstrings of meaningless digits without hampering correct use and without havingto know the exact precision of floating point values on a particular machine. |
| [6] | The advantage of leaving the newline on is that returning an empty string isthen an unambiguous EOF indication. It is also possible (in cases where itmight matter, for example, if you want to make an exact copy of a file whilescanning its lines) to tell whether the last line of a file ended in a newlineor not (yes this happens!). |