python基础
Posted anyux
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python基础相关的知识,希望对你有一定的参考价值。
匿名函数
匿名是因为不需要以标准的方式来声明,如使用def语句
lambda [arg1,[ar2,...argN]:expression
#定义匿名函数
In [1]: a = lambda x,y: x+y
In [2]: ?a
Signature: a(x, y)
Docstring: <no docstring>
File: ~/<ipython-input-1-07b4826b0230>
Type: function
#直接返回结果
In [3]: a(2,4)
Out[3]: 6
正则表达式
search()方法,搜索123,只要"abc123milk"中存在,就返回结果
match()方法,默认是从开头查找,
In [4]: import re
In [5]: re.search("123","abc123milk")
Out[5]: <_sre.SRE_Match object; span=(3, 6), match='123'>
In [6]: re.search("123","abc1c3milk")
In [7]: re.search("1.3","abc1c3milk")
Out[7]: <_sre.SRE_Match object; span=(3, 6), match='1c3'>
In [8]: re.match("1.3","abc1c3milk")
In [9]: re.match("[0-9]{3}1.3","abc1c3milk")
In [10]: re.match("[a-w]{3}1.3","abc1c3milk")
Out[10]: <_sre.SRE_Match object; span=(0, 6), match='abc1c3'>
match提取内容
提取内容:使用小括号将内容括起来, [a-w]{3}(1.3)
取出内容
groups()取得结果,得到无组
In [11]: re.match("[a-w]{3}(1.3)","abc1c3milk").groups()
Out[11]: ('1c3',)
group(0)取出整个正则匹配到的结果
group(1)取出想要取出第一个小括号中的结果
group(2)取出想要取出第二个小括号中的结果
In [12]: re.match("[a-w]{3}(1.3)","abc1c3milk").group(0)
Out[12]: 'abc1c3'
In [13]: re.match("[a-w]{3}(1.3)","abc1c3milk").group(1)
Out[13]: '1c3'
In [17]: re.match("[a-w]{3}(1.3)([a-z]{4})","abc1c3milk").group(2)
Out[17]: 'milk'
模块的导入导出
import module from module import name [,name2,nam3,...nameN] import as
查找模块顺序
In [18]: import sys
In [19]: sys.path
Out[19]:
['',
'/usr/lib64/python36.zip',
'/usr/lib64/python3.6',
'/usr/lib64/python3.6/lib-dynload',
'/usr/local/lib64/python3.6/site-packages',
'/usr/local/lib/python3.6/site-packages',
'/usr/lib64/python3.6/site-packages',
'/usr/lib/python3.6/site-packages',
'/usr/local/lib/python3.6/site-packages/IPython/extensions',
'/root/.ipython']
‘‘,代表先查找当前目录,然后向下查找
导入方法及别名
In [20]: from re import search
In [21]: from re import search as sss
In [22]: sss("abc","123abcmilk")
Out[22]: <_sre.SRE_Match object; span=(3, 6), match='abc'>
装饰器
装饰器本质上是一个Python函数
装饰器的返回值也是一个函数对象
它可以让其他函数在不需要做任何代码变动的前提下增加额外功能
简单装饰器
def debug(func):
def wrapper():
print("[DEBUG]: enter {}()".format(func.__name__))
return func()
return wrapper
def say_hello():
print("hello!")
say_hello = debug(say_hello) # 添加功能并保持原函数名不变
装饰器语法糖
def debug(func):
def wrapper():
print("[DEBUG]: enter {}()".format(func.__name__))
return func()
return wrapper
@debug
def say_hello():
print("hello!")
初级装饰器传参
def debug(func):
def wrapper(*args, **kwargs): # 指定宇宙无敌参数
print("[DEBUG]: enter {}()".format(func.__name__))
print('Prepare and say...',)
return func(*args, **kwargs)
return wrapper # 返回
@debug
def say(something):
print("hello {}!".format(something))
以上是关于python基础的主要内容,如果未能解决你的问题,请参考以下文章