Pyhton built-in functions encyclopedia

Source: Internet
Author: User
Tags iterable printable characters

First, the mathematical operation class

ABS (x) Seek absolute value

1, the parameters can be integral type, can also be plural

2, if the parameter is a complex number, then return the modulus of the complex

Complex ([real[, Imag]]) Create a complex number

Coerce () can be regarded as a numeric type conversion function) has two parameters, all numbers, returns a list of the two numbers, unifying the data types of the two numbers. such as coerce (1,2J), return (1+0J,2J)

Divmod (A, B) separate fetch and remainder

Note: integral, floating-point types can be

float ([x]) Converts a string or number to a float. If no parameter is returned 0.0

int ([x[, Base]]) Converts a character to an int type, and base represents the binary

Long ([x[, Base]]) converts a character to a long type

POW (x, y[, z]) Returns the Y power of X

Range ([start], stop[, step]) produces a sequence that starts with 0 by default

round (x[, N]) Rounding

sum (iterable[, start]) Sum the Set

Oct (x) Convert a number to 8 binary

Ord (x) returns the ASC code number corresponding to the character, as Ord (' A ') returns 65

Hex (x) Converts an integer x to a 16-binary string

CHR (i) returns the ASCII character corresponding to the integer i

bin (x) Converts an integer x to a binary string

BOOL ([x])

Converts an X to a Boolean type, and if x defaults, returns a subclass of False,bool also int;

Parameter x: arbitrary object or default; you notice that [x] is used here, stating that the x parameter is optional and returns False if no arguments are given.


Second, the collection class operation

Str ([Object]) Convert to String type

Unicode

Unicode can support multiple languages, preceded by ASCII, and each English character is stored in the computer in a 7-bit binary number, ranging from 32 to 126.

However, ASCII code can only represent 95 printable characters, and later extended ASCII to 8-bit, so that it can represent 223 characters, although this to indicate that the European and American Alphabet language is enough, but for languages such as Chinese and other languages too little. So the Unicode code was born.

Unicode represents a character by using one or more bytes, which breaks the ASCII limit so that Unicode can represent more than 90,000 characters.

In order for Unicode and ASCII value strings to look as similar as possible, the Python string changed from the original simple data type to the real object, the ASCII string became StringType, and the Unicode string became the Unicodetype type. Their behavior is very similar. There are corresponding processing functions in the string module. The string module has stopped updating and retains only support for ASXII code, the string module is deprecated and is not used in any Unicode-compatible code, and Python retains the module for backwards compatibility only.

In Python, all literal strings are ASCII-encoded, and you can declare a Unicode string by prefixing the string with a ' u ' prefix, which tells the string following python to be a Unicode string.

Apply Unicode to the real world note that four points:

1 You must prefix a string when it appears in the program

2 Do not use the STR () function in place of Unicode ()

3 Do not use outdated string modules. If you pass it non-ASCII, it will screw everything up.

4 do not encode Unicode characters in your program until you have to, and only call the Encode () function and the decode () function when you are writing to a file or database or network.

Basestrin g ()the superclass (parent class) of STR and Unicode, which is also an abstract class, cannot be called and instantiated, but can be used to determine whether an object is an instance of STR or Unicode, isinstance (obj, basestring) is equivalent to isinstance (obj, (str, Unicode));

ByteArray ([Source [, encoding [, errors]]) returns a byte array

The ByteArray type is a mutable sequence, and the value range of the elements in the sequence is [0, 255].

Parameter Source:

If source is an integer, returns an initialized array of length source;

If source is a string, the string is converted to a sequence of bytes according to the specified encoding;

If source is an iterative type, the element must be an integer in [0, 255];

If source is an object that is consistent with the buffer interface, this object can also be used to initialize the ByteArray:

Version: Newly introduced after python2.6, can also be used in Python3!

Usage Scenario: You can use ByteArray when you want to traverse every byte of str. In particular, Python 3 inside str, because always in Unicode, only with ByteArray to access to the string true byte.

The main difference between the bytes function and the ByteArray function is that the elements of the object that the bytes function produces cannot be modified, and the elements of the object that the ByteArray function produces can be modified. Therefore, except for modifiable object functions that are not the same as the ByteArray function, all other usage methods are the same. Finally, its parameters are defined in the same way as the ByteArray function.

format (value [, Format_spec]) formatting the output string

Formatted parameter order starting from 0, such as "I am {0},i like {1}"

UNICHR (i) Returns the Unicode of the given int type

Enumerate (sequence [, start = 0]) returns an enumerable object with the next () method returning a tuple

ITER (o[, Sentinel]) generates an iterator for an object, and the second parameter represents a delimiter

Max (iterable[, args ...] [Key]) returns the maximum value in the collection

min (iterable[, args ...] [Key]) returns the minimum value in the collection

Dict ([ARG]) Create a data dictionary

List ([iterable]) to convert a collection class to another collection class

Set The () and frozenset() functions are used to generate mutable and immutable collections, respectively. If no arguments are supplied, an empty collection is generated by default. If you supply a parameter, the argument must be iterative, that is, a sequence or iterator, or an object that supports iterations, such as a file or a dictionary.

Sorted (iterable[, cmp[, key[, reverse]])

Function: Return a new sorted list from the items in iterable.

The first parameter is a iterable, and the return value is a list that sorts the elements in iterable.

The optional parameters are three, CMP, key, and reverse.

1) CMP Specifies a custom comparison function that receives two parameters (elements of iterable), returns a negative number if the first argument is less than the second argument, returns 0 if the first argument is equal to the second argument, or returns a positive number if the first argument is greater than the second argument. The default value is None.

2) key specifies a function that receives a parameter, which is used to extract a keyword from each element for comparison. The default value is None.

3) Reverse is a Boolean value. If set to True, list elements are sorted in reverse order.

In general, key and reverse are faster than an equivalent CMP function. This is because the CMP is called multiple times for each list element, and key and reverse are called only once.

3. The specific usage is as follows:

1) Sort Basics

A simple ascending arrangement is simple-just call the sorted () function. This function returns a new sorted list. :

>>> sorted ([5,2,3,1,4])

[1,2,3,4,5]

You can also use the List.sort () method of the list. This method modifies the original list (the return value is None). Usually this method is less convenient than sorted ()-If you do not need the original List,list.sort () method, the efficiency will be slightly higher.

>>> a=[5,2,3,1,4]

>>> A.sort ()

>>> A

[1,2,3,4,5]

Another difference is that the List.sort () method is defined only for list. The sorted () function can receive any iterable.

>>> Sorted ({1: ' D ', 2: ' B ', 3: ' B ', 4: ' E ', 5: ' A '}) [1, 2, 3, 4, 5]


Reversed () #倒序排列函数 such as the Print list (reversed ([' Dream ', ' a ', ' have ', ' I ') ') results [' I ', ' have ', ' a ', ' dream ']

tuple ([iterable]) generates a tuple type

xrange ([start], stop[, step]) the xrange () function is similar to range (), but xrnage () does not create a list, but instead returns a Xrange object that behaves like a list, but calculates the list value only when it is needed, which saves us memory when the list is large.


Third, logical judgment

All (iterable)

1, the elements in the collection are true when they are true

2, special, if the empty string returned to True

any (iterable)

1, the elements in the collection have a true time for the true

2, special, if the empty string returned to False

CMP (x, Y)

If x < Y, returns a negative number; x = = y, returns 0;x > y, returns a positive number

Iv. Reflection

callable (object) checks whether object objects can be called

1, the class is can be called

2. Instances cannot be invoked unless the __call__ method is declared in the class

Classmethod ()1, annotated, to illustrate that this method is a class approach

2. Class methods can be called by the class or by instance

3. The class method is similar to the static method in Java

4. The self parameter is not required in a class method

Compile (source, filename, mode[, flags[, Dont_inherit]]) compiles source into code or AST object. The code object can be evaluated by EXEC statement execution or eval ().

1. Parameter source: string or AST (Abstract Syntax Trees) object.

2, Parameter filename: code file name, if not read from the file code is passed some recognizable values.

3. Parameter model: Specifies the kind of compiled code. can be specified as ' exec ', ' eval ', ' single '.

4. Parameter flag and Dont_inherit: These two parameters are not introduced temporarily

dir ([Object])

1, without parameters, returns the list of variables, methods, and definitions in the current scope;

2, with parameters, returns the properties of the parameter, the method list.

3. If the parameter contains method __dir__ (), the method will be called. When the argument is an instance.

4. If the parameter does not contain __dir__ (), the method will collect the parameter information to the maximum

delattr (object, name) Delete an object named Name property

Eval (expression [, globals [, locals]]) evaluates the value of an expression

execfile (filename [, globals [, locals]]) The usage is similar to exec (), the difference is that the execfile parameter filename is the file name, and the exec parameter is a string.

Filter (function, iterable) Constructs a sequence that is equivalent to [item for item ' in Iterable if function(item)]

1, Parameter function: Return a value of TRUE or false functions, can be none

2. Parameter iterable: A sequence or an iterative object

GetAttr (Object, name [, Defalut]) Gets the properties of a class

Globals () Returns a dictionary that describes the current global symbol table

hasattr (object, name) Determines whether the object contains an attribute named name

Hash (object) Returns the hash value of object if object is a hash table type

ID (object) returns the unique identity of an object

isinstance (Object, ClassInfo) Determine if object is an instance of class

Issubclass (class, ClassInfo) Determine if it is a subclass

Len (s) returns the set length

Locals () returns the current list of variables

Map (function, iterable, ...) iterate through each element to perform a function operation

Memoryview (obj) Returns an object of a memory image type

Next (iterator[, default]) similar to Iterator.next ()

Object () base class

Property ([fget[, fset[, fdel[, Doc]]) the wrapper class for property access, which can be set to access the setter and getter via C.x=value, etc.

Reduce (function, iterable[, initializer]) The merge operation, which starts with the first two parameters, and then the first two results are processed with the third merge, and so on

Reload (module) Reload Module

SetAttr (object, name, value) Setting property values

repr (object) changing an object to a printable format

Slice() Returns a Slice object that represents the range specified by range (start, stop, step). The start and step parameters default to None. The Slice object has read-only data properties Start,stop and step, which simply returns the parameter value (or default).

Staticmethod declares a static method, which is an annotation

Super (type[, Object-or-type]) referencing a parent class

type (object) Returns the type of the object

VARs ([Object]) Returns the variable of the object, if no argument is similar to the Dict () method

ByteArray ([Source [, encoding [, errors]]) returns a byte array

1, if source is an integer, returns an initialized array of length source;

2. If source is a string, the string is converted to a sequence of bytes according to the specified encoding;

3. If source is an iterative type, the element must be an integer in [0, 255];

4. If source is an object that is consistent with the buffer interface, this object can also be used to initialize the ByteArray.

Zip ([Iterable, ...])

It takes a series of iterated objects as parameters, packages the corresponding elements in the object into a tuple (tuple), and returns a list of these tuples. If the length of the passed parameter is not equal, the length of the returned list is the same as the object with the shortest length in the parameter. Using the * operator, you can unzip the list (unzip).

V. IO operation

file (filename [, mode [, BufSize]]) A constructor for the file type that opens a file that is created if the file does not exist and mode is write or append. Adding ' B ' to the mode parameter will manipulate the file in binary form. Adding ' + ' to the mode parameter will allow simultaneous read and write operations to the file

1. Parameter filename: Name of the file.

2, Parameter mode: ' R ' (read), ' W ' (write), ' a ' (append).

3, parameter bufsize: If 0 is not buffered, if 1 is a row buffer, if it is a number greater than 1 indicates the size of the buffer.

input ([Prompt]) Get user input

It is recommended to use raw_input because the function will not capture the user's error input

Open (name[, mode[, Buffering]) Open File

What is the difference from file? Recommended use of Open

print printing function

Raw_input ([Prompt]) Set input, input is handled as String

Vi. Other

Help ()--Information

Apply (), buffer (), coerce (), intern ()---these are built-in functions that are out of date, so it does not explain


Vii. PostScript

Built-in functions, generally because the use of frequency is more frequent or meta-operation, so through the form of built-in functions provided, through the Python built-in function classification analysis can be seen: basic data operations are basically some mathematical operations (except subtraction), logical operations, set operations, basic IO operations , and then it is the reflection of the language itself, but also the operation of the string, is also more commonly used, especially the need to pay attention to the reflection operation.


This article is from the "Small Five Car God" blog, please be sure to keep this source http://linuxtech.blog.51cto.com/3670088/1742712

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