Summary of python built-in functions

Source: Internet
Author: User
Tags string back vars

1. abs (x)

The abs () function returns the absolute value of a number (common, long, or floating point. If a plural number is given, the return value is the modulo of the plural number. For example:

>>> Print abs (-2, 4)

2.4

>>> Print abs (4 + 2j)

4.472135955

2. apply (function, args [, keywords])

The apply () function applies the args parameter to the function. Function parameters must be callable objects (functions, methods, or other callable objects ). The args parameter must be given in sequence. The list is converted to a tuples before being applied. When a function object is called, the content of the args list is treated as independent parameters. For example:

Apply (add, (1, 3, 4 ))

Equivalent

Add (1, 3, 4)

When you define a column of parameters in a list or tuples and use these parameters as independent parameters, you must use the apply () function. The apply () function is useful when you want to apply the variable length parameter column to a function.

The Optional keywords parameter should be a dictionary, and the dictionary keyword is a string. These strings are given at the end of the parameter column of the apply () function and will be used as keyword parameters.

3. buffer (object [, offset [, size])

If the object supports caching, call the buffer () function to create a new cache for the object. Such objects include strings, arrays, and caches. The new cache uses the offset parameter value to know the storage segment at the end of the object or the storage segment starting from the offset parameter value until the size parameter gives the size to reference the object. If no option parameter is provided, the cache region overwrites the entire sequence. The cached object is a read-only copy of the object data.

Cache objects are used to create a more friendly interface for an object type. For example, generic cache objects of the string object type become available, allowing byte-by-byte access to information in the string.

4. callable (object)

The callable () function returns true (true) when the object is a callable object; otherwise, false (false ), callable objects include functions, methods, code objects, classes (new instances are returned during calls), and class instances that have defined the '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 (72) + chr (101) + chr (108) + chr (111)

Hello

The chr () function is the inverse function of the ord () function. The ord () function converts the string back to the ASCII integer. The value of parameter I should be between 0 and 0 ~ Within the range of 255. If the value of parameter I is out of this range, a ValueError exception is thrown.

6. cmp (x, y)

The cmp () function compares the objects x and y and returns an integer based on the comparison result. If x Y, returns a positive number. Note that this function is especially used to compare the value size, rather than any reference relationship. Therefore, the following result is returned:

>>> A = 99

>>> B = int ('99 ')

>>> Cmp (a, B)

0

7. coerce (x, y)

The coerce () function returns a tuple consisting of two numeric parameters. This function converts two numeric parameters to the same type of number. The conversion rules are the same as those for arithmetic conversion. Here are two examples:

>>> A = 1

>>> B = 1.2

>>> Coerce (a, B)

(1.0, 1.2)

>>> A = 1 + 2j

>>> B = 4.3e10

>>> Coerce (a, B)

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

8 compile (string, filename, kind)

The compile () function compiles the string into a code object. The compiled code object is then executed by the exec statement, and then the eval () function can be used to evaluate it. The filename parameter should be the file name read from the code. If the file name is generated internally, the filename parameter value should be the corresponding identifier. The kind parameter specifies the category of the Code contained in the string parameter. For details about the possible value of kind, see Table 8-1.

Example:

>>> A = compile ('print "Hello World "',' ', 'Singles ')

>>> Exec ()

Hello World

>>> Eval ()

Hello World

Class of the Code Compiled by the compile () function

Code generated by Kind value Compilation

Exec statement Sequence

Simple eval expression

Single simple interaction statement

9. complex (real, [image])

The Complex () function returns a plural value, which is actually the real parameter value. If the value of the image parameter is given, the virtual part is image. If the default image parameter is provided, the virtual part is 0j.

10. delattr (object, name)

When the delattr () function permits an object, it deletes the name attribute of the object. This function is equivalent to the following statement:

Del object. attr

The delattr () function allows you to define the object and name Parameters Using programming methods, rather than display the parameters in the code.

11. dir ([object])

If no parameter is provided, the dir () function lists the names saved in the current local symbol table, as shown in the following example:

>>> Import sys

>>> Dir (sys)

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

(1, 3)

For integers, the returned values are 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 may also be 1 smaller than this. In any case, q * B + a % B is very close to; if a % B is a non-zero value, the positive and negative signs are the same as those of B, and there are 0 <= abs (a % B)

>>> Divmod (3.75, 1.125)

(3.0, 0.375)

>>> Divmod (4.99, 1.001)

(4.0, 0.98600000000000065)

>>> Divmod (-3.5, 1.1)

(-4.0, 0.90000000000000036)

13. eval (expression [, global [, locals])

The eval () function analyzes and evaluates expression strings as python standard expressions and returns the value of expression strings. When other optional parameters cannot be called, expression is used to access global and local objects of the program segment that calls the function. Another option is to provide the global and local symbol tables in the form of dictionaries (see the following section about global () and local () functions ).

The Return Value of the Eval () function is the value of the applied expression, as shown in the following example:

>>> A = 99

>>> Eval ('divmod (a, 7 )')

(14,1)

Any syntax error in job search operations will cause exceptions.

The eval () function can also be used to compile code objects such as those created by the complie () function. However, the eval () function can be used only after the code object is compiled in the "eval" mode.

To execute any python code mixed with statements and expressions, use the exec statement or execfile () function to dynamically execute a file containing any code.

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

The execfile () function is equivalent to the exec statement. The difference is that the statements in the execfile () function execution file, while the exec statement processes strings. The globals and locals parameters should be dictionary, which contains the symbol table that is valid during the execution of the file. If the locals parameter is omitted, all references use the globals namespace. If both optional parameters are omitted, the file accesses the current symbol table during running.

15. filter (function, list)

The filter () function filters items in the list parameter based on whether the results returned by the function parameter are true, and 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,)

Print B

[7, 8, 9]

If the value of function is None, the identity function is used. All false elements in the list parameter are deleted.

16. flaot (x)

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

17. getattr (object, name [, default])

The getattr () function returns the object's name attribute value. Syntax:

Getattr (x, 'myvalue ')

Equivalent

X. myvalue

If the name parameter does not exist but the value of the defalut parameter is given, this function returns the default parameter value; otherwise, AttributeError is thrown.

18. globals ()

The globals () function returns a dictionary representing 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 calls the function.

19. hasattr (object, name)

If the object has an attribute that matches the name string, the hasattr () function returns true; otherwise, 0 is returned.

20. hash (object)

The hash () function returns the integer hash Value of the object. If the comparison between any two objects is equivalent, their hash values are the same. This function should not be used for peer-up.

21. hex (x)

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

22. id (object)

The Return Value of the id () function is an integer (or a long integer) -- the "identifier" of the object -- the identifier is within the lifecycle of the corresponding object, make sure it is unique and constant.

23. input ([prompt])

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

24. 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 value of the radix parameter is used as the conversion base. This parameter must be 2 ~ An integer in the range of 36.

25. intern (string)

The intern () function adds the string to the table with the reserved string. The returned value is the reserved version number. "Reserved string" is available through a pointer instead of a pure string. Therefore, you can use pointer comparison instead of string comparison to search for dictionary keywords, which is better than the common string comparison method.

The names used in the python namespace table and the dictionary used to retain the module, class, or strength attribute are usually retained to accelerate script execution.

The reserved string definition cannot be collected as useless units. Therefore, you must note that using the reserved string in the large dictionary keyword set will greatly increase the memory requirement, even if the dictionary keyword Emergency Response exceeds the scope.

26. isinstance (object, class)

The isinstance () function returns true if the object parameter is an instance of the class parameter. The determination of the function value is subject to the general Inheritance Method and the subclass. If the object parameter uses a special type instance defined by the type class in the types module, it can also be identified by the isinstance () function. If the class parameter is neither a class nor a type object, a TypeError exception is thrown.

27. issubclass (class1, class2)

If the class1 parameter is a subclass of the class2 parameter, the issubclass () function returns true. Classes are generally considered as subclasses of their own. If neither of the two parameters is a class object, a TypeError exception is thrown.

28. len (s)

The len () function returns the length of a sequence (string, tuples, or list) or dictionary object.

29. list (sequence)

The list () function returns a list. The items and sequence of the list are the same as those of the sequence parameter, as shown in the following example:

>>> List ('abc ')

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

>>> List ([1, 2, 3])

[1, 2, 3]

30. locals ()

The Return Value of the locals () function indicates the dictionary of the current local symbol table.

31. long (x)

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

32. 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:

>>> A = [1, 2, 4]

>>> Map (lambda x: pow (x, 2),)

[,]

If additional lists are provided, they are provided to the function in parallel. Add None to the list of non-elements until all parameters reach the same length.

If the value of the function parameter is None, it is assumed to be the identify function. The map () function will return the list of all false parameters to be deleted. If the function parameter value is None and multiple LIST parameters are specified, the returned list is composed of tuples, which are composed of parameters at the same location in each parameter list in the function, for example:

>>> Map (None, [,], [,])

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

The result of the preceding example is equivalent to that of the zip () function.

33. max (s, [, args…])

If only one parameter is specified, the max () function returns the maximum value of series s. When a column of parameters is specified, the max () function returns the maximum value of the given parameter.

34. min (s [, args…])

If only one parameter is specified, the min () function returns the minimum value of the series s. When a column of parameters is given, the min () function returns the minimum value of the given parameter. Remember: The multi-parameter call sequence is not traversed. Each list parameter is compared as a whole, for example:

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

Return

[1, 2, 3]

Instead of the expected result of 1, to get the minimum value of one or more elements in the list, you can concatenate all the lists into a string, as shown below:

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

35. oct (x)

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

>>> Oct (2001)

'123'

Note that the return value is usually an unsigned number. As a result, oct (-1) produces '123' results on 32-bit machines.

36. open (filename [, mode [, bufsize])

The open () function uses the mode and cached bufsize types to open the file identified by filename. This function returns a file object.

The mode is the same as the mode used by the system function fopen. If the mode parameter is omitted, the default value is r.

Meaning

R open for read

W open for writing

Open a is used for appending (the file location is automatically moved to the end of the file during the opening)

R + open for update (read and write)

W + truncate (or clear) the file, and then open the file for reading and writing

A + open the file for reading and writing, and automatically change the end Of the file so far

When any Mode option is attached, open the file in binary mode instead of text mode (this mode

B is only valid for windows, dos, and other operating systems. For Unix, MacOS, and BeOS, all files are treated in binary mode regardless of the option value)

The bufsize option parameter of the open () function determines the cache size used to read data from the file. If the bufsize is omitted, the default cache capacity is used.

Description of bufsize values

Disable Cache

Row Cache

> 1 use a cache with the approximate size of bufsize characters

<0 Use System Default

37. ord (c)

This function returns the ASCII value or Unicode number 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])

This function returns the power value with x as the base number and y as the index. If z is given, this function calculates the y power value of x, which is the modulo value of z. For this calculation, Billy uses:

Pow (x, y) % z

Higher efficiency

The parameter provided to the pow () function should be numeric, and the given type determines the type of return value. If the calculated value cannot be expressed by the type of the given parameter value, an exception is thrown. For example, the following call to pow () will fail:

Pow (2,-1)

However

Pow (2.0,-1)

Is valid

39. range ([start,] stop [, step])

This function returns the Value List, which starts from start and ends before stop. All numbers should be listed and returned as normal integers. If step is omitted, 1 is used by default. If start is omitted, the value starts from 0. If it is called in the form of two parameters, the given parameters are start and stop. To define the step, all three parameters must be given. The following step uses a positive number to call the range () function:

>>> Range (5, 25, 5)

[5, 10, 15, 20]

Note that the final value is the value of the stop function minus step and the return value of the range () function increases from small to large, approaching the value of stop, but does not include the value of stop.

If the given value of step is negative, the return value of the range () function increases from large to small, instead of increasing. stop must be smaller than stop; otherwise, the returned list is empty. The following describes the application of a negative step value:

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

[,]

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

[25, 20, 15, 10, 5]

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

[]

40. raw_input ([prompt])

This function accepts the original input from sys. stdin and returns a string. The input ends with a linefeed. The linefeed is removed before the input string is returned to the caller. If prompt is given, the prompt without line break at the end will be written to sys. stdout and used as the input prompt, as shown in the following example:

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

Name? Martin

If the readline module has been loaded, features such as row editing and history are supported during input.

41. reduce (function, sequence [, initializer])

This function applies the function (supporting two functions) to each element in the sequence at a time, 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 as follows:

(1*2) * 3) * 4) * 5)

The result is 120.

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

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

1200

42. reload (module)

The reload () function loads the previously imported modules again. Reload includes the initial import module as the application analysis process and initialization process. In this way, the modified python module can be reloaded without exiting the interpreter.

Note the following when using the reload () function:

* If the module is syntactically correct but fails during initialization, the import process cannot properly bind the module name to the symbol table, you must use the import () function to load the module before it can be reloaded.

* The reloaded module does not delete the registration items of the old version in the symbol table. This is certainly not a problem for objects and functions with a constant name. However, if you change the name of a module object, the module name remains in the symbol table after being reloaded.

* Support for re-loading of extension modules (dependent on built-in or supported dynamic loading function libraries), but it may be untargeted and may cause failure, this completely depends on the behavior of Dynamically Loaded function libraries.

* If the module uses from... Import... Method To import objects from another module. The reload () function does not re-define the imported objects. You can use import... Form to avoid this problem

* The re-loading module of the provided classes does not affect any existing instances of the provided classes. The existing instances continue to use the original method definition. Only new instances of the provided classes use the new format. This principle applies to derived classes.

43. repr (object)

The repr () function returns a string representation of an object. This is consistent with the result that applies the object or attribute to the SLR quotation marks. The returned string generates an object. The value of this object is the same as the value generated by passing the object to the eval () function, as shown in the following example:

>>> Dict = {'one': 1, 'two: 2', 'two': {'two': 4, 'manyance': 8 }}

>>> Repr (dict)

"{'One': 1, 'blood': {'blood': 4, 'manyuncs': 8}, 'two': 2 }"

44. round (x [, n])

The round () function returns the floating point parameter x rounded to the n-digit value after the decimal point, as shown in the following example:

>>> Round (0.4)

0.0

>>> Round (0.5)

1.0

>>> Round (-0.5)

-1.0

>>> Round (1985,-2)

2000.0

45. setattr (object, name, value)

This function sets the name attribute of the object parameter to the value parameter value. The setattr () function is the inverse function of the getattr () function. The latter only obtains information. the following statement:

Setattr (myattr ', 'new value ')

Equivalent

Myobj. myattr = 'new value'

The setattr () function can be used in the following situations: the attribute is named programmatically by the name parameter, rather than explicitly naming the attribute.

46. slice ([start,] stop, [, step])

This function returns the slice object, which indicates the index set specified by range (start, stop, step. If a parameter is provided, this parameter is used as the stop parameter value. If two parameters are provided, they are used as the start and stop parameter values. If no parameter value is provided, the default value is None. The sequence slice object has three attributes (start, stop, and step). These three attributes only return the parameters to be provided to the slice () function.

47. str (object)

Returns a string representation of an object. This is similar to the repr () function. The only difference is that the return value of this function is designed as a printable string rather than a string compatible with the eval () function.

48. tuple (object)

The tuple () function returns a tuples whose items and items are in the same order as the sequence parameter. The following is an example of the tuple () function:

>>> Tuple ('abc ')

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

>>> Tuple ([1, 2, 3])

(1, 2, 3)

49. type (object)

This function returns the type of the object parameter. The returned 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'

50. unichr (I)

The return code of this function is a Unicode string of the Unicode Character of the integer parameter I. This function is equivalent to the preceding chr () function. Note that to convert Unicode characters back to their integer format, you can use the ord () function; without the uniord () function, if the given integer exceeds 0 ~ If the value range is 65535, A ValueError exception is thrown.

51. unicode (string [, encoding [, errors])

This function decodes a given string from one format to another using the encoding format decoder. Any Encoding Error is marked with a string defined by the errors parameter.

This function is especially used for conversion between string and Unicode encoding formats. The default (when the encoding parameter value is not given) operation is to strictly decode the string as the UTF-8 format, in the case of an errors error will cause a ValueError exception. For a proper decoding list, see the codecs module.

52. vars ([object])

This function returns the dictionary corresponding to the current local symbol table. When a module, class, or instance is provided, the vars () function returns the dictionary of the symbol table corresponding to that object. Because the results are not defined, do not modify the returned dictionary.

53. xrange ([start,] stop [, step])

The function functions the same as the range () function. The only difference is that the xrange () function returns an xrange object. An xrange () object is an opaque object type. The information returned by this type is consistent with the requested parameter list, but it does not have to store each independent element in the list. This function is particularly useful when creating a very large list; the memory saved by using the xrange () function is rather impressive than using the range () function.

54. zip (seq1 ,...)

The zip () function processes a series of sequences and returns these sequences to a list of tuples. Each tuple contains the nth element of each given sequence. The following is an example:

>>> A = [1, 2, 4]

>>> B = [5, 6, 7, 8]

>>> Zip (a, B)

[(), ()]

55. execute any statement

Python supports three commands, which allow the execution of strings of arbitrary files or python code. These three commands are exec statements, execfile (), and eval () functions.

56. exec statement

Exec statements are designed to execute any code snippets of python that can use any combination of functions and statements. The executed code accesses the objects, classes, methods, or functions of the same global definition and local definition. The following is a simple example of using the exec statement:

Exec "print 'Hello world '"

You can also define the resources that are valid for the exec Statement by providing a dictionary containing the object and Its Value List, as shown in the following example:

Exec "print message" in myglobals, mylocals

You can use the globals () and locals () functions to obtain the current dictionary.

Please note that exec statements execute expressions and statements, or evaluate expressions and statements, but exec statements do not return any value. Because exec is a statement rather than a function, any attempt to obtain the returned value will cause a syntax error.

57. execfile () function

This function executes the same operations as the exec statement. As described above, they differ in that the execfile () function reads the executed statement from the question for decades, the executed object is not a string, not a code object. All other aspects of the execfile () function are equivalent to the exec statement.

58. eval () function

This function cannot execute any python statement. The eval () function is designed to execute a python expression and return the value, as shown in the following example:

Result = eval (userexpression)

Or you can give an expression in a more explicit way in the statement, as shown in the following example:

Result = eval ("3 + 6 ")

The eval () function cannot be used to execute statements. Based on experience, the eval () function is usually used to evaluate an expression and return a value. In all other cases, the exec statement is used.

Exec ()

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: info-contact@alibabacloud.com 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.