The road of python-development-built-in function

Source: Internet
Author: User
Tags abs integer numbers ord pow


As pictured above, this will be a brief demonstration of what is commonly used in Python's built-in functions
For easy viewing, the functions of the same method are linked together to demonstrate; abs (): Absolute values

>>> Print (ABS ( -2345)) #
2345
/# 0,[], "", (), {},none These characters are used as Boolean values in Python flase All (): true, true
#all不接受多个字符串作为参数, you can only place these parameters in a list (or meta ancestor, etc.)
>>> print (All (0,true,1,[' qwe ', ' wer ',], ' qwe ')
traceback ( Most recent called last):
  File "<stdin>", line 1, in <module>
Typeerror:all () takes exactly one argumen T (5 given)
#因为0被python认为是False, so the whole is False
>>> print (All ([' qwe ', ' wer ', true,0,])
false
#改成1后就变成True了,
>>> print (All ([' qwe ', ' wer ', true,1,])
True
any (): true if either one is true
>>> print (Any ([none,0,[], (),]))
False
>>> Print (Any ([none,0,[], (), 1,])
True
Digital Conversion: Bin (), Oct (), int (), Hex ( ),
#初始化变量
>>> ret=520
#十进制转为二进制
>>> print (ret)
0b1000001000
#十进制转八进制
>>> Print (Oct (ret))
0o1010
#十进制转为十进制
>>> print (int (ret))
520
# Decimal hexadecimal
>>> print (Hex (ret))
0x208

bool (): To judge a Boolean value
>>> Print (bool (0))
False
>>> Print (bool (1))
True
>>> print (bool None))
false
>>> print (bool ("))
false
>>> print (bool (" QWERTW "))
True
float (): Convert integer numbers to floating-point round (float (), num): A floating-point number rounded to the decimal point after a specified number of digits (num)
>>> reg=520
>>> float (reg)
520.0
>>> ret = reg/1314
>>> Round (ret,4)
0.3957
>>> print (ret)
0.395738203957382
bytes (): Converts a string to a byte, which can be used to convert the character set "important"
>>> name = "Cloud Walk"                                                                                                                                                                                             
>>> ret = bytes (name,encoding= ' GBK ')
>>> reg = bytes (name,encoding = ' Utf-8 ')
>>> print (ret,reg)
B ' \xd4\xc6\xb6\xcb\xc2\xfe\xb2\xbd ' B ' \xe4\xba\x91\xe7\xab\xaf\xe6 \xbc\xab\xe6\xad\xa5 '
Ord (): Find the numeric value of the character in the ASCII table chr (): Reverse lookup the character corresponding to the ASCII table represented by the value
>>> ASG = "B"
>>> Ord (ASG)
>>> chr (Ord (ASG))
' B '

Can use this to implement the function of the random authentication code, detailed can point this reference dir (), Help ():P Ython to obtain the assistance information

>>> dir (dir)
[' __call__ ', ' __class__ ', ' __delattr__ ', ' __dir__ ', ' __doc__ ', ' __eq__ ', ' __format__ ', ' __ge __ ', ' __getattribute__ ', ' __gt__ ', ' __hash__ ', ' __init__ ', ' __le__ ', ' __lt__ ', ' __module__ ', ' __name__ ', ' __ne__ ', ' __< C1/>new__ ', ' __qualname__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __self__ ', ' __setattr__ ', ' __sizeof__ ', ' __str __ ', ' __subclasshook__ ', ' __text_signature__ ']
>>> help (dir) Help on
built-in function dir in module Builtins:

dir (...)
    Dir ([object])-> List of strings ...
    
Divmod (): Make division and return the quotient and remainder to the Ganso situation
>>> a = 1314
>>> b = 520
>>> divmod (a,b)
(2, 274)

This can achieve a small case: (a total of 234 records, each page shows 25, a total of several pages)

Total = 234
per = =
Divmod (total,per)
if result[1] = = 0:
    ret = result[0]
else:
    re t = result[1]
print (ret)
Enumerate (): iterator, return index and value to list situation
#创建对象来表现
a = [11,22,4,33,4,[1,2,3,4,]]
ret = Enumerate (a)
print (ret)
print (list (ret))

    > < Enumerate object at 0x0000000000d91480>
    > [(0, one), (1), (2, 4), (3,), (4, 4), (5, [1, 2, 3, 4])]

#或者 Performance for
Index,value in Enumerate (a) with a for loop iterator:
    print (Index,value)
    >0
    >1
    >2 4
    >3
    >4 4
    >5 [1, 2, 3, 4]
eval (): Executes an expression, gets the result, and has a return value

Ps:eval () Arg 1 must be a string, bytes or code object,eval () to the type of argument

reg = ' 1+ (2+8) *3 '
ret = eval (reg)
print (ret)
compile (): Escaping a string into Python code
reg = ' 1+ (2+8) *3 '
ret = compile (reg, ' <string> ', ' exec ')
print (Type (ret), ret)
<class ' Code ' > <code object <module> at 0x00000000006b28a0, file ' <string> ', line 1>
exec (): Execute Python code, but no return value
Reg = "Print (eval (' 1+ (2+8) *3 ')"
ret = EXEC (reg)
print (ret)

Summary: eval (), which encapsulates the method of compile () and exec () two functions, compile is responsible for escaping the string into Python code,exec executing the escaped code. Compile is more like adding a layer of adorners outside of exec and assigning a combination of function bodies to the Eval "important" filter (): Filtering on an iterative object

ret = [1,2,4,5,5,6,66,78,324,7,4,2,]
reg = filter (lambda a:a>6,ret)

print (Reg,type (reg))
Print (list ( REG))

Note that if you print the returned object Reg directly, you will give the memory address, and then look at the type, class ' filter ', so you have to create the object ' list ' again with the class that iterates the object.

Filter object at 0x0000000000d29e10> <class ' filter ' >
[66, 78, 324, 7]
"Important" map (): Manipulating an Iterative object
ret = [1,2,4,5,5,6,66,78,324,7,4,2,]
PJT = map (lambda b:print (b), ret) print (

pjt,type (PJT))
Print (list ( PJT))

Output, similar to the result of filter, can be realized by oneself

<map object at 0x0000000000d29eb8> <class ' map ' >
1
2
4
5
5
6
$
78
324
7
4
2
[None, none, no, none, none, none, none, none, none, none, none, none]
ID (): Gets the memory address of the expression
ret = [1,2,4,5,5,6,66,78,324,7,4,2,]
reg = ID (ret)
print (REG)
D:\python\python.exe d:/python/project-13/tmp/. py
11665992
isinstance (): Determines whether a class is an object, returns True & Flase
Age =
Print (isinstance (age,str))
print (Isinstance (age,int))
Len (): Return character length

PS: Note that the character length, not byte length, a letter, a Chinese character is divided into a character

#int整数类, there is no Len method, so it cannot be invoked and can only be created with the Str class age
= '
name ' = ' james '
fav = ' MVP '
dig = [31,11,12]
print (Len ( Age), Len (name), Len (Fav), Len (Dig))
D:\python\python.exe d:/python/project-13/tmp/. PY
2 3 3 3
Global () returns the globally variable of the current code environment, locals () returns the local variable of the current code environment, and returns the dictionary type
name = ' James '

def newinfo ():
    fav = ' total champion ' age
    =
    print (' 15-16 season, League strongest ')
    print (Globals ())
    Print (Locals ())

Newinfo ()
15-16 season, the league's strongest
{' newinfo ': <function newinfo at 0x0000000000d4aea0>, ' __loader__ ': <_frozen_importlib_ External. Sourcefileloader object at 0x00000000009c7860>, ' __spec__ ': None, ' name ': ' James ', ' __file__ ': ' d:/python/project-13/ tmp/. Py ', ' __package__ ': None, ' __name__ ': ' __main__ ', ' __builtins__ ': <module ' builtins ' (built-in), ' __ Cached__ ': None, ' __doc__ ': none}
{' fav ': ' Championship ', ' Age ': 31}
Max () min () sum (): Take the maximum, minimum, sum
ret = [1,2,4,5,5,6,66,78,324,7,4,2,]
print (max (ret), MIN (ret), SUM (ret))
D:\python\python.exe d:/python/project-13/tmp/. py
324 1 504
Pow (x,y,z): two parameters representing the Y-second side of X, three parameters representing X**y%z, in the remainder
reg = POW (2,10)
ret = POW (2,10,10)
print (Reg,ret)
D:\python\python.exe d:/python/project-13/tmp/. PY
1024 4
Zip (): Accept multiple data types of the same type, then ' column ' to ' Row ', return a tuple tuple
A = [23,12,32,34]
b = [23,43,127,]
c = [654,2,]
reg = Zip (a,b,c)
print (Reg,type (reg))
print ( List (reg))

It is not difficult to see from the output that, whichever is the shortest sequence, only a tuple element that matches the shortest number of sequences

D:\python\python.exe d:/python/project-13/tmp/built-in. PY
<zip object at 0x0000000000d230c8> <class ' zip ' >
[(23, 23, 654), (12, 43, 2)]
Finally, let's introduce the difference between 3.5 and 2.7.
# python3.5  can be traversed by character, or by byte for
I In "James":
    print (i)
a = "James"
print (A[:3], A[3:6], A[6:9])

# python2.7 #只能按照字节
a = "James"
print A[:3], a[3:6], A[6:9]
D:\python\python.exe d:/python/project-13/tmp/inside the building.
py
James Jim
  

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.