Python common set of built-in functions

Source: Internet
Author: User
Tags abs chr ord pow string format nameserver
1, Python type operator and built-in function summary

Table 4.5 lists all the operators and built-in functions, where the order of the operators is arranged by priority from highest to lowest. Operators of the same gray level have the same priority. Note that the functions of these (and most Python) operators in the operator module are available for use.

Table 4.5 standard type operators and built-in functions

Operator/function

Description

Result A

String representation

``

String representation of an object

Str

Built-in functions

CMP (OBJ1, OBJ2)

Compare two objects

Int

Repr (obj)

String representation of an object

Str

STR (obj)

String representation of an object

Str

Type (obj)

Detecting the type of object

Type

Value comparison

<

Less than

bool

>

Greater than

bool

<=

Less than or equal to

bool

>=

Greater than or equal to

bool

==

Equals

bool

!=

Not equal to

bool

<>

Not equal to

bool

Object comparison

is

Is

bool

is not

No

bool

Boolean operator

not

Logical counter

bool

and

Logic and

bool

or

Logical OR

bool



2. Python numeric type operators and built-in functions

first, the factory function

Numerical Factory function Summary class (factory function) operation

BOOL (obj) b returns the Boolean value of the Obj object, which is the return value of the obj.__nonzero__ () method.

int (obj, base=10) returns an integer representation of a string or numeric object, similar to String.atoi ();

From Python 1.6, an optional feed parameter was introduced.

Long (obj, base=10) returns an integer representation of a character or data object, similar to String.atol (),

From the Python1.6, optional feed parameter float (obj) is introduced.

Returns a floating-point number representation of a string or data object, similar to String.atof ().

Complex (str) or returns a plural representation of a string, or, depending on the given real number,

Complex (real, imag=0.0) (and an optional imaginary part) generates a complex number object.

two, built-in function

1, classification

Python has five computational built-in functions for numeric operations:

ABS (num), coerce (num1,num2), Divmod (num1,num2), pow (num1,num2,mod=1) and round (flt,ndig=0)

where ABS () returns the absolute value of the given parameter. If the argument is a complex number, it returns MATH.SQRT (Num.real2 + num.imag2).

Coerce () is a data type conversion function, but behaves more like an operator. The number coerce () provides a way for programmers to customize two numeric type conversions without relying on the Python interpreter. This feature is useful for a newly created numeric type. function Coerce () returns only a tuple containing two numeric elements that have finished converting the type.

The Divmod () built-in function combines division and remainder operations, returns a tuple that contains both the quotient and the remainder. For integers, the return value is the result of the floor removal and redundancy operation. For floating-point numbers, the returned quotient portion is Math.floor (num1/num2), and for the plural, The quotient section is Ath.floor ((num1/num2). Real).

POW () it and the Double star (* *) operator can be indexed. But the difference is not just one operator, but one built-in function. Before Python 1.5, there was no * * operator, and the built-in function pow () also accepted the third optional argument. A remainder parameter. If you have this argument, pow () first the exponential operation, and then the result of the operation and the third parameter for the remainder of the operation. This feature is primarily used for cryptographic operations and is better than POW (x,y)% Z because the implementation of this function is similar to the C function pow (x,y,z).

Round () is used to round up floating-point numbers. It has an optional scale parameter. If you do not supply a decimal parameter, it returns the nearest integer (but still the floating-point type) that is closest to the first parameter. The second argument tells the round function to specify the number of digits after the decimal point.

2, function int ()/round ()/math.floor () The difference between them:

function int () to intercept the decimal part directly. (return value is an integer)

function floor () Gets the integer closest to the original but less than the original. (The return value is a floating-point number)

The function round () Gets the integer closest to the original number. (The return value is floating point numbers)

3, the transformation function of the system:

Returns the 8-and 16-binary integers represented by a string, which are built-in functions, respectively:

Oct () and Hex (). Oct (255) = ' 0377 '/hex (255) = ' 0xFF '

The function Chr () accepts a single-byte integer value (0 to 255) and returns a string (ASCII) with the corresponding character. chr = ' a '

function ord () instead, it accepts a character (ASCII or Unicode) and returns its corresponding integer value. Ord (' A ') =65
3. Python string function

(i) standard type operators and standard BUILTIN functions
1), Standard type operator
>,<,>=,<=,==,!=,<> Objects Worth comparing
Note: The string is compared to the size of the ASCII value.
Is Object identity comparison
And,or,not Boolean type
2) Standard built-in function
Type (obj)
CMP (OBJ1,OBJ2)
STR (obj) and repr (obj) or inverted quotation operators ("") can easily get the object's
Information such as content, type, numeric properties, and so on. The STR () function gets a good string readability, and the repr () function gets the character
A string can usually be used to regain the object, and typically obj = = eval (repr (obj)) is a valid equation.
Isinstance (Obj,type) determines the type of object

(ii) Sequence operations
1. Sequence operation
Strings are part of a sequence object, and you can use the actions and functions of all sequences
slices [] [:] [::]
Simple summary:
* Index (S[i]) Gets the element of a specific offset.
--The first element is offset to 0
--(S[0]) gets the first element.
--The negative offset index means that the count is reversed from the last or right
--(S[-2]) gets the penultimate element (just like S[len (S)-2]
* Fragment [s[i:j] extracts the corresponding part as a sequence
--Right border not included
--The fragment boundary defaults to 0 and the length of the sequence, if not given the words s[:]
--(S[1:3]) gets an element with an offset of 1 until but not including an offset of 3
--(s[1:]) Gets the element from the offset of 1 to the end
--(S[:3]) Gets an element that is offset from 0 until it does not include an offset of 3
--(S[:-1]) gets the element from the offset of 0 until the last element is not included
--(s[:]) Gets the element from the offset of 0 to the end, which effectively implements the top S copy
Copies an identical value, but is an object of different memory regions. Object strings Such immutable objects are not useful, but are useful for objects that can be modified on the ground.
such as lists.
Extended fragmentation: Third restriction value "stepping"
Full form: X[i:j:k]: This identifies the element of the index X object, from the offset to I until the J-1, each time the K element is indexed. The third limit value, K, defaults to 1
Instance
Python Code

1
2
3
4
5
>>> s= ' Abcdefghijk '
>>> s[1:10]
' Bcdefghij '
>>> s[1:10:2]
' Bdfhj

You can also use negative numbers as stepping.
Piecewise expression
Python Code
1
2
>>> "Hello" [::-1]
' Olleh '

With negative steps, the meaning of the two boundaries is actually reversed.

3, member operator in, not in
Returns a Boolean value of TRUE or False
You can use the string module to determine the legality of the input character, visible idcheck.py in the finished product

4. String connection
+ connection string ' name ' + ' + ' Jin '
String format '%s '% (' name ', ' Jin ')
Join () method '. Join ((' name ', ' Jin ') '. Join ([' Name ', ' Jin '])

5. Delete empty string
Del astring
Astring= '
(iii), sequence functions
Sequence type function
Len (str) returns the length of a string
Enumerate (ITER): Takes an iterative object as an argument and returns a enumerate
Max (str)/min (str): the Max () and Min () functions may be more useful for other sequence types, but they work well for string types, returning the largest or smallest characters (sorted by ASCII code values),
Zip ([it0, It1,... ItN]) returns a list whose first element is It0,it1,... The first element of these elements consists of a tuple, the second ..., and so on.
Reversed (SEQ) c takes a sequence as an argument, returning an iterator that accesses in reverse order (PEP 322)
Sorted (Iter,func=none,key=none,reverse=false) accepts an iterative object as an argument, returning an ordered list; optional parameters func,key and reverse meaning with list.sort () The parameter meaning of the built-in function is the same.
Attention:
Sorted functions that need to be modified in situ cannot be used in string objects, but can produce new objects
Sum is a numeric object and cannot be used in a string

>>> Sorted (s)
[' A ', ' e ', ' e ', ' g ', ' g ', ' g ', ' O ']

(iv) functions appropriate to string type
1) the Raw_input () function
built-in raw_input () function uses the given string to prompt the user for input and returns the input, following is an example of
using Raw_input ():
>>> user_input = raw_input ("Enter Your Name:")
>>> prin user_input
2) str () and Unicode ()
St Both the R () and Unicode () functions are factory functions, that is, objects that produce the corresponding type. They accept an object of type
meaning, and then create a printable or Unicode string representation of the object. They and basestring both
The Isinstance () function can be passed as an argument to determine the type of an object
3) Chr (), UNICHR (), and Ord ()
the Chr () function to use a range (0 to 255) integer as an argument, Returns a corresponding character. UNICHR () Just like it, only returns the Unicode character the
Ord () function is the pairing function of the Chr () function (for a 8-bit ASCII string) or the UNICHR () function (for Unicode objects)
. It takes a character (length 1 string) as an argument, returns the corresponding ASCII value, or Unicode
value, and throws a TypeError exception if the given Unicode character is outside your Python definition range

(v) operators that apply only to strings
1. Format operator%
String formatting symbols
Format Character Conversion method
%c to a character (ASCII value, or a string of length)
%ra precedence with repr () function for string conversion
%s Precedence for string conversions with the STR () function
%d/%i converted to signed decimal numbers
%ub into unsigned decimal numbers
%ob Convert to unsigned octal number
%XB/%XB (Unsigned) to an unsigned hexadecimal number (x/x represents the size of the converted hexadecimal character
lowercase
%e/%e to scientific counting method (e/e control output e/e)
%f/%f to floating-point number (fractional part natural truncation)
Shorthand for%g/%g%e and%f/%e and%f
%% OUTPUT%
Format operator Auxiliary Instruction
Symbolic effect
* Define width or decimal point accuracy
-Used for left alignment
+ Show plus sign (+) before positive number
<sp> show spaces before positive numbers
# Displays 0 (' 0 ') before the octal number, showing ' 0x ' or ' 0X ' before hexadecimal (depending on
With an ' x ' or ' x '
0 The number displayed is preceded by the ' 0 ' instead of the default space
%% '% ' output a single '% '
(VAR) mapping variable (dictionary parameter)
M.N m is the minimum total width shown, n is the number of digits after the decimal point (if available)

2. String Template: A simpler alternative
Since the introduction of the new String Template object, the string module has come alive again, Template object
There are two methods, substitute () and Safe_substitute (). The former is more rigorous, in the case of key missing it will report a
A Keyerror exception, which, when missing key, shows the string directly intact.

3, the original string operator (R/R)
String suppression escape R ' string with special characters '
Myfile=open (R ' C:\new\text.data ', ' W ')

4. Unicode string operator (u/u)
U ' abc ' u+0061 u+0062 u+0063
U ' \u1234 ' u+1234
U ' abc\u1234\n ' u+0061 u+0062 u+0063 u+1234 u+0012


(vi) method of string object:
1, the deletion
T2.lstrip () removes the preceding character (the default space) of the string and returns the string
T2.rstrip () removes character after string (default space), returns string
T2.strip () Removes the space before the string, returns the default space for the string, and can s.strip other characters (' ")

2, cutting
Partition (Sep),
Rpartition (Sep),
Splitlines ([Keepends]), #把S按照行分割符分为一个list, Keepends is a bool value, and if true, the row delimiter is preserved after each row
Split ([Sep [, Maxsplit]]), #以sep为分隔符, divides s into a list. Maxsplit represents the number of splits. The default delimiter is a blank character
Rsplit ([Sep[,maxsplit]]) #从右到左切割
Note:
The partition () function family is a new method in version 2.5. It takes a string parameter and returns a tuple object of 3 elements.
If Sep does not appear in the parent string, the return value is (Sep, ', ');
Otherwise, the first element of the returned value is the part of the left side of the SEP, the second element is the SEP itself, and the third element is the part of the right end of Sep.
>>> s.partition (';')
(', '; ', ' generated by/sbin/dhclient-script\nnameserver 172.16.10.171\nnameserver 8.8.8.8\nnameserver 172.16.0.2\ Nnameserver 178.79.131.110\nnameserver 202.96.199.133\n ')
The parameter maxsplit is the number of slitting times, that is, the maximum number of slitting times, so the return value has a maximum of maxsplit+1 elements.
S.split () and S.split (') return values are different
>>> ' Hello world! '. Split ()
[' Hello ', ' world! ']
>>> ' Hello world! '. Split (")
[', ', ' hello ', ', ', ', ' world! ']
>>> s.split (' \ n ', 3)
['; generated by/sbin/dhclient-script ', ' nameserver 172.16.10.171 ', ' nameserver 8.8.8.8 ', ' nameserver 172.16.0.2\ Nnameserver 178.79.131.110\nnameserver 202.96.199.133\n ']
More than the maximum number of cuts after the whole is an element
Cut by line
>>> S

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