Sixth: Python Foundation _6 built-in functions and common modules (i)

Source: Internet
Author: User
Tags chr ord vars

The content of this article
    1. Built-in functions
    2. anonymous functions
    3. Re module
    4. Time Module
    5. Random module
    6. OS Module
    7. SYS module
    8. JSON and Pickle modules
    9. Shelve module

First, built-in functions

1. Definition

Built-in functions are also known as factory functions.

2. Common built-in functions

(1) ABS ()

#!/usr/binl/env Python#encoding:utf-8#author:yangleiprint (ABS (-1))

(2) All ()

#!/usr/binl/env Python#encoding:utf-8#author:yangleiprint (All ([Up, ' a ', None])) print (All ([]))

(3) any ()

#!/usr/binl/env Python#encoding:utf-8#author:yangleiprint (Any ([])) print (Any ([', ', None,false]) , False])) print (Any ([', none,false,1]))

(4) Bin (), Oct (), Hex ()

#!/usr/binl/env python#encoding:utf-8#author:yangleiprint (Bin) print (Oct) print (Hex (10))

(5) bytes ()

#!/usr/binl/env python#encoding:utf-8#author:yanglei#unicode----Encode----->bytesprint (' Hello '. Encode (' Utf-8 ') print (bytes (' Hello ', encoding= ' utf-8 '))

(6) Callable ()

#!/usr/binl/env python#encoding:utf-8#author:yangleiprint (callable (bytes)) Print (callable (ABS))

(7) Chr (), Ord ()

#!/usr/binl/env python#encoding:utf-8#author:yangleiprint (CHR) print (CHR) print (Ord (' # '))

(8) Int ()

#!/usr/binl/env Python#encoding:utf-8#author:yangleix=1print (Type (x)) X=int (2) print (type (x))

Complex (), float (), str (), list (), tuple (), dict () and int ()

(9) Set (), variable set

#!/usr/binl/env Python#encoding:utf-8#author:yangleis={1,2,3,4}print (type (s))

(Ten) Frozenset (), immutable collection

#!/usr/binl/env python#encoding:utf-8#author:yangleis1=frozenset ({1,2,3,4}) print (Type (S1))

(one) dir ()

#!/usr/binl/env python#encoding:utf-8#author:yangleiimport sys#sys.path# sys.argvprint (dir (SYS))

(Divmod) ()

#!/usr/binl/env Python#encoding:utf-8#author:yangleiprint (Divmod (10,3)) print (Divmod (102,20))

(+) Enumerate ()

#!/usr/binl/env python#encoding:utf-8#author:yangleil=[' A ', ' B ', ' C ']res=enumerate (L) for I in Res:    print (i) for Index,item in Enumerate (l):    print (Index,item)

(+) Globals (), locals (), view global scope and local scope

#!/usr/binl/env Python#encoding:utf-8#author:yangleiprint (Globals ())

() hash ()

#!/usr/binl/env Python#encoding:utf-8#author:yangleiprint (hash (' abcdefg123 ')) print (hash (' abcdefg123 '))

(+) Help ()

#!/usr/binl/env python#encoding:utf-8#author:yangleidef func ():    '    test function    : return:    ' '    Passprint (Help (func))

() ID (), which is a function implemented by the Python interpreter, only reflects the variable's address in memory, but not the actual memory address

#!/usr/binl/env Python#encoding:utf-8#author:yangleix=1print (ID (x)) def func ():    passprint (ID (func)) Print (func )

() Isinstance ()

#!/usr/binl/env Python#encoding:utf-8#author:yangleix=1print (Type (x) is int) print (isinstance (x,int))

Max (), Min ()

#!/usr/binl/env Python#encoding:utf-8#author:yangleiprint (Max ([1,2,3,10])) print (max ([' A ', ' B ']) print (min ([ 1,2,3,10]))

() Pow ()

#!/usr/binl/env python#encoding:utf-8#author:yangleiprint (POW (3,2,2)) #3 **2%2

(+) repr (), str ()

#!/usr/binl/env python#encoding:utf-8#author:yangleiprint (Type (str (1))) print (Type (repr (1)))

(a) reversed ()

#!/usr/binl/env python#encoding:utf-8#author:yangleil=[1, ' A ', 2, ' C ']print (list (Reversed (l))) print (L)

(at) Slice ()

#!/usr/binl/env Python#encoding:utf-8#author:yangleil=[1,2,3,4,5,6]print (L[0:4:2]) s=slice (0,4,2) print (L[s])

(sorted) ()

#!/usr/binl/env Python#encoding:utf-8#author:yangleil=[1,10,4,3,-1]print (sorted (l,reverse=true))

SUM ()

#!/usr/binl/env python#encoding:utf-8#author:yangleiprint (sum ([1, 2,3]) print (SUM (i-I in range (10)))

(+) VARs ()

#!/usr/binl/env python#encoding:utf-8#author:yangleiimport M1print (VARs (m1) = = m1.__dict__)

(+) Zip ()

#!/usr/binl/env python#encoding:utf-8#author:yangleis= ' Helloss ' l=[1,2,3,4,5]print (list (Zip (s,l)))

(+) __import__ ()

#!/usr/binl/env python#encoding:utf-8#author:yangleiimport sysm_name=input (' module>>: ') if m_name = = ' sys ':    m=__import__ (m_name) print (    m)    print (M.path) sys=__import__ (' sys ') print (SYS)

() round ()

#!/usr/binl/env Python#encoding:utf-8#author:yangleiprint (Round (3.565,2)) print (round (3.555,2))

Second, anonymous function

1. Definition

Anonymous functions:

(1) No name.

(2) The function body comes with return.

Application Scenarios for anonymous functions:
Apply to a one-time scenario for temporary use.

1. Role

#!/usr/binl/env python#encoding:utf-8#author:yangleidef func (x,y,z=1):    return X+y+zprint (func) Print (func ( ) print (lambda x,y,z=1:x+y+z) F=lambda x,y,z=1:x+y+zprint (f) Print (f ()

Third, re module

(1)

#!/usr/binl/env Python#encoding:utf-8#author:yangleiimport Reprint (Re.findall (' \w ', ' hello_ | yanglei 123 ') print ( Re.findall (' \w ', ' hello_ | yanglei 123 ')) Print (Re.findall (' \s ', ' hello_ | yanglei 123 \ t ')) print (Re.findall (' \s ', ' Hello_ | Yanglei 123 \ t ') print (Re.findall (' \d ', ' hello_ | yanglei 123 \ t ')) print (Re.findall (' \d ', ' hello_ | yanglei 123 \ t ') ) Print (Re.findall (' h ', ' hello_ | Hello h yanglei 123 \ t ')) print (Re.findall (' \ahe ', ' hello_ | Hello h yanglei 123 \ n \ t ') Print (Re.findall (' ^he ', ' hello_ | Hello h yanglei 123 \ t ')) print (Re.findall (' 123\z ', ' hello_ | Hello h yanglei 123 \ T  123 ') Print (Re.findall (' 123$ ', ' hello_ | Hello h yanglei 123 \ n \t123 ')) print (Re.findall (' \ n ', ' hello_ | Hello h yanglei 123 \ \t123 ') Print (Re.findall (' \ t ', ' hello_ | Hello h yanglei 123 \ n \t123 '))

(2). [] [^]

#!/usr/binl/env Python#encoding:utf-8#author:yangleiimport re#, which itself represents any one character print (Re.findall (' a.c ', ' a A1C a*c a2c ABC a C AAAAAAC AACC ')) #[] can have multiple characters inside, but only one print of multiple characters (Re.findall (' a[0-9][0-9]c ', ' a a12c A1c a*c a2c a C a\nc ', re. S)) Print (Re.findall (' a[a-za-z]c ', ' AAC ABC AAC a12c A1C a*c a2c a C a\nc ', re. S)) Print (Re.findall (' a[^a-za-z]c ', ' AAC ABC AAC a12c A1C a*c a2c a C a\nc ', re. S)) Print (Re.findall (' a[\+\/\*\-]c ', ' a-c a+c A/C AAC ABC AAC a12c A1C a*c a2c a C a\nc ', re. S))

(3) \: Escaped

#!/usr/binl/env Python#encoding:utf-8#author:yangleiimport Reprint (Re.findall (R ' a\\c ', ' a\c abc '))

(4)? * + {}: There are several characters on the left, if any, greedy match

#!/usr/binl/env python#encoding:utf-8#author:yangleiimport re#? The character on the left has 0 or 1 print (Re.findall (' ab ', ' AaB a ab aaaa ') ) #* left that character has 0 or infinitely print (Re.findall (' ab* ', ' a ab ABB abbb abbbb bbbbbb ') print (Re.findall (' ab{0,} ', ' A ab ABB abbb ABBBB BBBBBB ') #+ the left one character has 1 or infinitely print (Re.findall (' ab+ ', ' a ab ABB abbb abbbb bbbbbb ')) print (Re.findall (' Ab{1,} ', ' a ab ABB ABBB abbbb bbbbbb ') #{n,m} The character on the left has n-m times print (Re.findall (' ab{3} ', ' A ab ABB abbb abbbb bbbbbb ') print (Re.findall (' ab{2,3} ') , ' A ab ABB abbb abbbb bbbbbb '))

(5). *. *?

#!/usr/binl/env python#encoding:utf-8#author:yangleiimport re#.* greedy match print (Re.findall (' a.*c ', ' a123c456c ')) #.*? Non-greedy match print (Re.findall (' a.*?c ', ' a123c456c '))

(6) |

#!/usr/binl/env Python#encoding:utf-8#author:yangleiimport Reprint (Re.findall (' company|companies ', ' Too many Companies has gone bankrupt, and the next one is my company ') print (Re.findall (' compan|companies ', ' Too many companies hav e gone bankrupt, and the next one is my company '))

(7) (): Grouping

#!/usr/binl/env Python#encoding:utf-8#author:yangleiimport Reprint (Re.findall (' ab+ ', ' abababab123 ')) print ( Re.findall (' ab+123 ', ' abababab123 ') print (Re.findall (' ab ', ' abababab123 ')) print (Re.findall (' (AB) ', ' abababab123 ') Print (Re.findall (' (a) B ', ' abababab123 ')) print (Re.findall (' A (b) ', ' abababab123 ')) print (Re.findall (' (AB) + ', ' Abababab123 ') Print (Re.findall (' (?: AB) + ', ' abababab123 ')) print (Re.findall (' (AB) +123 ', ' abababab123 ')) print ( Re.findall (' (?: AB) +123 ', ' abababab123 ')) print (Re.findall (' (AB) + (123) ', ' abababab123 ')) print (Re.findall (' Compan ') (Y |ies) ', ' Too many companies has gone bankrupt, and the next one is my company ') print (Re.findall (' Compan (?: y|ies) ', ' Too ma NY companies has gone bankrupt, and the next one is my company '))

(8) Other methods of RE

#!/usr/binl/env Python#encoding:utf-8#author:yangleiimport Reprint (re.findall (' ab ', ' abababab123 ')) print ( Re.search (' ab ', ' abababab123 '). Group ()) Print (Re.search (' ab ', ' 12AASSSDDDSSSSSSSS3 ')) print (Re.search (' Ab ', ' 12aasssdddsssssssab3sssssss ') (group ()) Print (Re.search (' ab ', ' 123ab456 ') print (Re.match (' ab ', ' 123ab456 ')) print ( Re.split (' B ', ' ABCDE ')) print (Re.split (' [ab] ', ' ABCDE ')) print (Re.sub (' Xiaolan ', ' xiaohong ', ' Xiaolan make Love Xiaolan Xiaolan ', 1)) Print (Re.subn (' Xiaolan ', ' xiaohong ', ' Xiaolan make Love Xiaolan Xiaolan ', 1)) Print (Re.sub (' (\w+) (\w+) (\w+ (\w+) (\w+) ', R ' \5\2\3\4\1 ', ' Toms Make Love ') print (Re.sub (' (\w+) (. *) (\w+) ', R ' \3\2\1 ', ' Toms Make Love ')) obj= Re.compile (' \d{2} ') Print (Obj.search (' abc123eeee '). Group ()) Print (Obj.findall (' abc123eeee '))

Four, Time module

Module method

#!/usr/binl/env python#encoding:utf-8#author:yangleiimport Timeprint (Time.time ()) Print (Time.strftime ('%Y-%m-%d%x ') print (Time.localtime ()) print (Time.gmtime ()) #UTCprint (Time.localtime () tm_mon) print (Time.localtime (123123123 ) Print (Time.gmtime (123123123)) print (Time.mktime (Time.localtime ())) Print (Time.strftime ('%Y ', Time.gmtime ())) ' 2017-03-01 ' Print (time.strptime (' 2017-03-01 ', '%y-%m-%d ')) print (Time.ctime (12312312)) Print (Time.asctime ( Time.gmtime ()))

V. Random module

1. Module method

#!/usr/binl/env python#encoding:utf-8#author:yangleiimport Randomprint (Random.sample ([1, '% ', [4,5]],2)] Print ( Random.uniform (1,3)) Item=[1,3,5,7,9]random.shuffle (item) print (item)

2. Generate key Application

#!/usr/binl/env python#encoding:utf-8#author:yangleiimport randomdef make_code (n):    res= "for    I in range (n):        s1=str (Random.randint (0,9))        s2=chr (Random.randint (65,90))        res+=random.choice ([s1,s2])    return Resprint (Make_code (10))

VI. OS Module

Module method

#!/usr/binl/env python#encoding:utf-8#author:yangleiimport osprint (Os.listdir ('. ')) Print (Os.stat (' m1.py '). St_size) print (os.sep) print (os.linesep) print (OS.PATHSEP) print ([Os.sep,os.linesep, OS.PATHSEP]) Res=os.system (' dir. ') Print (' ====?> ', res) print (Os.path.dirname (R ' C:\a\b\c\d\a.txt ')) print (Os.path.basename (R ' C:\a\b\c\d\a.txt ')) Print (Os.path.split (R ' C:\a\b\c\d\a.txt ')) print (Os.stat (' m1.py '). St_atime) Print (Os.stat (' m1.py '). St_size) Print ( Os.path.getsize (' m1.py ')) print (Os.path.join (' c:\\ ', ' A ', ' B ', ' C ', ' D.txt ')) print (Os.path.join (' c:\\ ', ' A ', ' B ', ' D:\ \ ', ' C ', ' D.txt ') print (os.path.normcase (' c:/windows\\system32\\ '))  print (Os.path.normpath (' c://windows\\ system32\\. /temp/')  a= '/users/jieli/test1/\\\a1/\\\\aa.py/. /..‘ Print (Os.path.normpath (a)) print (Os.path.dirname (Os.path.dirname (Os.path.abspath (__file__))) base_dir= Os.path.normpath (Os.path.join (    os.path.abspath (__file__), '.. ', '..    ')) Print (Base_dir)

Seven, sys module

Simulation Progress bar Application

#!/usr/binl/env Python#encoding:utf-8#author:yangleiimport sys,timedef Progress (percent,width=50): #51    if Percent >=:        # print (' \r[%s] 100%% '% (width* ' # '))        percent=100    show_str= (' [%%-%ds] '%width)% (int ( width*percent/100) * ' # ')    print (' \r%s%d%% '% (show_str,percent), file=sys.stdout,flush=true,end= ') #total_size = 1025121recv_size=0while Recv_size < total_size:    time.sleep (0.01) #模拟下载的网络延迟    recv_size+=1024    recv_ Per=int (100*recv_size/total_size)    Progress (recv_per,width=10)

viii. JSON and pickle modules

(1) JSON

Wide Application Platform

#!/usr/binl/env python#encoding:utf-8#author:yangleiimport jsondic={' name ': ' Yanglei ', ' Age ': 23}print (Type ( Json.dumps (DIC))) with open (' A.json ', ' W ') as F:    F.write (Json.dumps (DIC)) with open (' A.json ', ' R ') as F:    data= F.read ()    dic=json.loads (data)    print (dic[' name ') dic={' name ': ' Yanglei ', ' Age ': 23}json.dump (' Dic,open (' B.json ', ' W ')) Print (Json.load (open (' B.json ', ' r ')) [' name ']) with open (' C.json ', ' R ') as F:    Data=f.read ()    #[ null,true,false,1]    eval (data)

(2) Pickle

Valid only for Python

#!/usr/binl/env python#encoding:utf-8#author:yangleiimport pickledic={' name ': ' Yanglei ', ' Age ': 23}print ( Pickle.dumps (DIC)) with open (' D.pkl ', ' WB ') as F:    F.write (Pickle.dumps (DIC)) with open (' d.pkl ', ' RB ') as F:    dic= Pickle.loads (F.read ())    print (dic[' name ') dic={' name ': ' Yanglei ', ' Age ': 23}pickle.dump (Dic,open (' e.pkl ', ' WB ') ) Print (Pickle.load (' e.pkl ', ' RB ')) [' Name ']) def func ():    print (' from Func ') Import Jsonprint (Json.dumps (func )) Import Pickleprint (Pickle.dumps (func)) Pickle.dump (Func,open (' func.pkl ', ' WB ')

Nine, shelve module

Module method

#!/usr/binl/env python#encoding:utf-8#author:yangleiimport Shelvef=shelve.open (R ' sheve.shl ') f[' Yanglei ']={' age ' : ' pwd ': ' 123456 '}f[' Xiaolan ']={' age ': ' pwd ': ' 123456 '}f.close () Obj=shelve.open (R ' SHEVE.SHL ') print (obj[') Yanglei ']) print (obj[' Xiaolan ') obj.close () for i in obj:    print (I,obj[i])

Sixth: Python Foundation _6 built-in functions and common modules (i)

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.