Python3 built-in functions encyclopedia

Source: Internet
Author: User
Tags eval instance method iterable pow

I. INTRODUCTION

Python has built-in a series of common functions for us to use, Python English official documentation detailed description: Click to view, in order to facilitate viewing, the summary of the built-in functions recorded.

Two. Instructions for use

The following are all the built-in functions of the Python3 version:

1. ABS () Get absolute value

1 >>> ABS ( -10) 2 103 >>> ABS (0) 4---------ABS (+) 6, >>> a = -108 >>> a.__abs_ _ () 9 10

2. All () accepts an iterator that returns true if all the elements of the iterator are true, otherwise false

False: 0,none, empty list, empty string, empty progenitor, empty dictionary bool () judged true or false

1 >>> tmp_1 = [' Python ', 123]2 >>> All (tmp_1) 3 True4 >>> tmp_2 = []5 >>> All (tmp_2) 6 Tr Ue7 >>> tmp_3 = [0]8 >>> All (tmp_3) 9 False

3. Any () accepts an iterator that returns true if an iterator has an element true, otherwise false

4. ASCII () invokes the int.__repr__ () method of the object to obtain the return value of the method., similar to the ABS call __ABS__ ()

5. Bin (), 6. Oct (), 7. Hex () Three functions are: convert decimal number to 2/8/16 binary respectively.

8. BOOL () tests whether an object is true or false.

9. Bytes () Converts a string to a byte type, and ByteArray ("Hello", ' enconding=utf-8 ') converts the string to a number of bits.

1 >>> s = ' python ' 2 >>> x = bytes (s, encoding= ' Utf-8 ') 3 >>> x4 B ' python ' 5 >>> a = ' King ' 6 >>> s = bytes (A, encoding= ' Utf-8 ') 7 >>> S8 B ' \xe7\x8e\x8b '

Ten. STR () converts a character type/numeric type to a string type

1 >>> str (b ' \xe7\x8e\x8b ', encoding= ' Utf-8 ')  # byte converted to string 2 ' king ' 3 >>> str (1)   # Integer converted to string 4 ' 1 '

Challable () Determines whether an object can be called, and the object that can be called is a Callables object, such as a function and an instance with __call__ ().

1 >>> callable (max) 2 True3 >>> callable ([1, 2, 3]) 4 False5 >>> callable (None) 6 False7 >>& Gt Callable (' str ') 8 False

. Char (), 13. Ord () view the ASCII characters corresponding to the decimal number/view the decimal number corresponding to an ASCII

1 >>> chr ( -1) 2 Traceback (most recent): 3   File "<pyshell#26>", line 1, in <module> 4
   CHR ( -1) 5 valueerror:chr () arg not in range (0x110000) 6 >>> chr (0) 7 ' \x00 ' 8 >>> ord (' \x00 ') 9 010 >>> Ord (' 7 ') 11 55

Classmethod () is used to specify a method as a method of a class that is executed directly by the class, with only one CLS parameter, and automatically assigns the class that called the method to the CLS when it executes the method of the ray. There is no method for the class specified by this parameter as an instance method

1 class province:2     country = "China" 3        4     def __init__ (self, name): 5         self.name = name 6        7     @classmeth OD 8     def show (CLS):  # class method, called by class, must have at least one parameter CLS, called when this parameter does not pass the value, automatically assigns the class name to the CLS 9         print (CLS)       11 # Call Method 12 Province.show ()

Complie () compiles a string into code that Python can recognize or can execute, or read text into a string and recompile

1 compile (source, filename, mode, flags=0, Dont_inherit=false, optimize=-1) 2 compile source as code or AST object. Code objects can be evaluated over EXEC statements or eval (). 3 parameter Source: A string or an AST (abstract syntax trees) object. 4 parameter filename: The code file name, and some recognizable values are passed if the code is not read from the file. 5 parameter Model: Specifies the kind of compiled code. You can specify ' exec ', ' eval ', ' single '. 6 parameter flag and Dont_inherit: These two parameters are optional.
1 >>> s  = "print (' HelloWorld ')" 2 >>> r = Compile (s, "<string>", "exec") 3 >>> R4 <c Ode Object <module> at 0x000001c648038390, file ' <string> ', line 1>

Complex ()

1 Create a complex number with a value of real + imag * J or convert a string or count to plural. If the first argument is a string, you do not need to specify a second argument. 2 parameter Real:int,long,float or string. 3 parameter imag:int,long,float.

Delattr () Delete the properties of an object

Dict () Creating a data dictionary

1 >>> a = dict ()  null dictionary 2 >>> a3 {}4 >>> B = dict (one = 1, =2) 5 >>> b6 {' One ': 1, ' Both ': 2}7 >>> c = dict ({' One ': 1, ' One ': 2}) 8 >>> C9 {' One ': 1, ' both ': 2}

Dir () returns the current range of variables, the method and the defined type list, the property of the parameter when the parameter is returned with the argument, the method list

1 >>> dir () 2 [' __builtins__ ', ' __doc__ ', ' __loader__ ', ' __name__ ', ' __package__ ', ' __spec__ ', ' Li ', ' li1 ', ' Li2 ' , ' li_1 ']3 >>> dir (list) 4 [' __add__ ', ' __class__ ', ' __contains__ ', ' __delattr__ ', ' __delitem__ ', ' __dir__ ', ' __ Doc__ ', ' __eq__ ', ' __format__ ', ' __ge__ ', ' __getattribute__ ', ' __getitem__ ', ' __gt__ ', ' __hash__ ', ' __iadd__ ', ' __imul_ _ ', ' __init__ ', ' __iter__ ', ' __le__ ', ' __len__ ', ' __lt__ ', ' __mul__ ', ' __ne__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ' , ' __repr__ ', ' __reversed__ ', ' __rmul__ ', ' __setattr__ ', ' __setitem__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' Append ', ' clear ', ' copy ', ' Count ', ' extend ', ' index ', ' Insert ', ' pop ', ' remove ', ' reverse ', ' sort ']

Divmod () the respective vendor and remainder

1 >>> divmod (20,6) 2 (3, 2)

Enumerate () Returns an object that can be enumerated, and the next () method of the object returns a tuple

1 >>> test = [' A ', ' B ', ' C ']2 >>> for k,v in Enumerate (test): 3     print (K,V) 4  5 # Output: 6 0 A7 1 B8 2 C

Eval () evaluates the string str as a valid expression and returns the result of the calculation

1 >>> s = "1+2*3" 2 >>> type (s) 3 <class ' str ' >4 >>> eval (s) 5 7

. exec () Execute string or Complie method compiled string, no return value

The. Filter () filter, constructs a sequence equivalent to [item for item in Iterables if function (item)], sets the filter condition in the function, loops the elements in the iterator one by one, leaves the element with the return value true, form a filter type data

1 Filter (function, iterable) 2 parameter function: Returns a value of TRUE or FALSE, which can be none. 3 parameter iterable: A sequence or an iterative object. 4 >>> def bigerthan5 (x): 5 ...     return x > >>> filter (Bigerthan5, [3, 4, 5, 6, 7, 8]) 7 [6, 7, 8]

Float () to convert a string or integer to a floating-point number

1 >>> float () 2 0.0 3 >>> float (' 123 ') 4 123.0 5 >>> Float (1) 6 1.0 7 >>> float (' a ') 8 Traceback (most recent): 9   File "<pyshell#45>", line 1, in <module>10     float (' a ') valueerr Or:could not convert string to float: ' A '

Format () formatted output string, format (value, Format_spec) is essentially the __format__ (Format_spec) method that called value

1 >>> "I am {0}, I like {1}!". Format ("Wang", "Moon")    2 ' I am Wang, I like moon! '

Frozenset () Create a non-modifiable collection

1 Frozenset ([iterable]) 2 The most essential difference between set and Frozenset is that the former is mutable and the latter is immutable. When the collection object is changed (such as deleting, adding elements), you can use set only where set,3 generally uses Fronzet. 4 parameter iterable: The object can be iterated.

GetAttr () Gets the properties of an object

1 GetAttr (object, name [, Defalut]) 2 Gets an attribute with object name name, and if object does not contain an attribute named name, the Attributeerror exception will be thrown, if the attribute named name is not included 3 And the default parameter is supplied, the default is returned. 4 Parameter: Object 5 parameter name: attribute name of object 6 parameter default: Default return value 7 >>> append = getattr (list, ' append ') 8 >>> append 9 &l T;method ' append ' of ' list ' objects>10 >>> mylist = [3, 4, 5]11 >>> append (mylist, 6) >>> mylist13 [3, 4, 5, 6]14 >>> method = GetAttr (list, ' Add ') Traceback (most recent call last):   "<st Din> ", line 1, in <module>17 attributeerror:type object ' list ' have no attribute ' Add ' >>> method = ge Tattr (list, ' Add ', ' Nomethod ') >>> method20 ' Nomethod '

Globals () returns a dictionary that describes the current global variable.

1 >>> a = >>> globals () 3 {' __loader__ ': <class ' _frozen_importlib. Builtinimporter ', ' a ': 1, ' __builtins__ ': <module ' builtins ' (built-in);, ' __doc__ ': None, ' __name__ ': ' __main __ ', ' __package__ ': None, ' __spec__ ': none}

Hasattr ()

1 hasattr (Object,name) 2 Determines whether the object contains an attribute named name (Hasattr is implemented by calling GetAttr (Object,name) to throw an exception). 3 Parameter object: 4 parameter name: attribute name 5 >>> hasattr (list, ' append ') 6 True7 >>> hasattr (list, ' Add ') 8 False

. Hash () hashes

1 Hash (object) 2 Returns the object's hash value if the object is a hash table type. The hash value is an integer, and in the dictionary lookup, the hash value is used for the key of the Express parity dictionary. 32 values if equal, the hash value is also equal.

Help () returns the helper document for the object

A. ID () Returns the memory address of an object

1 >>> a = >>> ID (a) 3 1588522800

Get user input from. Input ()

1 num = input ("Please enter a number:") 2 # User input (num) 4 # output Result 5 3

A. Int () Converts a string or numeric value to a normal integer

1 int ([X[,radix]]) 2 If the argument is a string, it may contain symbols and decimal points. The parameter radix represents the cardinality of the transformation (default is 10 binary). 3 It can be a value in the range of [2,36], or 0. If it is 0, the system is parsed according to the string contents. 4 If the parameter radix is supplied, but the parameter x is not a string, the TypeError exception is thrown; 5 Otherwise, the parameter x must be a numeric value (normal integer, long integer, floating point). The floating point is converted by rounding the decimal point. 6 If the representation range of a normal integer is exceeded, a long integer is returned. 7 If no arguments are supplied, the function returns 0.

Isinstance () checks whether an object is a class object, returns True or False

1 isinstance (obj, CLS) 2 checks if obj is a class CLS object, returns TRUE or False3 class Foo (object): 4     pass5 obj = Foo () 6 isinstance (obj, foo)

Panax Notoginseng. Issubclass () checks if a class is a subclass of another class. Returns TRUE or False

1 Issubclass (Sub, super) 2 Check if the sub class is a derived class (subclass) of the Super class. Returns TRUE or False 3   4 class Foo (object): 5     Pass 6     7 class Bar (Foo): 8     Pass 9    issubclass (Bar, Foo)

ITER ()

1 iter (o[, Sentinel]) 2 returns a Iterator object. The function's resolution for the first parameter depends on the second argument. 3 If no second argument is provided, the parameter o must be a collection object, support Traversal (__iter__ () method) or support sequence function (__getitem__ () method), 4 parameter is an integer, and zero-based. If these two functions are not supported, the TYPEERROR exception will be punished. 5 If the second argument is supplied, the parameter o must be a callable object. In this case a iterator object is created, each call to the next () method of iterator to call O without a 6 parameter, if the return value equals the parameter sentinel, the stopiteration exception is triggered, otherwise the value is returned.

A. Len () returns the length of the object, which can be a sequence type (string, tuple, or list) or a mapping type (such as a dictionary)

The list () listing constructor

1 list ([iterable]) 2 The constructor of the list. The parameter iterable is optional, it can be a sequence, a container object that supports compilation, or a iterator object. 3 The function creates a list of element values, in the same order as the parameter iterable. If the parameter iterable is a list, a copy of the 4 list is created and returned, just like the statement iterables[:].

Locals () print a dictionary of the currently available local variables

1 Do not modify the contents of the dictionary returned by locals (); changes may not affect the parser's use of local variables. 2 call Locals () in the function body and return the free variable. Modifying a free variable does not affect the parser's use of the variable. 3 You cannot return a free variable within a class area.

Map ()

1 map (function, iterable,...) 2 applies the fuction function for each element in the parameter iterable and returns the result as a list. 3 If there are multiple iterable parameters, then the Fuction function must receive multiple arguments, and the elements at the same index in those iterable will be parallel as arguments to the function functions. 4 If the number of elements in a iterable is less than the others, then the iterable will be extended with none to make the number of elements consistent. 5 If there is more than one iterable and function is None,map () returns a list of tuples, each containing the value at the corresponding index in all iterable. The 6 parameter iterable must be a sequence or any object that can be traversed, and the function returns a list. 7   8 li = [14] 9 data = map (lambda x:x*100,li) print (type data) one data = List (data) print (data)  run Result:  <class ' map ' >17 [100, 200, 300]

Max () returns the maximum value in a given element

1 Max (iterable [, args ...] [, Key]) 2 if only the iterable parameter is supplied, the function returns the largest non-empty element that can traverse an object, such as a string, tuple, or list. 3 If more than one parameter is supplied, the one with the largest return value. 4 Optional Parameter key is a single-parameter sort function. 5 If the key parameter is supplied, it must be in the form of a name, such as: Max (A, B, c, key = Fun)

Meoryview ()

MIN () returns the minimum value in the given element

1 min (iterable [, args ...] [, Key]) 2 if only the iterable parameter is supplied, the function returns the smallest non-empty element that can traverse an object, such as a string, tuple, or list. 3 If more than one parameter is supplied, the parameter with the lowest return value. 4 Optional Parameter key is a single-parameter sort function. 5 If the key parameter is supplied, it must be in the form of a name, such as: Max (A, B, c, key = Fun)

Next () returns an iterator to the next item in a data structure, such as a list

. Object ()

1 Gets a new, no-attribute (geatureless) object. object is the base class for all classes. The method it provides will be shared across all instances of the type. 2 When the function is 2.2. Version new, after 2.3 version, the function does not accept any parameters.

Open () file

1 open (filename [, mode [, BufSize]]) 2 opens a file that returns a Files object. If the file cannot be opened, the IOError exception will be punished. 3 You should use open () instead of opening the file directly using the constructor of the file type. The 4 parameter filename indicates the path string of the file to be opened, and the 5 parameter mode indicates the open mode, and the most commonly used modes are: ' R ' for the Read text, ' W ' for the Write text file, ' A ' for appending in the file. 6 The default value for mode is ' R '. 7 when manipulating binary files, simply add ' B ' to the mode value. This improves the portability of the program. 8 optional parameter bufsize defines the size of the file buffer. 0 means no buffering, 1 for row buffering, any other positive for buffers with that size, 9 negative for the system default buffer size, and for TTY devices it is often a row buffer, while for other files it is often fully buffered. If the parameter value is omitted. 10 Use the system default value.

. POW () power function

1 R = Pow (2, Ten)  # 2 10 square 2 print (r) 3               4 # Output 5 1024

. print () Output function

The print statement in 1 Python2 is replaced by the print () function in the Python3. 2 How to limit the default line break for print: 3 1. Python2 version, at the end of the print output, add a comma ', ' 4 2. After python3.4, print (value, ..., sep= ', end= ' \ n ', file=sys.stdout,flush=false), set end to null.

Wuyi Property ()

A. Range () generates a specified range of numbers as needed to provide the control you need to iterate over the specified number of times

1 is used to create a list that contains consecutive arithmetic values. Commonly used for a For loop. The parameter must be a normal integer. The 2 parameter step defaults to 1, and the default value for the start parameter is 0. 3 Full parameter Call this function will return a list of ordinary integers. 4 step can be a positive integer or a negative integer. Can not be 0, otherwise will punish ValueError exception. 5 Range (3) stands for 0,1,2. Equivalent to Range (0,3) 6 >>> Range (0,10,2)  #第一个参数是起始数, the second is the number of terminations (not including this), and the third step of 7 >>>[ 0,2,4,6,8]

Repr () converts any value to a string, in the form of a timer read

1 Repr (object) 2 Returns a string representation of an object. You can sometimes use this function to access operations. 3 for many types, repr () attempts to return a string, and the eval () method can use the string to produce the object, or 4 to enclose the string with the class name and other two outer information in angle brackets.

Reversed () reverse, Reverse object

1 reversed (SEQ) 2 Returns an iterator object in reverse order. The parameter seq must be an object that contains the __reversed__ () method or support sequence operations (__LEN__ () and __getitem__ ()) 3 The function is new in 2.4

Round () rounding

1 round (x [, N]) 2 rounds the n+1 decimal place of the parameter x, returning a floating-point number with a scale of N. 3 The default value for parameter n is 0. The result is a floating-point number. For example, round (0.5) results for 1.04 >>> round (4,6) 5->>> round (5,6) 7 5

. Set ()

SetAttr () corresponds to GetAttr ().

Slice () slicing function

Sorted () sort

1 >>> sorted ([36,6,-12,9,-22])  list sort 2 [ -22, -12, 6, 9, approx] 3 >>> sorted ([36,6,-12,9,-22],key=abs) high order Functions, sorted in absolute size 4 [6, 9, -12, -22, +] 5 >>> sorted ([' Bob ', ' about ', ' Zoo ', ' Credit '])  string sort, sorted by ASCII size 6 [' Cre Dit ', ' Zoo ', ' about ', ' Bob '] 7 if you need to sort a tuple, you need to use the parameter key, which is the keyword. 8 >>> A = [(' B ', 2), (' A ', 1), (' C ', 0)] 9 >>> list (sorted (A,key=lambda x:x[1]))   sorted by the second element of the tuple [(' C ', 0  ), (' A ', 1), (' B ', 2)]11 >>> list (sorted (A,key=lambda x:x[0]))   sorted by tuple's first element [(' A ', 1), (' B ', 2), (' C ', 0)]13 >>> sorted ([' Bob ', ' about ', ' zoo ', ' credits '],key=str.lower) ignoring the case sort [' about ', ' Bob ', ' credits ', ' Zoo '] >& Gt;> sorted ([' Bob ', ' about ', ' zoo ', ' credits '],key=str.lower,reverse=true) reverse sort [' zoo ', ' credits ', ' Bob ', ' about ']

Staticmethod ()

A. STR () string constructor

SUM () summation

The method of calling the parent class by a. Super ()

Group () tuple constructor

A. Type () displays the type to which the object belongs

VARs ()

The. zip () pair the objects individually

1 list_1 = [1,2,3]2 list_2 = [' A ', ' B ', ' C ']3 s = Zip (list_1,list_2) 4 print (list (s)) 5  6 Run Result: 7  8 [(1, ' a '), (2, ' B ') , (3, ' C ')]
1 A = [(1,), (2,), (3,)]2 R = Zip (*a) 3 print (list (r)) 4 run Result: 5 [(1, 2, 3)]6 print (list (r) [0]) 7 Run Result: 8 (1, 2, 3)

__import__ ()

Python3 built-in functions encyclopedia

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.