Movatterモバイル変換


[0]ホーム

URL:


Navigation

Built-in Types

The following sections describe the standard types that are built into theinterpreter.

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.

Truth Value Testing

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,0.0,0j.

  • any empty sequence, for example,'',(),[].

  • any empty mapping, for example,{}.

  • instances of user-defined classes, if the class defines a__bool__() 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.)

Boolean Operations —and,or,not

These are the Boolean operations, ordered by ascending priority:

OperationResultNotes
xoryifx is false, theny, elsex(1)
xandyifx is false, thenx, elsey(2)
notxifx is false, thenTrue,elseFalse(3)

Notes:

  1. This is a short-circuit operator, so it only evaluates the secondargument if the first one isFalse.
  2. This is a short-circuit operator, so it only evaluates the secondargument if the first one isTrue.
  3. not has a lower priority than non-Boolean operators, sonota==b isinterpreted asnot(a==b), anda==notb is a syntax error.

Comparisons

There are eight comparison operations in Python. 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:

OperationMeaning
<strictly less than
<=less than or equal
>strictly greater than
>=greater than or equal
==equal
!=not equal
isobject identity
isnotnegated object identity

Objects of different types, except different numeric types, never compare equal.Furthermore, some types (for example, file objects) support only a degeneratenotion of comparison where any two objects of that type are unequal. The<,<=,> and>= operators will raise aTypeError exception whenany operand is a complex number, the objects are of different types that cannotbe compared, or other cases where there is no defined ordering.

Non-identical instances of a class normally compare as non-equal unless theclass defines the__eq__() method.

Instances of a class cannot be ordered with respect to other instances of thesame class, or other types of object, unless the class defines enough of themethods__lt__(),__le__(),__gt__(), and__ge__() (ingeneral,__lt__() and__eq__() are sufficient, if you want theconventional meanings of the comparison operators).

The behavior of theis andisnot operators cannot becustomized; also they can be applied to any two objects and never raise anexception.

Two more operations with the same syntactic priority,in andnotin, aresupported only by sequence types (below).

Numeric Types —int,float,complex

There are three distinct numeric types:integers,floatingpoint numbers, andcomplex numbers. In addition, Booleans are asubtype of integers. Integers have unlimited precision. Floating pointnumbers are implemented usingdouble in C—all bets on theirprecision are off unless you happen to know the machine you are workingwith. Complex numbers have a real and imaginary part, which are eachimplemented usingdouble in C. To extract these parts from acomplex numberz, usez.real andz.imag. (The standard libraryincludes additional numeric types,fractions that hold rationals,anddecimal that hold floating-point numbers with user-definableprecision.)

Numbers are created by numeric literals or as the result of built-in functionsand operators. Unadorned integer literals (including hex, octal and binarynumbers) yield integers. Numeric literals containing a decimal point or anexponent sign yield floating point numbers. Appending'j' or'J' to anumeric literal yields an imaginary number (a complex number with a zero realpart) which you can add to an integer or float to get a complex number with realand imaginary parts.

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 integer is narrower than floating point,which is narrower than complex. Comparisons between numbers of mixed type usethe same rule.[2] The constructorsint(),float(), andcomplex() can be used to produce numbers of a specific type.

All numeric types (except complex) support the following operations, sorted byascending priority (operations in the same box have the same priority; allnumeric operations have a higher priority than comparison operations):

OperationResultNotesFull documentation
x+ysum ofx andy  
x-ydifference ofx andy  
x*yproduct ofx andy  
x/yquotient ofx andy  
x//yfloored quotient ofx andy(1) 
x%yremainder ofx/y(2) 
-xx negated  
+xx unchanged  
abs(x)absolute value or magnitude ofx abs()
int(x)x converted to integer(3)int()
float(x)x converted to floating point(4)float()
complex(re,im)a complex number with real partre, imaginary partim.im defaults to zero. complex()
c.conjugate()conjugate of the complex numberc  
divmod(x,y)the pair(x//y,x%y)(2)divmod()
pow(x,y)x to the powery(5)pow()
x**yx to the powery(5) 

Notes:

  1. Also referred to as integer division. The resultant value is a wholeinteger, though the result’s type is not necessarily int. The result isalways rounded towards minus infinity:1//2 is0,(-1)//2 is-1,1//(-2) is-1, and(-1)//(-2) is0.

  2. Not for complex numbers. Instead convert to floats usingabs() ifappropriate.

  3. Conversion from floating point to integer may round or truncateas in C; see functionsfloor() andceil() in themath modulefor well-defined conversions.

  4. float also accepts the strings “nan” and “inf” with an optional prefix “+”or “-” for Not a Number (NaN) and positive or negative infinity.

  5. Python definespow(0,0) and0**0 to be1, as is common forprogramming languages.

Allnumbers.Real types (int andfloat) also include the following operations:

OperationResultNotes
math.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 

For additional numeric operations see themath andcmathmodules.

Bit-string Operations on Integer Types

Integers support additional operations that make sense only for bit-strings.Negative numbers are treated as their 2’s complement value (this assumes asufficiently large number of bits that no overflow 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(operations in the same box have the same priority):

OperationResultNotes
x|ybitwiseor ofx andy 
x^ybitwiseexclusive or ofx andy 
x&ybitwiseand ofx andy 
x<<nx shifted left byn bits(1)(2)
x>>nx shifted right byn bits(1)(3)
~xthe bits ofx inverted 

Notes:

  1. Negative shift counts are illegal and cause aValueError to be raised.
  2. A left shift byn bits is equivalent to multiplication bypow(2,n)without overflow check.
  3. A right shift byn bits is equivalent to division bypow(2,n) withoutoverflow check.

Additional Methods on Integer Types

int.bit_length()

Return the number of bits necessary to represent an integer in binary,excluding the sign and leading zeros:

>>>n=-37>>>bin(n)'-0b100101'>>>n.bit_length()6

More precisely, ifx is nonzero, thenx.bit_length() is theunique positive integerk such that2**(k-1)<=abs(x)<2**k.Equivalently, whenabs(x) is small enough to have a correctlyrounded logarithm, thenk=1+int(log(abs(x),2)).Ifx is zero, thenx.bit_length() returns0.

Equivalent to:

defbit_length(self):s=bin(x)# binary representation:  bin(-37) --> '-0b100101's=s.lstrip('-0b')# remove leading zeros and minus signreturnlen(s)# len('100101') --> 6

New in version 3.1.

Additional Methods on Float

The float type has some additional methods.

float.as_integer_ratio()
Return a pair of integers whose ratio is exactly equal to theoriginal float and with a positive denominator. RaisesOverflowError on infinities and aValueError onNaNs.

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.

float.hex()
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.
float.fromhex(s)
Class method to return the float represented by a hexadecimalstrings. The strings may have leading and trailingwhitespace.

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'

Iterator Types

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:

container.__iter__()
Return an iterator object. The object is required to support the iteratorprotocol described below. If a container supports different types ofiteration, additional methods can be provided to specifically requestiterators for those iteration types. (An example of an object supportingmultiple forms of iteration would be a tree structure which supports bothbreadth-first and depth-first traversal.) This method corresponds to thetp_iter slot of the type structure for Python objects in the Python/CAPI.

The iterator objects themselves are required to support the following twomethods, which together form theiterator protocol:

iterator.__iter__()
Return the iterator object itself. This is required to allow both containersand iterators to be used with thefor andin statements.This method corresponds to thetp_iter slot of the type structure forPython objects in the Python/C API.
iterator.__next__()
Return the next item from the container. If there are no further items, raisetheStopIteration exception. This method corresponds to thetp_iternext slot of the type structure for Python objects in thePython/C API.

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.

Once an iterator’s__next__() method raisesStopIteration, it mustcontinue to do so on subsequent calls. Implementations that do not obey thisproperty are deemed broken.

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__() and__next__() methods.

Sequence Types —str,bytes,bytearray,list,tuple,range

There are six sequence types: strings, byte sequences (bytes objects),byte arrays (bytearray objects), lists, tuples, and range objects. Forother containers see the built indict andset classes, andthecollections module.

Strings contain Unicode characters. Their literals are written in single ordouble quotes:'xyzzy',"frobozz". SeeString and Bytes literals for more aboutstring literals. In addition to the functionality described here, there arealso string-specific methods described in theString Methods section.

Bytes and bytearray objects contain single bytes – the former is immutablewhile the latter is a mutable sequence. Bytes objects can be constructed theconstructor,bytes(), and from literals; use ab prefix with normalstring syntax:b'xyzzy'. To construct byte arrays, use thebytearray() function.

Warning

While string objects are sequences of characters (represented by strings oflength 1), bytes and bytearray objects are sequences ofintegers (between 0and 255), representing the ASCII value of single bytes. That means that fora bytes or bytearray objectb,b[0] will be an integer, whileb[0:1] will be a bytes or bytearray object of length 1. Therepresentation of bytes objects uses the literal format (b'...') since itis generally more useful than e.g.bytes([50,19,100]). You can alwaysconvert a bytes object into a list of integers usinglist(b).

Also, while in previous Python versions, byte strings and Unicode stringscould be exchanged for each other rather freely (barring encoding issues),strings and bytes are now completely separate concepts. There’s no impliciten-/decoding if you pass and object of the wrong type. A string alwayscompares unequal to a bytes or bytearray object.

Lists are constructed 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 tuple must havethe enclosing parentheses, such asa,b,c or(). A single item tuplemust have a trailing comma, such as(d,).

Objects of type range are created using therange() 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:

OperationResultNotes
xinsTrue if an item ofs isequal tox, elseFalse(1)
xnotinsFalse if an item ofs isequal tox, elseTrue(1)
s+tthe concatenation ofs andt(6)
s*n,n*sn 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 lists arecompared lexicographically by comparing corresponding elements. This means thatto compare equal, every element must compare equal and the two sequences must beof the same type and have the same length. (For full details seeComparisons in the language reference.)

Notes:

  1. Whens is a string object, thein andnotin operations act like asubstring test.

  2. 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]]
  3. 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 isstill0.

  4. 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.

  5. 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.

  6. 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.

String Methods

String objects support the methods listed below. Note that none of thesemethods take keyword arguments.

In addition, Python’s strings support the sequence type methods described intheSequence Types — str, bytes, bytearray, list, tuple, range section. To output formatted strings, see theString Formatting section. Also, see there module for stringfunctions based on regular expressions.

str.capitalize()
Return a copy of the string with only its first character capitalized.
str.center(width[,fillchar])
Return centered in a string of lengthwidth. Padding is done using thespecifiedfillchar (default is a space).
str.count(sub[,start[,end]])
Return the number of occurrences of substringsub in the range [start,end]. Optional argumentsstart andend are interpreted as in slicenotation.
str.encode([encoding[,errors]])
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.
str.endswith(suffix[,start[,end]])
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.
str.expandtabs([tabsize])
Return a copy of the string where all tab characters are replaced by one ormore spaces, depending on the current column and the given tab size. Thecolumn number is reset to zero after each newline occurring in the string.Iftabsize is not given, a tab size of8 characters is assumed. Thisdoesn’t understand other non-printing characters or escape sequences.
str.find(sub[,start[,end]])
Return the lowest index in the string where substringsub is found, such thatsub is contained in the range [start,end]. Optional argumentsstartandend are interpreted as in slice notation. Return-1 ifsub is notfound.
str.format(format_string,*args,**kwargs)

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.

str.index(sub[,start[,end]])
Likefind(), but raiseValueError when the substring is not found.
str.isalnum()
Return true if all characters in the string are alphanumeric and there is atleast one character, false otherwise.
str.isalpha()
Return true if all characters in the string are alphabetic and there is at leastone character, false otherwise.
str.isdecimal()
Return true if all characters in the string are decimalcharacters and there is at least one character, falseotherwise. Decimal characters include digit characters, and all charactersthat that can be used to form decimal-radix numbers, e.g. U+0660,ARABIC-INDIC DIGIT ZERO.
str.isdigit()
Return true if all characters in the string are digits and there is at least onecharacter, false otherwise.
str.isidentifier()
Return true if the string is a valid identifier according to the languagedefinition, sectionIdentifiers and keywords.
str.islower()
Return true if all cased characters in the string are lowercase and there is atleast one cased character, false otherwise.
str.isnumeric()
Return true if all characters in the string are numericcharacters, and there is at least one character, falseotherwise. Numeric characters include digit characters, and all charactersthat have the Unicode numeric value property, e.g. U+2155,VULGAR FRACTION ONE FIFTH.
str.isprintable()
Return true if all characters in the string are printable or the string isempty, false otherwise. Nonprintable characters are those characters definedin the Unicode character database as “Other” or “Separator”, excepting theASCII space (0x20) which is considered printable. (Note that printablecharacters in this context are those which should not be escaped whenrepr() is invoked on a string. It has no bearing on the handling ofstrings written tosys.stdout orsys.stderr.)
str.isspace()
Return true if there are only whitespace characters in the string and there isat least one character, false otherwise.
str.istitle()
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.
str.isupper()
Return true if all cased characters in the string are uppercase and there is atleast one cased character, false otherwise.
str.join(seq)
Return a string which is the concatenation of the strings in the sequenceseq. ATypeError will be raised if there are any non-string valuesinseq, includingbytes objects. The separator between elementsis the string providing this method.
str.ljust(width[,fillchar])
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).
str.lower()
Return a copy of the string converted to lowercase.
str.lstrip([chars])

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'
str.maketrans(x[,y[,z]])

This static method returns a translation table usable forstr.translate().

If there is only one argument, it must be a dictionary mapping Unicodeordinals (integers) or characters (strings of length 1) to Unicode ordinals,strings (of arbitrary lengths) or None. Character keys will then beconverted to ordinals.

If there are two arguments, they must be strings of equal length, and in theresulting dictionary, each character in x will be mapped to the character atthe same position in y. If there is a third argument, it must be a string,whose characters will be mapped to None in the result.

str.partition(sep)
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.
str.replace(old,new[,count])
Return a copy of the string with all occurrences of substringold replaced bynew. If the optional argumentcount is given, only the firstcountoccurrences are replaced.
str.rfind(sub[,start[,end]])
Return the highest index in the string where substringsub is found, such thatsub is contained within s[start,end]. Optional argumentsstart andendare interpreted as in slice notation. Return-1 on failure.
str.rindex(sub[,start[,end]])
Likerfind() but raisesValueError when the substringsub is notfound.
str.rjust(width[,fillchar])
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).
str.rpartition(sep)
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.
str.rsplit([sep[,maxsplit]])
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.
str.rstrip([chars])

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'
str.split([sep[,maxsplit]])

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 '].

str.splitlines([keepends])
Return a list of the lines in the string, breaking at line boundaries. Linebreaks are not included in the resulting list unlesskeepends is given andtrue.
str.startswith(prefix[,start[,end]])
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.
str.strip([chars])

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'
str.swapcase()
Return a copy of the string with uppercase characters converted to lowercase andvice versa.
str.title()
Return a titlecased version of the string: words start with uppercasecharacters, all remaining cased characters are lowercase.
str.translate(map)

Return a copy of thes where all characters have been mapped through themap which must be a dictionary of Unicode ordinals (integers) to Unicodeordinals, strings orNone. Unmapped characters are left untouched.Characters mapped toNone are deleted.

You can usestr.maketrans() to create a translation map fromcharacter-to-character mappings in different formats.

Note

An even more flexible approach is to create a custom character mappingcodec using thecodecs module (seeencodings.cp1251 for anexample).

str.upper()
Return a copy of the string converted to uppercase.
str.zfill(width)
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).

Old String Formatting Operations

Note

The formatting operations described here are obsolete and may go away in futureversions of Python. Use the newString Formatting in new code.

String objects have one unique built-in operation: the% operator (modulo).This is also known as the stringformatting orinterpolation operator.Givenformat%values (whereformat is a string),% conversionspecifications informat are replaced with zero or more elements ofvalues.The effect is similar to the usingsprintf in the C language.

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:

  1. The'%' character, which marks the start of the specifier.
  2. Mapping key (optional), consisting of a parenthesised sequence of characters(for example,(somename)).
  3. Conversion flags (optional), which affect the result of some conversiontypes.
  4. Minimum field width (optional). If specified as an'*' (asterisk), theactual width is read from the next element of the tuple invalues, and theobject to convert comes after the minimum field width and optional precision.
  5. Precision (optional), given as a'.' (dot) followed by the precision. Ifspecified as'*' (an asterisk), the actual width is read from the nextelement of the tuple invalues, and the value to convert comes after theprecision.
  6. Length modifier (optional).
  7. Conversion type.

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:

FlagMeaning
'#'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:

ConversionMeaningNotes
'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()). 
'%'No argument is converted, results in a'%'character in the result. 

Notes:

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. The precision determines the maximal number of characters used.

  1. 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.

Range Type

Therange type is an immutable sequence which is commonly used forlooping. The advantage of therange type is that anrangeobject will always take the same amount of memory, no matter the size of therange it represents. There are no consistent performance advantages.

Range objects have very little behavior: they only support indexing, iteration,and thelen() function.

Mutable Sequence Types

List and bytearray objects support additional operations that allow in-placemodification of the object. Other mutable sequence types (when added to thelanguage) should also support these operations. Strings and tuples areimmutable sequence types: such objects cannot be modified once created. Thefollowing operations are defined on mutable sequence types (wherex is anarbitrary object).

Note that while lists allow their items to be of any type, bytearray object“items” are all integers in the range 0 <= x < 256.

OperationResultNotes
s[i]=xitemi ofs is replaced byx 
s[i:j]=tslice ofs fromi tojis replaced by the contents ofthe iterablet 
dels[i:j]same ass[i:j]=[] 
s[i:j:k]=tthe 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] 
s.extend(x)same ass[len(s):len(s)]=x(2)
s.count(x)return number ofi‘s forwhichs[i]==x 
s.index(x[,i[,j]])return smallestk such thats[k]==x andi<=k<j(3)
s.insert(i,x)same ass[i:i]=[x](4)
s.pop([i])same asx=s[i];dels[i];returnx(5)
s.remove(x)same asdels[s.index(x)](3)
s.reverse()reverses the items ofs inplace(6)
s.sort([key[,reverse]])sort the items ofs in place(6), (7), (8)

Notes:

  1. t must have the same length as the slice it is replacing.

  2. x can be any iterable object.

  3. RaisesValueError whenx is not found ins. When a negative index ispassed as the second or third parameter to theindex() method, the sequencelength is added, as for slice indices. If it is still negative, it is truncatedto zero, as for slice indices.

  4. When a negative index is passed as the first parameter to theinsert()method, the sequence length is added, as for slice indices. If it is stillnegative, it is truncated to zero, as for slice indices.

  5. The optional argumenti defaults to-1, so that by default the lastitem is removed and returned.

  6. Thesort() andreverse() methods modify the sequence in place foreconomy of space when sorting or reversing a large sequence. To remind youthat they operate by side effect, they don’t return the sorted or reversedsequence.

  7. Thesort() method takes optional arguments for controlling thecomparisons. Each must be specified as a keyword argument.

    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.

    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 implementationmakes the list appear empty for the duration, and raisesValueError if itcan detect that the list has been mutated during a sort.

  8. sort() is not supported bybytearray objects.

Bytes and Byte Array Methods

Bytes and bytearray objects, being “strings of bytes”, have all methods found onstrings, with the exception ofencode(),format() andisidentifier(), which do not make sense with these types. For convertingthe objects to strings, they have adecode() method.

Wherever one of these methods needs to interpret the bytes as characters(e.g. theis...() methods), the ASCII character set is assumed.

Note

The methods on bytes and bytearray objects don’t accept strings as theirarguments, just as the methods on strings don’t accept bytes as theirarguments. For example, you have to write

a="abc"b=a.replace("a","f")

and

a=b"abc"b=a.replace(b"a",b"f")

The bytes and bytearray types have an additional class method:

bytes.fromhex(string)
bytearray.fromhex(string)

Thisbytes class method returns a bytes or bytearray object,decoding the given string object. The string must contain two hexadecimaldigits per byte, spaces are ignored.

>>>bytes.fromhex('f0 f1f2  ')b'\xf0\xf1\xf2'

The translate method differs in semantics from the version available on strings:

bytes.translate(table[,delete])

Return a copy of the bytes or bytearray object where all bytes occurring inthe optional argumentdelete are removed, and the remaining bytes have beenmapped through the given translation table, which must be a bytes object oflength 256.

You can use thestring.maketrans() helper function to create atranslation table.

Set thetable argument toNone for translations that only deletecharacters:

>>>b'read this short text'.translate(None,b'aeiou')b'rd ths shrt txt'

Set Types —set,frozenset

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.)

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:

classset([iterable])
classfrozenset([iterable])

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:

len(s)
Return the cardinality of sets.
x in s
Testx for membership ins.
x not in s
Testx for non-membership ins.
isdisjoint(other)
Return True if the set has no elements in common withother. Sets aredisjoint if and only if their intersection is the empty set.
issubset(other)
set <= other
Test whether every element in the set is inother.
set < other
Test whether the set is a true subset ofother, that is,set<=otherandset!=other.
issuperset(other)
set >= other
Test whether every element inother is in the set.
set > other
Test whether the set is a true superset ofother, that is,set>=otherandset!=other.
union(other,...)
set | other | ...
Return a new set with elements from the set and all others.
intersection(other,...)
set & other & ...
Return a new set with elements common to the set and all others.
difference(other,...)
set - other - ...
Return a new set with elements in the set that are not in the others.
symmetric_difference(other)
set ^ other
Return a new set with elements in either the set orother but not both.
copy()
Return a new set with a shallow copy ofs.

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.

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(other,...)
set |= other | ...
Update the set, adding elements fromother.
intersection_update(other,...)
set &= other & ...
Update the set, keeping only elements found in it andother.
difference_update(other,...)
set -= other | ...
Update the set, removing elements found in others.
symmetric_difference_update(other)
set ^= other
Update the set, keeping only elements found in either set, but not in both.
add(elem)
Add elementelem to the set.
remove(elem)
Remove elementelem from the set. RaisesKeyError ifelem isnot contained in the set.
discard(elem)
Remove elementelem from the set if it is present.
pop()
Remove and return an arbitrary element from the set. RaisesKeyError if the set is empty.
clear()
Remove all elements from the set.

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.

Mapping Types —dict

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.

classdict([arg])

Return a new dictionary initialized from an optional positional argument orfrom a set of keyword arguments. If no arguments are given, return a newempty dictionary. If the positional argumentarg is a mapping object,return a dictionary mapping the same keys to the same values as does themapping object. Otherwise the positional argument must be a sequence, acontainer that supports iteration, or an iterator object. The elements ofthe argument must each also be of one of those kinds, and each must in turncontain exactly two objects. The first is used as a key in the newdictionary, and the second as the key’s value. If a given key is seen morethan once, the last value associated with it is retained in the newdictionary.

If keyword arguments are given, the keywords themselves with their associatedvalues are added as items to the dictionary. If a key is specified both inthe positional argument and as a keyword argument, the value associated withthe keyword is retained in the dictionary. For example, these all return adictionary equal to{"one":2,"two":3}:

  • dict(one=2,two=3)
  • dict({'one':2,'two':3})
  • dict(zip(('one','two'),(2,3)))
  • dict([['two',3],['one',2]])

The first example only works for keys that are valid Python identifiers; theothers work with any valid keys.

These are the operations that dictionaries support (and therefore, custommapping types should support too):

len(d)
Return the number of items in the dictionaryd.
d[key]

Return the item ofd with keykey. Raises aKeyError ifkey isnot in the map.

If a subclass of dict defines a method__missing__(), if the keykeyis not present, thed[key] operation calls that method with the keykeyas argument. Thed[key] operation then returns or raises whatever isreturned or raised by the__missing__(key) call if the key is notpresent. No other operations or methods invoke__missing__(). If__missing__() is not defined,KeyError is raised.__missing__() must be a method; it cannot be an instance variable. Foran example, seecollections.defaultdict.

d[key] = value
Setd[key] tovalue.
del d[key]
Removed[key] fromd. Raises aKeyError ifkey is not in themap.
key in d
ReturnTrue ifd has a keykey, elseFalse.
key not in d
Equivalent tonotkeyind.
clear()
Remove all items from the dictionary.
copy()
Return a shallow copy of the dictionary.
fromkeys(seq[,value])

Create a new dictionary with keys fromseq and values set tovalue.

fromkeys() is a class method that returns a new dictionary.valuedefaults toNone.

get(key[,default])
Return the value forkey ifkey is in the dictionary, elsedefault.Ifdefault is not given, it defaults toNone, so that this methodnever raises aKeyError.
items()
Return a new view of the dictionary’s items ((key,value) pairs). Seebelow for documentation of view objects.
keys()
Return a new view of the dictionary’s keys. See below for documentation ofview objects.
pop(key[,default])
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.
popitem()

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.

setdefault(key[,default])
Ifkey is in the dictionary, return its value. If not, insertkeywith a value ofdefault and returndefault.default defaults toNone.
update([other])

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).
values()
Return a new view of the dictionary’s values. See below for documentation ofview objects.

Dictionary view objects

The objects returned bydict.keys(),dict.values() anddict.items() areview objects. They provide a dynamic view on thedictionary’s entries, which means that when the dictionary changes, the viewreflects these changes.

Dictionary views can be iterated over to yield their respective data, andsupport membership tests:

len(dictview)
Return the number of entries in the dictionary.
iter(dictview)

Return an iterator over the keys, values or items (represented as tuples of(key,value)) in the dictionary.

Keys and values are iterated over in an arbitrary order which is non-random,varies across Python implementations, and depends on the dictionary’s historyof insertions and deletions. If keys, values and items views are iteratedover with no intervening modifications to the dictionary, the order of itemswill directly correspond. This allows the creation of(value,key) pairsusingzip():pairs=zip(d.values(),d.keys()). Another way tocreate the same list ispairs=[(v,k)for(k,v)ind.items()].

x in dictview
ReturnTrue ifx is in the underlying dictionary’s keys, values oritems (in the latter case,x should be a(key,value) tuple).

Keys views are set-like since their entries are unique and hashable. If allvalues are hashable, so that (key, value) pairs are unique and hashable, thenthe items view is also set-like. (Values views are not treated as set-likesince the entries are generally not unique.) Then these set operations areavailable (“other” refers either to another view or a set):

dictview & other
Return the intersection of the dictview and the other object as a new set.
dictview | other
Return the union of the dictview and the other object as a new set.
dictview - other
Return the difference between the dictview and the other object (all elementsindictview that aren’t inother) as a new set.
dictview ^ other
Return the symmetric difference (all elements either indictview orother, but not in both) of the dictview and the other object as a new set.

An example of dictionary view usage:

>>>dishes={'eggs':2,'sausage':1,'bacon':1,'spam':500}>>>keys=dishes.keys()>>>values=dishes.values()>>># iteration>>>n=0>>>forvalinvalues:...n+=val>>>print(n)504>>># keys and values are iterated over in the same order>>>list(keys)['eggs', 'bacon', 'sausage', 'spam']>>>list(values)[2, 1, 1, 500]>>># view objects are dynamic and reflect dict changes>>>deldishes['eggs']>>>deldishes['sausage']>>>list(keys)['spam', 'bacon']>>># set operations>>>keys&{'eggs','bacon','salad'}{'bacon'}

File Objects

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:

file.close()

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.

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__ import with_statement # This isn't required in Python 2.6with open("hello.txt") as f:    for line in f:        print(line)

In older versions of Python, you would have needed to do this to get the sameeffect:

f=open("hello.txt")try:forlineinf:print(line)finally: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.

file.flush()
Flush the internal buffer, likestdio‘sfflush. This may be ano-op on some file-like objects.
file.fileno()

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!

file.isatty()

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.

file.__next__()
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:print(line)), the__next__() method is called repeatedly. This method returns the nextinput line, or raisesStopIteration when EOF is hit when the file is openfor reading (behavior is undefined when the file is open for writing). In orderto make afor loop the most efficient way of looping over the linesof a file (a very common operation), the__next__() method uses a hiddenread-ahead buffer. As a consequence of using a read-ahead buffer, combining__next__() with other file methods (likereadline()) does not workright. However, usingseek() to reposition the file to an absoluteposition will flush the read-ahead buffer.
file.read([size])
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.
file.readline([size])

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.

file.readlines([sizehint])
Read until EOF usingreadline() and return a list containing the linesthus read. If the optionalsizehint argument is present, instead ofreading up to EOF, whole lines totalling approximatelysizehint bytes(possibly after rounding up to an internal buffer size) are read. Objectsimplementing a file-like interface may choose to ignoresizehint if itcannot be implemented, or cannot be implemented efficiently.
file.seek(offset[,whence])

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.

file.tell()

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.

file.truncate([size])
Truncate the file’s size. If the optionalsize argument is present, the fileis truncated to (at most) that size. The size defaults to the current position.The current file position is not changed. Note that if a specified size exceedsthe file’s current size, the result is platform-dependent: possibilitiesinclude that the file may remain unchanged, increase to the specified size as ifzero-filled, or increase to the specified size with undefined new content.Availability: Windows, many Unix variants.
file.write(str)

Write a string to the file. Due to buffering, the string may not actuallyshow up in the file until theflush() orclose() method iscalled.

The meaning of the return value is not defined for every file-like object.Some (mostly low-level) file-like objects may return the number of bytesactually written, others returnNone.

file.writelines(sequence)
Write a sequence of strings to the file. The sequence can be any iterableobject producing strings, typically a list of strings. There is no return value.(The name is intended to matchreadlines();writelines() does notadd line separators.)

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.

file.closed
bool indicating the current state of the file object. This is a read-onlyattribute; theclose() method changes the value. It may not be availableon all file-like objects.
file.encoding
The encoding that this file uses. When 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 strings.
file.errors
The Unicode error handler used along with the encoding.
file.mode
The I/O mode for the file. If the file was created using theopen()built-in function, this will be the value of themode parameter. This is aread-only attribute and may not be present on all file-like objects.
file.name
If the file object was created usingopen(), the name of the file.Otherwise, some string that indicates the source of the file object, of theform<...>. This is a read-only attribute and may not be present on allfile-like objects.
file.newlines
If Python was built with the--with-universal-newlines option toconfigure (the default) this read-only attribute exists, and forfiles opened in universal newline read mode it keeps track of the types ofnewlines encountered while reading the file. The values it can take are'\r','\n','\r\n',None (unknown, no newlines read yet) or atuple containing all the newline types seen, to indicate that multiple newlineconventions were encountered. For files not opened in universal newline readmode the value of this attribute will beNone.

memoryview Types

memoryviews allow Python code to access the internal data of an objectthat supports the buffer protocol without copying. Memory can be interpreted assimple bytes or complex data structures.

classmemoryview(obj)

Create amemoryview that referencesobj.obj must support thebuffer protocol. Builtin objects that support the buffer protocol includebytes andbytearray.

len(view) returns the total number of bytes in the memoryview,view.

Amemoryview supports slicing to expose its data. Taking a singleindex will return a single byte. Full slicing will result in a subview:

>>>v=memoryview(b'abcefg')>>>v[1]b'b'>>>v[-1]b'g'>>>v[1:4]<memory at 0x77ab28>>>>bytes(v[1:4])b'bce'>>>v[3:-1]<memory at 0x744f18>>>>bytes(v[4:-1])

If the object the memory view is over supports changing its data, thememoryview supports slice assignment:

>>> data = bytearray(b'abcefg')>>> v = memoryview(data)>>> v.readonlyFalse>>> v[0] = 'z'>>> databytearray(b'zbcefg')>>> v[1:4] = b'123'>>> databytearray(b'a123fg')>>> v[2] = b'spam'Traceback (most recent call last):File "<stdin>", line 1, in <module>ValueError: cannot modify size of memoryview object

Notice how the size of the memoryview object can not be changed.

memoryview has two methods:

tobytes()
Return the data in the buffer as a bytestring.
tolist()

Return the data in the buffer as a list of integers.

>>>memoryview(b'abc').tolist()[97, 98, 99]

There are also several readonly attributes available:

format
A string containing the format (instruct module style) for eachelement in the view. This defaults to'B', a simple bytestring.
itemsize
The size in bytes of each element of the memoryview.
shape
A tuple of integers the length ofndim giving the shape of thememory as a N-dimensional array.
ndim
An integer indicating how many dimensions of a multi-dimensional array thememory represents.
strides
A tuple of integers the length ofndim giving the size in bytes toaccess each element for each dimension of the array.

Context Manager Types

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:

contextmanager.__enter__()

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.

contextmanager.__exit__(exc_type,exc_val,exc_tb)

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.

Other Built-in Types

The interpreter supports several other kinds of objects. Most of these supportonly one or two operations.

Modules

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'>.

Classes and Class Instances

SeeObjects, values and types andClass definitions for these.

Functions

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

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.

If you access a method (a function defined in a class namespace) through aninstance, you get a special object: abound method (also calledinstance method) object. When called, it will add theself argumentto the argument list. Bound methods have two special read-only attributes:m.__self__ is the object on which the method operates, andm.__func__ isthe function implementing the method. Callingm(arg-1,arg-2,...,arg-n)is completely equivalent to callingm.__func__(m.__self__,arg-1,arg-2,...,arg-n).

Like function objects, bound method objects support getting arbitraryattributes. However, since method attributes are actually stored on theunderlying function object (meth.__func__), setting method attributes onbound methods 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:

class C:    def method(self):        passc = C()c.method.__func__.whoami = 'my name is c'

SeeThe standard type hierarchy for more information.

Code Objects

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 their__code__attribute. See also thecode module.

A code object can be executed or evaluated by passing it (instead of a sourcestring) to theexec() oreval() built-in functions.

SeeThe standard type hierarchy for more information.

Type Objects

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:<class'int'>.

The Null Object

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.

The Ellipsis Object

This object is commonly used by slicing (seeSlicings). It supports nospecial operations. There is exactly one ellipsis object, namedEllipsis (a built-in name).

It is written asEllipsis or....

Boolean Values

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.

Internal Objects

SeeThe standard type hierarchy for this information. It describes stack frame objects,traceback objects, and slice objects.

Special Attributes

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.

object.__dict__
A dictionary or other mapping object used to store an object’s (writable)attributes.
instance.__class__
The class to which a class instance belongs.
class.__bases__
The tuple of base classes of a class object. If there are no base classes, thiswill be an empty tuple.
class.__name__
The name of the class or type.

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!).

Table Of Contents

Previous topic

Built-in Objects

Next topic

Built-in Exceptions

This Page

Quick search

Enter search terms or a module, class or function name.

Navigation

©Copyright 1990-2009, Python Software Foundation. Last updated on Feb 14, 2009. Created usingSphinx 0.6.

[8]ページ先頭

©2009-2025 Movatter.jp