Python built-in function summary

Source: Internet
Author: User
Tags abs arithmetic modulus object object ord string back vars

1. ABS (x)

The ABS () function returns the absolute value of a number (which can be a normal, long, or floating-point type). If the plural is given, the return value is the modulus of the complex number. For example:

>>>print ABS ( -2,4)


>>>print ABS (4+2J)


2. Apply (Function,args[,keywords])

The Apply () function applies the args parameter to the function. The function arguments must be callable objects (functions, methods, or other callable objects). The args parameter must be given as a sequence. Lists are converted to tuples before they are applied. When a function object is called, the contents of the args list are treated as separate parameters. For example:

Apply (Add, (1,3,4))

Equivalent to

Add (1,3,4)

You must use the Apply () function when you have defined a column of parameters in a list or tuple, and you need to use this list parameter separately as individual parameters. The Apply () function is useful when you want to apply a variable-length parameter column to an already function.

The optional keywords parameter should be a dictionary, and the dictionary's keyword is a string. These strings are given at the end of the parameter column of the Apply () function, which will be used as the keyword parameter.

3. Buffer (Object[,offset[,size])

The object object creates a new cache for object objects if it supports the cache call interface buffer () function. Such objects include strings, arrays, and caches. The new cache references the object object by using a storage fragment from the offset parameter value that knows the end of the object, or a storage fragment that starts at the value of the offset parameter until the size parameter gives the dimension length. If no option parameters are given, the cache area overwrites the entire sequence, and the resulting cache object is a read-only copy of the object's data.

A cache object is used to create a more user-friendly interface for an object type. For example, the string object type Universal cache object becomes available, allowing the information in the string to be accessed byte by bit.

4. Callable (object)

The callable () function returns True if the Object object is callable (true), otherwise false (false), the callable object includes functions, methods, code objects, classes (returning a new instance upon invocation), and class instances that have defined a ' call ' method

5. chr (i)

The CHR () function returns a single string that matches the ASCII code I, as shown in the following example:

>>>print CHR +CHR (101) +CHR (108) +CHR (111)


The Chr () function is an inverse of the Ord () function, where the Ord () function converts the string back to the ASCII integer, and the value of parameter I should be within the 0~255 range. If the value of parameter I is outside this range, an ValueError exception is thrown.

6. CMP (x, y)

The CMP () function compares the two objects x and Y, and returns an integer based on the result of the comparison. If XY, a positive number is returned. Note that this function is especially useful for comparing numeric sizes, not any reference relationships, and thus has the following result:


>>>b=int (' 99 ')

>>>CMP (A, B)


7. Coerce (x, y)

The coerce () function returns a tuple that consists of two numeric parameters. This function converts two numeric parameters to the same type number, with the same conversion rules as the arithmetic conversion rules. Here is a two example:



>>>coerce (A, B)




>>>coerce (A, B)

((1+2J), (43000000000+0J))

8 Compile (String,filename,kind)

The compile () function compiles a string into a code object, and the generated code object is then executed by the EXEC statement, which can then be evaluated using the eval () function. The filename parameter should be the name of the file from which the code is read. If the file name is generated internally, the filename parameter value should be the appropriate identifier. The kind parameter specifies the category of code contained in the string parameter, and for more information about the possible value of kind, see table 8-1

Examples are as follows:

>>>a=compile (' print ' Hello world ' ', ' ', ' single ')

>>>exec (a)

Hello World

>>>eval (a)

Hello World

Table the categories of code compiled by the compile () function

Kind code generated by compiling values

EXEC statement sequence

eval Simple expression

Single Simple interactive statement

9. Complex (Real,[image])

The Complex () function returns a complex number, in fact the real parameter value. If the value of the image parameter is given, the imaginary part is an image, and if the default image parameter, the imaginary part is 0j.

Delattr (Object,name)

The delattr () function deletes the Name property of the object when it is permitted to object, and this function is equivalent to the following statement:

Del object.attr

The Delattr () function allows you to define the object and the name parameter by using a programmatic definition, rather than displaying the specified in code.

Dir ([Object])

When no parameters are supplied, the Dir () function lists the names saved in the current local symbol table, as shown in the following example:

>>>import SYS

>>>dir (SYS)

Divmod (A, B)

The Devmod () function returns a tuple that contains the quotient and remainder of a divided by B, as shown in the following example:

>>>divmod (7,4)


For integers, the return value is the same as A/b and a%b. If the given parameter value is a floating-point number, the result is (q,a%b), where: Q is usually Math.floor (A/b), but it can also be 1 smaller, regardless of the circumstances, Q*b+a%b is very close to a; If A%b is a non-0 value, its sign and B are the same, and 0 <=abs (a%b) <abs (b) was established. The following example shows how the Divmod () function handles floating-point:< p= "" >

>>>divmod (3.75,1.125)


>>>divmod (4.99,1.001)


>>>divmod ( -3.5,1.1)

( -4.0,0.90000000000000036)

Eval (Expression[,global[,locals]])

The eval () function parses and evaluates an expression string as a Python standard expression, returning the value of the expression string, and when other optional arguments are not called, expression accesses the global and local objects of the program segment that called the function. Another option is to give the global and local symbol tables in a dictionary (see the following section on Global () and the Local () functions).

The return value of the Eval () function is the value of the job-search expression, as shown in the following example:


>>>eval (' Divmod (a,7) ')


Any syntax errors in a job search operation will be thrown into an exception

The eval () function can also be used to compile code objects such as those created by the Complie () function, but only when the code object is compiled with "eval" mode, the eval () function is compiled.

To execute python arbitrary code that mixes statements and expressions, use the EXEC statement or use the execfile () function to dynamically execute files that contain arbitrary code.

14.execfile (File[,globals[,locals]])

The execfile () function is equivalent to the EXEC statement, except that the execfile () function executes the statement in the file, and the EXEC statement processes the string. Where the globals and locals parameters should be a dictionary that contains the symbol table that the file is valid for during execution, and if the locals parameter is omitted, all references use the Globals namespace. If two optional parameters are omitted, the file accesses the current symbol table during the run.

15. Filter (Function,list)

The filter () function filters the items in the list parameter based on whether the result returned by the function parameter is True (TRUE), and finally returns a new list, as shown in the following example:

a=[1,2,3, 4, 5,6,,7,8,9]

B=filter (Lambda x:x>6,a)

Print B


If the function parameter value is none, all elements in the list parameter that are false (false) are deleted by using the identity function.

Flaot (x)

The float () function converts the x parameter to a floating-point number, where: X can be a string or it can be a digit.

GetAttr (Object,name[,default])

The GetAttr () function returns the value of the Name property of object. On the syntax, the following statement:

GetAttr (x, ' myvalue ')

Equivalent to


If the name parameter does not exist, but the value of the Defalut parameter is given, the function returns the default parameter value; otherwise throws a Attributeerror exception

Globals ()

The Globals () function returns a dictionary that represents the current global symbol table. This dictionary is usually the dictionary of the current module. If the Globals () function is called in a function or method, it returns the symbol table of the module that defines the function or method, rather than the symbol table of the module that called the function.

Hasattr (Object,name)

If the object has a property that matches the name string, the Hasattr () function returns True (TRUE); otherwise 0 is returned.

Hash (object)

The hash () function returns an integer hash value about the object. If any two objects are equivalent in comparison, their hash values are the same. This function is not applied to the up-to-up.

21. Hex (x)

The hex () function converts an integer to a hexadecimal string, which is a valid Python expression,

ID (object)

The ID () function returns a value of an integer (or long Integer)-the "identity" of the object-the identity that is guaranteed to be unique and constant throughout the lifetime of its corresponding object.

. input ([prompt])

The input () function is equivalent to eval (raw_input (Prompt)).

. int (X,[radix])

the int () function converts a number or string x to a "normal" integer. If the value of the radix parameter is given, the radix parameter value is used as the base of the conversion, which should be an integer in the 2~36 range.

Intern (String)

The Intern () function adds a string to the table that holds the string, and the return value is the reserved version number. The "reserved string" is available through pointers, not a pure string, so it is possible to find the dictionary keyword using pointer comparisons instead of string comparisons, which is better than the usual method of string comparison.

Names used in the Python namespace table and in dictionaries used to preserve modules, classes, or power attributes are usually reserved for speeding up script execution.

Since the string definition cannot be collected as a useless unit, it is important to note that using a reserved string on a large dictionary key set will greatly increase memory requirements even if the Dictionary keyword contingency is out of scope.

Isinstance (Object,class)

The Isinstance () function returns True when the object parameter is an instance of the class parameter. The determination of the function value is subject to the common inheritance law and subclass. If the object parameter is an instance of a special type that is defined in the types module with a type class, it can also be identified with the isinstance () function. Throws a TypeError exception if the class parameter is not a class and is not a type object

27.issubclass (CLASS1,CLASS2)

If the Class1 parameter is a subclass of the Class2 parameter, the Issubclass () function returns True. Classes are generally considered to be subclasses of their own. Throws a TypeError exception if either of the two parameters is not a class object

Len (s)

The Len () function returns the length of a sequence (string, tuple, or list) or Dictionary object

29. List (sequence)

The list () function is returned as a listing. The items and order of the list are the same as the items and order of the sequence parameter, as shown in the following example:

>>>list (' abc ')

[' A ', ' B ', ' C ']

>>>list ([i])


Locals ()

The locals () function returns a dictionary that represents the current local symbol table

. Long (x)

The long () function converts a string or number to a long integer, and the conversion of floating-point numbers follows the same rules as int ()

Map (function,list,...)

The map () function applies the function to each item in the list and returns a new list, as shown in the following example:


>>>map (Lambda X:pow (x,2), a)


If additional lists are provided, they are provided in parallel to the function. In the subsequent list of no elements, add none until all parameter lists reach the same length.

If the function parameter has a value of none, it is assumed to be identify, which causes the map () function to return the list of all parameters that are false. If the function parameter value is none, and given more than one list parameter, the returned list consists of a tuple of tuples that consist of parameters at the same location in each parameter list in the function, as shown in the following example:

>>>map (none,[1,2,3,4],[4,5,6,7])

[(1,4), (2,5), (3,6), (4,7)]

The result of the above example is equivalent to the result of the zip () function

Max (S,[,args ...])

When given only one parameter, the MAX () function returns the maximum value of the sequence S. When given a column parameter, the MAX () function returns the maximum parameter for a given parameter

Min (S[,args ...])

When given only one parameter, the min () function returns the minimum value of the sequence S. When given a column parameter, the min () function returns the minimum value in the given parameter. Remember: The sequence of multi-parameter calls is not traversed, and each list parameter is compared as a whole, such as:

MIN ([1,2,3],[4,5,6])



Instead of the usual thought of a result of 1, to get the minimum value of an element in one or more lists, you can link all the lists to a string, as follows:

MIN ([1,2,3]+[4,5,6])

Oct (x)

The function converts an integer to an octal string. The result is a valid Python expression, as shown in the following example:

>>>OCT (2001)

' 03721 '

Note that the return value is usually an unsigned number. This causes the OCT (-1) to produce ' 037777777777 ' results on 32-bit machines

Open (Filename[,mode[,bufsize]])

The open () function opens the file identified by the filename by using the mode and cache bufsize types. This function returns a file object

Where mode is the same as the system function fopen (). If the mode parameter is omitted, its default value is R

Mode meaning

R Open for Read

W Open for writing

A open for attach (during open, the file location is automatically moved to the end of the file)

r+ Open for Update (read and write)

w+ truncate (or empty) the file, then open the file for read-write

A + open file for read and write, and automatically change the current to the end of the file

When attaching any mode option, open the file in binary mode instead of text mode (this mode

b only works with Windows, DOS and some other operating systems, and UNIX, MacOS, and BeOS regardless of the option value, treats all files in binary mode

The bufsize option parameter of the open () function determines the size of the cache used when reading data from a file and, if BufSize omitted, uses the system default cache capacity

BufSize Value Description

Disable caching

Row cache

>1 uses a cache that is approximately the size of bufsize character length

<0 using the system default

37. Ord (c)

The function returns the ASCII code value or Unicode numeric code of a string consisting of a character C. The Ord () function is the inverse function of the CHR () function and the NUICHR () function

38. Pow (x,y[,z])

The function returns a power value with a base of x that is exponential by Y. If z is given, the function calculates the value of the Y-power of X by the z-modulus, which is calculated more than using:

Pow (x, y)%z

is more efficient

The argument supplied to the POW () function should be numeric, and the given type determines the type of the return value. If the calculated value cannot be represented by the type of the given parameter value, an exception is thrown, for example, the following call to POW () will fail:

Pow (2,-1)


Pow (2.0,-1)

It's effective.

Range ([Start,]stop[,step])

The function returns a list of values, starting with start, step as step, and ending before stop. All numbers should be listed and returned as a normal integer number. If step is omitted, the default is 1. If Start is omitted, the value is evaluated starting at 0. If called in two arguments, the given parameter is start and stop, and if you want to define the step, you must give all three arguments. The following call to the range () function uses step step with a positive value:

>>>range (5,25,5)


Note that the last value is the stop minus step,range () function's return value is incremented from small to large, approaching the value of stop, but does not contain the stop value

If the given value of step is negative, the return value of the range () function increments from large to small instead of incrementing, stop must be smaller than stop, otherwise the returned list is empty. The following is a description of the use of a negative step value:

>>>range (10,0,-1)


>>>range (25,0,-5)


>>>range (0,10,-1)


Raw_input ([prompt])

The function accepts the original input from Sys.stdin and returns a string. The input ends with a newline character, where the line break is removed before the input string is returned to the caller. If prompt is given, prompt with no newline at the end is written to sys.stdout and used as the input hint, as shown in the following example:

>>>name=raw_input (' name? ')

Name? Martin

If the ReadLine module is loaded, features such as line editing and history are supported during input

Reduce (Function,sequence[,initializer])

The function applies function at a time (supporting two functions) to each element in sequence, gradually shortening the entire statement until it is a single value. For example, the following statement simulates the arithmetic operator "! ”:

Reduce (lambda x,y:x*y,[1,2,3,4,5])

The result is the same as performing the following calculations:


Result equals 120

If the initializer parameter value is given, the initializer parameter value is used as the first element of the sequence, as shown in the following:

>>>reduce (Lambda x,y:x*y,[1,2,3,4,5],10)


Reload (module)

The reload () function loads the previously imported modules once again. Reloading (reload) includes the analysis process and initialization process that the initial import module is applied to. This allows the changed Python module to be reloaded without exiting the interpreter.

Some considerations for using the reload () function are as follows:

* If the module is syntactically correct, but fails during initialization, the import process does not correctly bind the module's name to the symbol table, and the module must be loaded with the import () function before the module can be reloaded.

* Reloading the module does not delete the original old version of the registration entry in the symbol table. This is certainly not a problem for objects and functions that have a constant name, but if you change the name of a module entity, the module name remains in the symbol table after reloading

* Supports the reload of the extension module (which relies on a built-in or supported dynamically loaded library of functions), but may be non-targeted, and determines that it may lead to failure, which is entirely dependent on the behavior of the dynamically loaded function library

* If using the From...import module ... Way to import objects from another module, the reload () function does not redefine the imported objects, you can take advantage of the import ... form to avoid this problem

* The reload module for the provided class does not affect any of the saved instances of the provided class-the saved instance will continue to use the original method definition, and only the new instance of the class uses the new format. This principle also applies to derived classes

Repr (object)

The repr () function returns the string representation of an object. This is consistent with the result of applying an object or property to the SLR quotation marks ('). The returned string produces an object that has the same value as passing an object to the eval () function, as shown in the following example:

>>>dict={' One ': 1, ' two:2 ', ' many ': {' Many ': 4, ' Manymany ': 8}}

>>>repr (Dict)

"{' One ': 1, ' many ': {' Many ': 4, ' Manymany ': 8}, ' Both ': 2}"

Round (X[,n])

The round () function returns the value of the float parameter x rounded to the N-bit after the decimal point, as shown in the following example:

>>>round (0.4)


>>>round (0.5)


>>>round (-0.5)


>>>round (1985,-2)


SetAttr (Object,name,value)

The function sets the Name property of the object parameter to the value parameter. The SetAttr () function is the inverse of the getattr () function, which obtains only information, the following statement:

SetAttr (myattr ', ' new value ')

Equivalent to

Myobj.myattr= ' new value '

The SetAttr () function can be used in situations where a property is named programmatically by the name parameter rather than explicitly naming the property

Slice ([start,]stop,[,step])

The function returns a sequence slice (slice) object that represents the set of indexes specified by range (start,stop,step). If a parameter is given, this parameter is used as the stop parameter value, and if two arguments are given, they are used as the parameter values for start and stop, and any parameter that does not give the parameter value is the default value of None. The sequence slice object has 3 properties (Start,stop, and step), and these 3 properties simply return the arguments to be supplied to the slice () function

. Str (object)

Returns a string representation of the object. This is similar to the repr () function, except that the return value of this function is designed to be a printable string instead of a string compatible with the eval () function.

. Tuple (object)

The tuple () function returns a tuple that has the same order of items and items as the sequence parameter, and the following is an example of the tuple () function:

>>>tuple (' abc ')

(' A ', ' B ', ' C ')

>>>tuple ([i])


. Type (object)

The function returns the type of the object parameter. The return value is a type object as described by the type module, for example:

>>>import type

>>>if type (String) ==type. StringType:

print ' This is a string '


The function returns a Unicode string that is the Unicode character of an integer parameter I. This function is equivalent to the CHR () function discussed earlier. Note that to convert Unicode characters back to their integer format, you can use the Ord () function, without the Uniord () function, and if the given integer exceeds the range of 0~65535, the ValueError exception is thrown


The function uses an encoded format decoder to decode a given string from one format to another format. Any errors that are encoded are marked with a string that is defined with the errors parameter

This function is especially useful for converting between string and Unicode encoding formats. The default (when the encoding parameter value is not given) is a strict way to decode a string into the UTF-8 format, which throws a ValueError exception when a errors error occurs. For the appropriate decoding list, see the Codecs module

52.vars ([object])

The function returns a dictionary that corresponds to the current local symbol table. When a module, class, or instance is given, the VARs () function returns a dictionary of the symbol table corresponding to that object. Because the result is not defined, be sure not to modify the returned dictionary

Xrange ([Start,]stop[,step])

The function, like the range () function, is the only difference: the xrange () function returns a Xrange object. The xrange () object is an opaque object type that returns information that is consistent with the requested list of arguments, but does not have to store each individual element in the list. This function is particularly useful in the case of creating a very large list, and using the xrange () function to save more memory than to use the range () function is quite impressive.

54. Zip (seq1,...)

The zip () function processes a series of sequences that return a list of tuples. Where each tuple contains the nth element of each sequence given. Here's an example:



>>>zip (A, B)

[(1,5), (2,6), (3,7), (4,8)]

55. Execute arbitrary statements

Python supports 3 instructions, and these 3 directives allow the execution of strings of arbitrary files or Python code, which are the EXEC statement, execfile (), and eval () functions.

The. EXEC statement

The EXEC statement is designed to execute any snippet of Python that can use any combination of functions and statements. The code that executes accesses the same globally defined and locally defined objects, classes, and methods or functions. Here is a simple example of using the EXEC statement:

Exec "print ' Hello World '"

You can also qualify resources that are valid for an EXEC statement by providing a dictionary that contains a list of objects and their values, as in the following example:

EXEC "Print message" in Myglobals,mylocals

can use the Globals () and locals () functions to obtain the current dictionary

Note that the EXEC statement executes expressions and statements, or evaluates expressions and statements, but the EXEC statement does not return any values. Because EXEC is a statement that is not a function, any attempt to get the return value will result in a syntax error

ExecFile () function

The function performs the same operations as the EXEC statement, which differs from the following: the execfile () function reads the executed statement from the question for several decades, and executes the object that is not a string, not a code object; execfile () All other aspects of the function are equivalent to the EXEC statement

The. Eval () function

This function does not allow arbitrary python statements to be executed. The eval () function is designed to execute a python expression and return a value, as in the following example:

Result=eval (userexpression)

Or give the expression more explicitly in the statement, as shown in the following example:

Result=eval ("3+6")

You cannot use the Eval () function to execute a statement, and based on experience, you typically use the Eval () function to evaluate an expression and return a value, and in all other cases use the EXEC statement


Python built-in function summary

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.