第六章:Python匿名函数与内置函数+常用模块

导航: 

   匿名函数

     内置函数

   常用模块

一、匿名函数

在python中有一个匿名函数lambda,匿名函数顾名思义就是指:是指一类无需定义标识符(函数名)的函数或子程序。最早引入匿名函数的是LISP语言,LISP是最早的函数编程式语言,我们使用的Vim的插件大部分都是使用LISP语言进行编写的,后来又派生出Emacs Lisp,Emacs的扩展插件就是使用Lisp编写的。在C++11和C#中都有匿名函数的存在。下面看看在python中匿名函数的使用。

#使用def定义的函数:
def func(x,y,z=1):
    return x+y+z
print(func)
print(func(1,2,3))

匿名函数特点:

  1. 没有名字

  2. 函数体自带return

# print(lambda x,y,z=1:x+y+z)

f=lambda x,y,z=1:x+y+z  #lambda匿名函数关键字
print(f)
print(f(1,2,3))  #参数1,2,3分别给x,y,z传参
# x=1
# 1
# print(x)
# print(1) 

匿名函数的应用场景:

  应用于一次性的场景,临时使用 

二、 内置函数

常用内置函数
#abs绝对值

>>> print(abs(-22))
22

#all所有的可迭代对象的值都是True则为True

#all可迭代对象为空则为True

>>> print(all([1,2,3]))
True
>>> print(all([]))
True

#bool值为假的情况:None、空、0、False
#迭代器you任意一个bool值为Ture为真

>>> print(any([None]))
False
>>> print(any([]))
False
>>> print(any([1,2,False]))
True

#bin、oct、hex  ,进制转换

>>> print(bin(10))
0b1010
>>> print(oct(10))
0o12
>>> print(hex(10))
0xa

# bytes
#unicode---enconde---bytes

>>> print('hello'.encode('utf-8'))
b'hello'
>>> print(bytes('hello',encoding='utf-8'))
b'hello'

#callable

>>> print(callable(bytes))
True
>>> print(callable(abs))
True

#chr、ord

>>> print(chr(65))
A
>>> print(chr(90))
Z
>>> print(ord('B'))
66
>>> print(ord('#'))
35
View Code

#complie、ea
#int
# str
# tuple
# complex
# float
# dict
# set #可变集合
# frozenset  #可变集合

#dir

import sys
sys.path
sys.argv
print(dir(sys)) #dir是pytharm 提供的查看sys可以调用那些属性的方法

#divmod  #取出商和余数
#应用在前端页面展示

>>> print(divmod(10,2))
(5, 0)

# enumerate  #循环列表的同时得到索引和数据

l=[1,2,3,4]
for i,tems in enumerate(l):
    print(i,tems)

#format

print(10,'b')

# globals、locals  #查看全局和局部作用于变量使用

#hash  #哈希出一个值

>>> print(hash('13dsfas'))
-125995431276603917
>>> print(hash('13dsfas'))
-125995431276603917

#help # 查看帮助信息

def func():
    '''
    ShengLeQi
    '''
    pass
print(help(func))

#id,访问到对象的id号(id号反映内存地址)

>>> a=1
>>> print(id(a))
1628152928

# isinstance  #判断是否是一个类型的实例

x=1
print(type(x))
print(isinstance(x,int)) #判断x是否是int的一个实例
b='fasdf'
print(isinstance(b,str))

#len、#max

l=[1,2,4,34]
print(len(l))
print(max(l))

其他常用的内置函数

#pow
>>> print(pow(3,2,2))  #3**2/2
1

#range

#rapr:把对象转化成字符串,str
>>> a=int(23)
>>> print(type(str(a)))
<class 'str'>
>>> print(type(repr(a)))
<class 'str'>

# reversed
>>> l=[1,2,'a','b','c']
>>> print(list(reversed(l)))
['c', 'b', 'a', 2, 1]
>>> print(l)
[1, 2, 'a', 'b', 'c']

# round()  给数字保留小数的位数
>>> print(round(12.2323,2))
12.23

# slice  利用函数的形式切片一次定义多次使用
>>> l=[0,1,2,3,4,5,6]
>>> print(l[0:6:2])
[0, 2, 4]
>>> s=slice(0,6,2)
>>> print(l[s])
[0, 2, 4]

# sorted()  #排序
l=[1,23,4,5,78,-2]
l=sorted(l)  #从小到大
>>> print(l)
[-2, 1, 4, 5, 23, 78]
>>> print(sorted(l,reverse=True))  #从大到小
[78, 23, 5, 4, 1, -2]

#sum
>>> print(sum([1,2,3,3]))
9

#vars #Without arguments, equivalent to locals(
import  os
vars()
#pow、rapr、reversed、round、slice

#zip:拉链

>>> a='hello'
>>> b=[1,2,3,4,5]
>>>
>>> print(list(zip(a,b))) #a中的值和b中的值组成一个小元祖
[('h', 1), ('e', 2), ('l', 3), ('l', 4), ('o', 5)]

实例应用:

salarys={
    'egg':213,
    'alex':23,
    'lele':12222,
    'qiqi':233
}  #取出salarys的最大值的名字。
# print(salarys.keys())
# print(salarys.values())
res=zip(salarys.values(),salarys.keys())
print(max(zip(salarys.values(),salarys.keys())))
zip函数的应用

#filet、map、reduce(重点)

三、 常用模块

1、time模块 

在Python中,通常有这几种方式来表示时间:

  • 时间戳(timestamp):通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型。
  • 格式化的时间字符串(Format String)
  • 结构化的时间(struct_time):struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一年中第几周,一年中第几天,夏令时
import time
#--------------------------我们先以当前时间为准,让大家快速认识三种形式的时间
print(time.time()) # 时间戳:1487130156.419527
print(time.strftime("%Y-%m-%d %X")) #格式化的时间字符串:'2017-02-15 11:40:53'

print(time.localtime()) #本地时区的struct_time
print(time.gmtime())    #UTC时区的struct_time

时间函数的应用:

import time

# print(time.time()) #查看时间戳,
# 1502096796.0680387
print(time.strftime('%Y-%m-%d %X')) #格式化的时间字符串
#2017-08-07 17:06:49
print(time.localtime())  #本地时区的struct_time
print(time.gmtime())   #UTC时区的struct_time
print(time.localtime().tm_mon)  ##本地时区的的月份
#
#
print(time.localtime(123123123)) #查看时间戳对应的local时间
print(time.gmtime(123123123)) #查看时间戳UTC的local时间
#
print(time.mktime(time.localtime()))  #把本地时区的struct_time变成时间戳

print(time.strftime('%Y',time.gmtime()))  #
#
# '2017-03-01'
print(time.strptime('2017-03-01','%Y-%m-%d')) # 把一个格式化时间字符串转化为struct_time。实际上它和strftime()是逆操作。
#

print(time.ctime(12312312))  #穿件时间
print(time.asctime(time.gmtime()))  #
View Code

 

2、random模块

import random
print(random.random())  #---float  大于0小于1的小数
# 0.9149702969643526
print(random.randint(1,6))  #---int 大于等于1小于等于6的整数
print(random.randrange(1,6))  #---int 大于等于1小于6的整数
print(random.choice([2,3,4,5,[88,89]]))  #---2,3,4,5,[88,89]
print(random.sample([1,'23',[4,5]],2))  #---列表[1,'23',[4,5]]内任意2个组合
# ['23', 1]
print(random.uniform(1,3))  #--大于1小于3的小数
# 2.3743227233748305

item=[1,2,3,4,5,6]
random.shuffle(item)
print(item)

随机数的应用

==》生产随机验证码的功能 10位大写字母和数字组成

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(20))
随机数的应用

 

3、os模块

os模块是与操作系统交互的一个接口

import  os
os.getcwd() #获取当前工作目录,即当前python脚本工作的目录路径
os.chdir("dirname") # 改变当前脚本工作目录;相当于shell下cd
os.curdir  #返回当前目录: ('.')
os.pardir  #获取当前目录的父目录字符串名:('..')
os.makedirs('dirname1/dirname2')    #可生成多层递归目录
os.removedirs('dirname1')    #若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir('dirname')    #生成单级目录;相当于shell中mkdir dirname
os.rmdir('dirname')    #删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
os.listdir('dirname')    #列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove() # 删除一个文件
os.rename("oldname","newname") # 重命名文件/目录
os.stat('path/filename') # 获取文件/目录信息
os.sep    #输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
os.linesep    #输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"
os.pathsep    #输出用于分割文件路径的字符串 win下为;,Linux下为:
os.name    #输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
os.system("bash command")  #运行shell命令,直接显示
os.environ  #获取系统环境变量
os.path.abspath(path)  #返回path规范化的绝对路径
os.path.split(path)  #将path分割成目录和文件名二元组返回
os.path.dirname(path)  #返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path)  #返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path)  #如果path存在,返回True;如果path不存在,返回False
os.path.isabs(path)  #如果path是绝对路径,返回True
os.path.isfile(path)  #如果path是一个存在的文件,返回True。否则返回False
os.path.isdir(path)  #如果path是一个存在的目录,则返回True。否则返回False
os.path.join(path1[, path2[, ...]])  #将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.path.getatime(path)  #返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path)  #返回path所指向的文件或者目录的最后修改时间
os.path.getsize(path) #返回path的大小

os模块中的os.path.exists()方法用于检验文件是否存在。

  • 判断文件是否存在
import os
os.path.exists(test_file.txt)
#True

os.path.exists(no_exist_file.txt)
#False
  • 判断文件夹是否存在
import os
os.path.exists(test_dir)
#True

os.path.exists(no_exist_dir)
#False

 

可以看出用os.path.exists()方法,判断文件和文件夹是一样。

其实这种方法还是有个问题,假设你想检查文件“test_data”是否存在,但是当前路径下有个叫“test_data”的文件夹,这样就可能出现误判。为了避免这样的情况,可以这样:

  • 只检查文件
    import os
    os.path.isfile("test-data")
    

通过这个方法,如果文件”test-data”不存在将返回False,反之返回True。

即是文件存在,你可能还需要判断文件是否可进行读写操作

os模块的应用:

import os
res=os.system('dir .')  #执行命令
print('==>%s' %res)  #命令执行是否成功的结果

print(os.path.dirname(r'c:\a\b\c\d\a.txt'))
# c:\a\b\c\d
print(os.path.basename(r'c:\a\b\c\d\a.txt'))
# a.txt

# 在Linux和Mac平台上,该函数会原样返回path,在windows平台上会将路径中所有字符转换为小写,并将所有斜杠转换为饭斜杠。
print(os.path.normcase('c:/windows\\system32\\'))
# 'c:\\windows\\system32\\'

# 规范化路径,如..和/
print(os.path.normpath('c://windows\\System32\\../Temp/'))
# c:\windows\Temp
a='/Users/jieli/test1/\\\a1/\\\\aa.py/../..'
print(os.path.normpath(a))
# \Users\jieli\test1

print(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# C:\Users\think\PycharmProjects\Python18
BASE_HOME=os.path.normpath(os.path.join(
    os.path.abspath(__file__),
    '..',
    '..'
)
)
print(BASE_HOME)
# C:\Users\think\PycharmProjects\Python18

 

4、sys模块

sys模块需要掌握的。 

sys.argv           #命令行参数List,第一个元素是程序本身路径
sys.exit(n)        #退出程序,正常退出时exit(0)
sys.version        #获取Python解释程序的版本信息
sys.maxint         #最大的Int值
sys.path           #返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform       #返回操作系统平台名称

sys的应用:

1、使用sys模块实现

for i in range(20):
    sys.stdout.write ('\r%s'%('#'*i))
    time.sleep(0.5)
    sys.stdout.flush()
View Code

2、使用print方式实现 

for i in range(20):
    print('\r%s' %('#'*i),file=sys.stdout,flush=True,end='')
    time.sleep(0.5)
View Code 

3、进度条

#需要知道的知识储备
print('<%-10s>' %'#')  #打印固定长度(10)
width=10
print('<%%-%ds>' %width)    #<%-12s>
print(('<%%-%ds>' %width)%('hello'))  #('<%%-%ds>' %width)  ==> <%-12s>

#模仿linux的进度条
import sys,time
def  progress(percent,width):
    if percent >=100:
        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=101342
rev_size=0
while rev_size < total_size:
    time.sleep(0.3)
    rev_size += 2048
    rev_size_per=int(rev_size/total_size*100)
    progress(rev_size_per,50)
模仿linux的进度条

 

5、shutil模块

 

6、json&pickle模块

  我们学习过用eval内置方法可以将一个字符串转成python对象,不过,eval方法是有局限性的,对于普通的数据类型,json.loads和eval都能用,但遇到特殊类型的时候,eval就不管用了,所以eval的重点还是通常用来执行一个字符串表达式,并返回表达式的值

import json
x="[null,true,false,1]"
print(eval(x)) #报错,无法解析null类型,而json就可以
print(json.loads(x)) 

1、什么是序列化?

    我们把变量从内存中变成可存储或传输的过程称之为序列化。

序列化之后,就可以把序列化后的内容写入磁盘,或者通过网络传输到别的机器上。

反过来,把变量内容从序列化的对象重新读到内存里称之为反序列化,即unpickling。

举例:

  大家应该都玩过虚拟机VMware ,应该知道该虚拟机有个一个快照的功能,我每次关机的时候就可以快照,在直接关闭计算机,当我们打开计算机重启VMware 的时候,直接启动快照就可以恢复到我们之前保存的那个状态。

---如何序列化?  

  在python中提供了两个模块可进行序列化。分别是pickle和json。

pickle

  pickle是python中独有的序列化模块,所谓独有,就是指不能和其他编程语言的序列化进行交互,因为pickle将数据对象转化为bytes

  pickle模块提供了四个功能:dumps、dump、loads、load。

  dumps和dump都是进行序列化,而loads和load则是反序列化。

import pickle
dict={'name':'sheng','age':12,'sex':'man'}
#使用dumps、loads
# with open('c.pkl','wb') as f:
#     f.write(pickle.dumps(dict))  #序列化
with open('c.pkl','rb') as f:
    dic=pickle.loads(f.read())  #反序列化
    print(dic['name'])
#使用dump、load
pickle.dump(dict,open('d.pkl','wb'))#序列化
print(pickle.load(open('d.pkl','rb'))['name'])  #反序列化
#函数序列化,内存一定要有函数的地址,才能反序列化。
# 【注意】在反解特殊的类型的时候需要内存中要用地址。

json

  如果我们要在不同的编程语言之间传递对象,就必须把对象序列化为标准格式,比如XML,但更好的方法是序列化为JSON,因为JSON表示出来就是一个字符串,可以被所有语言读取,也可以方便地存储到磁盘或者通过网络传输。JSON不仅是标准格式,并且比XML更快,而且可以直接在Web页面中读取,非常方便。

如果想要详细了解JSON的话,推荐一篇博文:http://www.cnblogs.com/mcgrady/archive/2013/06/08/3127781.html

 

import  json
dict={'name':'sheng','age':12,'sex':'man'}
print(json.dumps(dict),type(json.dumps(dict)))  #dumps就是序列化
##使用dumps、loads
with open('a.json','w') as f:
    f.write(json.dumps(dict))  #序列化
with open('a.json','r') as f:
    date=f.read()
    dic=json.loads(date)      #反序列化
    print(date,type(dic))
    print(dic['name'])
# 使用dump、load
json.dump(dict,open('b.json','w'))  ##序列化
print(json.load(open('b.json','r'))['name'])  #反序列化
# 【注意】eval不能使用

JSONpickle模块的区别

  1、JSON只能处理基本数据类型。pickle能处理所有Python的数据类型。

  2、JSON用于各种语言之间的字符转换。pickle用于Python程序对象的持久化或者Python程序间对象网络传输,但不同版本的Python序列化可能还有差异。

 

7、shelve模块

       shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写;key必须为字符串,而值可以是python所支持的数据类型

序列化 :

import shelve
f=shelve.open(r'sheve.shl')
#
f['alex']={'age':28,'pwd':'alex3714'}  #序列化
f['egon']={'age':18,'pwd':'3714'}
f.close()

反序列化:

import shelve
obj=shelve.open(r'sheve.shl')
# print(obj['alex'])  #反序列化
# print(obj['egon'])
# obj.close()
for i in obj:
print(i,obj[i])

 

8、re模块 

一:什么是正则? 

 正则就是用一些具有特殊含义的符号组合到一起(称为正则表达式)来描述字符或者字符串的方法。或者说:正则就是用来描述一类事物的规则。(在Python中)它内嵌在Python中,并通过 re 模块实现。正则表达式模式被编译成一系列的字节码,然后由用 C 编写的匹配引擎执行。 

二:常用匹配模式(元字符) 

http://blog.csdn.net/yufenghyc/article/details/51078107

# =================================匹配模式=================================
import  re
# print(re.findall('\w','Le_Qilele 123|le\nle1\t2'))
# print(re.findall('\S','Le_Qilele 123|le\nle1\t2'))
# print(re.findall('\d','Le_Qilele 123|le\nle1\t2')) #只匹配数字
# print(re.findall('\D','Le_Qilele 123|le\nle1\t2')) #只匹配任意非数字
# print(re.findall('L','Le_Qilele 123|Le\nle1\t2'))
# print(re.findall('\AL','Le_Qilele 123|Le\nle1\t2')) #匹配以L开通的一个
# print(re.findall('^L','Le_Qilele 123|Le\nle1\t2'))  #匹配以L开通的一个
# print(re.findall('L$','Le_Qilele 123|Le\nle1\t2L')) #匹配以L结尾的一个
# print(re.findall('L\Z','Le_Qilele 123|Le\nle1\t2L')) #匹配以L结尾的一个
# print(re.findall('\n','Le_Qilele 123|Le\nle1\t2L')) #只匹配‘\n'
# print(re.findall('\t','Le_Qilele 123|Le\nle1\t2L'))#只匹配‘\t'

#.[][^]
#'.'代表任意一个字符
print(re.findall('a.c','a a1c a*c abc a c aaaaaaac'))#只匹配‘a.c'
#['a1c', 'a*c', 'abc', 'a c', 'aac']
print(re.findall('a.c','a a1c a*c abc a c a\nc'))#.不匹配\n、\t
#['a1c', 'a*c', 'abc', 'a c']
print(re.findall('a.c','a a1c a*c abc a c a\nc a\tc',re.DOTALL))#.把\n、\t匹配进去
#['a1c', 'a*c', 'abc', 'a c', 'a\nc', 'a\tc']
print(re.findall('a.c','a a1c a*c abc a c a\nc a\tc',re.S))#同上效果
#['a1c', 'a*c', 'abc', 'a c', 'a\nc', 'a\tc']

#[]内部可以有多个值,但是只匹配多个字符中的一个
print(re.findall('a[1 23][456]c','a a1c a*c abc a ca26c a\nc a\tc',re.DOTALL))#[]内匹配2个数字
#['a26c']
print(re.findall('a[a-z]c','a a1c a*c abc a caXc a\nc a\tc',re.DOTALL))#[]内匹配2个数字
#['abc']
print(re.findall('a[a-zA-Z]c','a a1c a*c abc a caXc a\nc a\tc',re.DOTALL))#[]
#['abc', 'aXc']
print(re.findall('a[\+\-\*\/]c','a+c \n a-c a*c a/c',re.DOTALL))#[]特殊符号需要转义
#['a+c', 'a-c', 'a*c', 'a/c']
print(re.findall('a[^a-zA-Z]c','a a1c a*c abc a caXc a\nc a\tc',re.DOTALL))#[]匹配非字母
#['a1c', 'a*c', 'a c', 'a\nc', 'a\tc']

#\:转义
print(re.findall('a\\\\c','a\c abc')) #第一个转义第二个为普通'\',第三个转义第四个为普通'\'
#['a\\c']
print(re.findall(r'a\\c','a\c abc')) #rastring,正则表达式去前面加‘r’
#['a\\c']

#? * + {}   =>>左边有几个字符,如果有字符的话,就贪婪匹配
#'?'代表左边的字符0个或者1个
print(re.findall('ab?','a ab abb abbb bbbbbbb'))
#['a', 'ab', 'ab', 'ab']

#'*'代表左边那个字符0个或者多个
print(re.findall('ab*','a ab abb abbb bbbbbbb'))
#['a', 'ab', 'abb', 'abbb']

#'+'代表左边那个字符1个或者多个
print(re.findall('ab+','a ab abb abbb bbbbbbb'))
#['ab', 'abb', 'abbb']


#{n,m}左边的字符有自己指定个个数n-m次
print(re.findall('ab{2,4}','a ab abb abbb abbbb bbbbbbb'))
#['abb', 'abbb', 'abbbb']
print(re.findall('ab{4}','a ab abb abbb abbbb bbbbbbb'))
#['abbbb']


#.*  .?
#.*贪婪匹配
print(re.findall('a.*c','abc\t f|ac\tbc'))
#['abc\t f|ac\tbc']

#.*?非贪婪匹配
print(re.findall('a.*?c','adfbc\t f|ac\tbc'))
#['adfbc', 'ac']

# |
print(re.findall('company|companies','Too many companies have gone bankrupt, and the next one is my company'))
#['companies', 'company']

#():分组
print(re.findall('ab+','ababababababbb123'))
#['ab', 'ab', 'ab', 'ab', 'ab', 'abbb']
print(re.findall('ab+123','ababababababbb123'))
#['abbb123']
print(re.findall('(ab)','ababababababbb123'))
#['ab', 'ab', 'ab', 'ab', 'ab', 'ab']
print(re.findall('(a)b','ababababababbb123'))
#['a', 'a', 'a', 'a', 'a', 'a']

#()括号代表分组显示组里面的内容
print(re.findall('(ab)+','ababababababbb123'))
#['ab']

print(re.findall('a(1|2)c','a1c a2c a3c')) #匹配到a1c和a2c但是1、2是被()的所以打印()之间的内容。
#['1', '2']

print(re.findall('(ab)+123','abababababab123'))
#['ab']
print(re.findall('ab+123','abababababab123'))
#['ab123']
print(re.findall('(ab)+(123)','abababababab123'))  #以元祖的方式打印出来
#[('ab', '123')]
print(re.findall('(?:ab)+','ababababababbb123'))  #想匹配()内的所有匹配的内容
#['abababababab']


print(re.findall('compan(y|ies)','Too many companies have gone bankrupt, and the next one is my company'))
#['ies', 'y']
print(re.findall('compan(?:y|ies)','Too many companies have gone bankrupt, and the next one is my company'))
#['companies', 'company']


#re的其他方法search、

print(re.findall('ab','fabfaabfaabfqwrq'))  #把ab全都找出来
print(re.search('ab','fabfaabfaabfqwrq').group())  #到匹配一次就结束
#ab
print(re.search('ab','ffafdsaasdfa'))  #有值就可以.group(),没有就无法执行
#None

print(re.search('ab','abfaabfaabfqwrq'))
#<_sre.SRE_Match object; span=(0, 2), match='ab'>
print(re.match('ab','abfaabfaabfqwrq'))
#<_sre.SRE_Match object; span=(0, 2), match='ab'>

print(re.match('ab','adsfaababsfqwrq'))  #match只能从头找
#None

print(re.split('a','qacbe'))  #以a来切字符串
#['q', 'cbe']
print(re.split('[ab]','qacbe'))  #以a或者b来切字符串
#['q', 'c', 'e']

print(re.sub('a' ,'A','alax make sb')) #把a替换成A
#AlAx mAke sb
print(re.subn('a' ,'A','alax make sb')) #把a替换成A
#('AlAx mAke sb', 3)
print(re.subn('a' ,'A','alax make sb',1)) #把a替换成A
#('Alax make sb', 1))

print(re.sub('(\w+)+(\W+)+(\w+)+(\W+)+(\w+)',r'\5\2\3\4\1','alax make sb')) #把a替换成A
# sb make alax

#补充
obj=re.compile('\d{2}')
print(obj.search('fasfda12fdsae24').group())
#12
print(obj.findall('fasfda12fdsae24'))
# ['12', '24']

#练习 =》
# 1、找出数字(-12.34)
print(re.findall(r'-?\d+\.?\d*','1-12*(60+(-40.35/5)-(-4*3))'))
# 2、找出所有整数 (1,-3 )
print(re.findall(r"-?\d+\.\d+|(-?\d+)","1-2*(60+(-40.35/5)-(-4*3))")) #找出所有整数 

 

posted @ 2017-08-06 15:38  ShengLeQi  阅读(214)  评论(0)    收藏  举报