第六篇:python基础_6 内置函数与常用模块(一)

本篇内容

  1. 内置函数
  2. 匿名函数
  3. re模块
  4. time模块
  5. random模块
  6. os模块
  7. sys模块
  8. json与pickle模块
  9. shelve模块

一、 内置函数

1.定义

内置函数又被称为工厂函数。

2.常用的内置函数

(1)abs()

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

print(abs(-1))

(2)all()

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

print(all([1,2,‘a‘,None]))
print(all([]))

(3)any()

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

print(any([]))
print(any([‘ ‘,None,False]))
print(any([‘‘,None,False]))
print(any([‘‘,None,False,1]))

(4)bin(),oct(),hex()

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

print(bin(10))
print(oct(10))
print(hex(10))

(5)bytes()

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

#unicode----encode----->bytes
print(‘hello‘.encode(‘utf-8‘))
print(bytes(‘hello‘,encoding=‘utf-8‘))

(6)callable()

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

print(callable(bytes))
print(callable(abs))

(7)chr(),ord()

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

print(chr(65))
print(chr(90))
print(ord(‘#‘))

(8)int()

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

x=1
print(type(x))
x=int(2)
print(type(x))

complex()、float()、str()、list()、tuple()、dict()与int()同理

(9)set(),可变集合

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

s={1,2,3,4}
print(type(s))

(10)frozenset(),不可变集合

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

s1=frozenset({1,2,3,4})
print(type(s1))

(11)dir()

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

import sys
#sys.path
# sys.argv
print(dir(sys))

(12)divmod()

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

print(divmod(10,3))
print(divmod(102,20))

(13)enumerate()

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

l=[‘a‘,‘b‘,‘c‘]
res=enumerate(l)
for i in res:
    print(i)
for index,item in enumerate(l):
    print(index,item)

(14)globals(),locals(),查看全局作用域和局部作用域

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

print(globals())

(15)hash()

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

print(hash(‘abcdefg123‘))
print(hash(‘abcdefg123‘))

(16)help()

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

def func():
    ‘‘‘
    test function
    :return:
    ‘‘‘
    pass

print(help(func))

(17)id(),是python解释器实现的功能,只是反映了变量在内存的地址,但并不是真实的内存地址

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

x=1
print(id(x))
def func():
    pass
print(id(func))
print(func)

(18)isinstance()

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

x=1
print(type(x) is int)
print(isinstance(x,int))

(19)max(),min()

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

print(max([1,2,3,10]))
print(max([‘a‘,‘b‘]))
print(min([1,2,3,10]))

(20)pow()

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

print(pow(3,2,2)) #3**2%2

(21)repr(),str()

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

print(type(str(1)))
print(type(repr(1)))

(22)reversed()

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

l=[1,‘a‘,2,‘c‘]
print(list(reversed(l)))
print(l)

(23)slice()

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

l=[1,2,3,4,5,6]
print(l[0:4:2])

s=slice(0,4,2)
print(l[s])

(24)sorted()

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

l=[1,10,4,3,-1]
print(sorted(l,reverse=True))

(25)sum()

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

print(sum([1, 2,3]))
print(sum(i for i in range(10)))

(26)vars()

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

import m1
print(vars(m1) == m1.__dict__)

(27)zip()

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

s=‘helloss‘
l=[1,2,3,4,5]
print(list(zip(s,l)))

(28)__import__()

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

import sys

m_name=input(‘module>>: ‘)
if m_name == ‘sys‘:
    m=__import__(m_name)
    print(m)
    print(m.path)

sys=__import__(‘sys‘)
print(sys)

(29)round()

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

print(round(3.565,2))
print(round(3.555,2))

二、 匿名函数

1.定义

匿名函数:

(1)没有名字。

(2)函数体自带return。

匿名函数的应用场景:
应用于一次性的场景,临时使用。

2.使用

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

def func(x,y,z=1):
    return x+y+z

print(func)
print(func(1,2,3))

print(lambda x,y,z=1:x+y+z)
f=lambda x,y,z=1:x+y+z
print(f)
print(f(1,2,3))

三、 re模块

(1)

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

import re

print(re.findall(‘\w‘,‘hello_ | yanglei 123‘))
print(re.findall(‘\W‘,‘hello_ | yanglei 123‘))
print(re.findall(‘\s‘,‘hello_ | yanglei 123 \n \t‘))
print(re.findall(‘\S‘,‘hello_ | yanglei 123 \n \t‘))
print(re.findall(‘\d‘,‘hello_ | yanglei 123 \n \t‘))
print(re.findall(‘\D‘,‘hello_ | yanglei 123 \n \t‘))
print(re.findall(‘h‘,‘hello_ | hello h yanglei 123 \n \t‘))
print(re.findall(‘\Ahe‘,‘hello_ | hello h yanglei 123 \n \t‘))
print(re.findall(‘^he‘,‘hello_ | hello h yanglei 123 \n \t‘))
print(re.findall(‘123\Z‘,‘hello_ | hello h yanglei 123 \n \t123‘))
print(re.findall(‘123$‘,‘hello_ | hello h yanglei 123 \n \t123‘))
print(re.findall(‘\n‘,‘hello_ | hello h yanglei 123 \n \t123‘))
print(re.findall(‘\t‘,‘hello_ | hello h yanglei 123 \n \t123‘))

(2). [] [^]

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

import re

#.本身代表任意一个字符
print(re.findall(‘a.c‘,‘a a1c a*c a2c abc a c aaaaaac aacc‘))

#[]内部可以有多个字符,但是本身只配多个字符中的一个
print(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)\:转义

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

import re

print(re.findall(r‘a\\c‘,‘a\c abc‘))

(4)? * + {}:左边有几个字符,如果有的话,贪婪匹配

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

import re

#?左边那一个字符有0个或者1个
print(re.findall(‘ab?‘,‘aab a ab aaaa‘))

#*左边那一个字符有0个或者无穷个
print(re.findall(‘ab*‘,‘a ab abb abbb abbbb bbbbbb‘))
print(re.findall(‘ab{0,}‘,‘a ab abb abbb abbbb bbbbbb‘))

#+左边那一个字符有1个或者无穷个
print(re.findall(‘ab+‘,‘a ab abb abbb abbbb bbbbbb‘))
print(re.findall(‘ab{1,}‘,‘a ab abb abbb abbbb bbbbbb‘))

#{n,m}左边的字符有n-m次
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: YangLei

import re

#.*贪婪匹配
print(re.findall(‘a.*c‘,‘a123c456c‘))

#.*?非贪婪匹配
print(re.findall(‘a.*?c‘,‘a123c456c‘))

(6)|

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

import re

print(re.findall(‘company|companies‘,‘Too many companies have gone bankrupt, and the next one is my company‘))
print(re.findall(‘compan|companies‘,‘Too many companies have gone bankrupt, and the next one is my company‘))

(7)():分组

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

import re

print(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 have gone bankrupt, and the next one is my company‘))
print(re.findall(‘compan(?:y|ies)‘,‘Too many companies have gone bankrupt, and the next one is my company‘))

(8)re的其他方法

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

import re

print(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‘))

四、time模块

模块方法

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

import time

print(time.time())
print(time.strftime(‘%Y-%m-%d %X‘))

print(time.localtime())
print(time.gmtime()) #UTC
print(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()))

五、random模块

1.模块方法

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

import random
print(random.sample([1,‘23‘,[4,5]],2))

print(random.uniform(1,3))

item=[1,3,5,7,9]
random.shuffle(item)
print(item)

2. 生成秘钥应用

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

import random
def 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 res
print(make_code(10))

六、os模块

模块方法

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

import os

print(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)

七、sys模块

模拟进度条应用

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

import sys,time

def progress(percent,width=50): #51
    if percent >= 100:
        # 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=1025121
recv_size=0

while recv_size < total_size:
    time.sleep(0.01) #模拟下载的网络延迟
    recv_size+=1024
    recv_per=int(100*recv_size/total_size)
    progress(recv_per,width=10)

八、json与pickle模块

(1)json

应用平台广泛

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

import json
dic={‘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

只对python有效

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

import pickle

dic={‘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(open(‘e.pkl‘,‘rb‘))[‘name‘])

def func():
    print(‘from func‘)

import json
print(json.dumps(func))

import pickle
print(pickle.dumps(func))
pickle.dump(func,open(‘func.pkl‘,‘wb‘))

九、shelve模块

模块方法

#!/usr/binl/env python
#encoding: utf-8
#author: YangLei

import shelve

f=shelve.open(r‘sheve.shl‘)

f[‘yanglei‘]={‘age‘:23,‘pwd‘:‘123456‘}
f[‘xiaolan‘]={‘age‘:18,‘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])
时间: 2024-10-27 12:32:08

第六篇:python基础_6 内置函数与常用模块(一)的相关文章

Python基础day-11[内置函数(未完),递归,匿名函数]

内置函数: abs() : 返回数字的绝对值.参数可以是整数或浮点数,如果参数是复数,则返回复数的模. print(abs(0.2)) print(abs(1)) print(abs(-4)) print(abs(-0.2)) print(abs(3+4j)) 执行结果: D:\Python\Python36-32\python.exe E:/Python/DAY-11/tmp.py 0.2 1 4 0.2 5.0 Process finished with exit code 0 all():

python基础知识内置函数(二)、装饰器

一.内置函数 1.chr()  ord() r= chr(65) #ASCII对应的字母 print (r) n= ord("a") #ASCII对应的数字 print(n) #以下为执行结果 A 97 可以利用此函数随机生成验证码: import random li=[] for i in range(6): r = random.randrange(0,5) if r ==2 or r==4: num = random.randrange(0,10) li.append(str(n

python 基础 学习 内置函数

内置函数       例:如果返回数字的绝对值 ,写函数是非常不方便的 [[email protected] tools]# python fa.py  10 [[email protected] tools]# cat fa.py  #!/usr/bin/python def a(x):     if x < 0 :         return -x      return x  n = a(-10) print n  #帮助查看# >>> help(len) 用法: help

Python 基础5:内置函数一

===========内置函数=========== 1.abs绝对值 #abs() i = abs(-123) print(i) #结果:123 2.all与any #all 循环参数,如果每个元素都为真,那么all的返回值为真 #any,只要有一个是真的,则为真 r = all([True,True,False]) print(r) #结果:False #元素为假的有:0,None,空的字符串.列表.元组.字典 3.ascii,对象的类中找__repr__,获取齐返回值 # class Fo

python基础学习-内置函数

#!/usr/bin/env python # -*- coding:utf-8 -*- 系统内置函数 n =abs(-1) #绝对值 print(n) #bytes()函数 s="离开" re= bytes(s,encoding="utf-8")  # bytes() 把字符串 转换成字节 print(re) res = str(re,encoding="utf-8") #转换回字符串 print(res) re= bytes(s,encodi

Python基础编程 内置函数

内置函数 内置函数(一定记住并且精通) print()屏幕输出 int():pass str():pass bool():pass set(): pass list() 将一个可迭代对象转换成列表 tuple() 将一个可迭代对象转换成元组 dict() 通过相应的方式创建字典. # 创建字典的几种方式 #直接创建 dic = {1: 2} #字典推导式 print({i: 1 for i in range(3)}) dict() #dict创建 dic = dict(one=1, two=2,

学习PYTHON之路, DAY 4 - PYTHON 基础 4 (内置函数)

注:查看详细请看https://docs.python.org/3/library/functions.html#next 一 all(), any() False: 0, Noe, '', [], {}, () all()  全部为真是, 才为真 any() 任何一个为真, 都为真 二 bin(), oct(),hex() bin(), 接收十进制转二进制 (0b) oct(), 接收十进制转八进制 (0o) hex(), 接收十进制转十六进制 (0x) 三 bytes() bytes(只要转

python基础:内置函数zip,map,filter

一.zip zip,就是把俩list,合并到一起,如果想同时循环2个list的时候,可以用zip,会帮你轮流循环两个list 比如: l1=[1,2,3,4,5] l2=['a','b','c','d','e'] for a,b in zip(l1,l2): print(a,b) #得到的结果就是1 a2 b3 c4 d5 e 如果两个list的长度不一致,则以长度小的为依据 比如: l1=[1,2,3,4] l2=['a','b','c','d','e'] for a,b in zip(l1,

python协程函数、递归、匿名函数与内置函数使用、模块与包

目录: 协程函数(yield生成器用法二) 面向过程编程 递归 匿名函数与内置函数的使用 模块 包 常用标准模块之re(正则表达式) 一.协程函数(yield生成器用法二) 1.生成器的语句形式 a.生成器相关python函数.装饰器.迭代器.生成器,我们是如何使用生成器的.一个生成器能暂停执行并返回一个中间的结果这就是 yield 语句的功能 : 返回一个中间值给调用者并暂停执行. 我们的调用方式为yeild 1的方式,此方式又称为生成器的语句形式. 而使用生成器的场景:使用生成器最好的场景就