abs 绝对值
n = abs(-1)print(n)=========================
/usr/bin/python3.5 /home/liangml/pythonscript/test1.py1Process finished with exit code 0
abs 实例
all 所有为真,才为真
any 只要有真,就为真
n = all([1,2,3,4])print(n)
n= all([0,2,3,4])print(n)
n= any([[],1,"",None])print(n)
n= any([[],0,"",None])print(n)============================================
/usr/bin/python3.5 /home/liangml/pythonscript/test1.py
True
False
True
False
Process finished with exit code 0
all any 实例
bool 值(0,None,"",[]......)
print(bool())===============================
/usr/bin/python3.5 /home/liangml/pythonscript/test1.py
False
Process finished with exit code 0
bool值,实例
ascii 自动执行对象 _repr_ 方式
classFoo:def __repr__(self):return "444"n=ascii(Foo())print(n)========================================
/usr/bin/python3.5 /home/liangml/pythonscript/test1.py444Process finished with exit code 0
ascii 实例
bin() 将10进制转换成2进制
oct() 将10进制转换成8进制
hex() 将10进制转换成16进制
print(bin(5))print(oct(9))print(hex(15))========================================
/usr/bin/python3.5 /home/liangml/pythonscript/test1.py
0b101
0o110xfProcess finished with exit code 0
bin oct hex 实例
callable 查看函数是否可以被调用
deff1():passf2= 123
print(callable(f1))print(callable(f2))=====================================
/usr/bin/python3.5 /home/liangml/pythonscript/test1.py
0b101
0o110xfProcess finished with exit code 0
callable 实例
chr 将数字转换成字母
ord 将字母转换成数字
r = chr(65)print(r)
n= ord('A')print(n)======================================r= chr(65)print(r)
n= ord('A')print(n)
chr ord 实例
引入random 模块,制作随机验证码(字母随机验证码),每次切换都有不同的效果importrandom
li=[]for i in range(6):
temp= random.randrange(65,91)
c=chr(temp)
li.append(c)#li = ["c","b","a"]#cba
result = "".join(li)print(result)==========================================
/usr/bin/python3.5 /home/liangml/pythonscript/test.py
MFRAID
Process finished with exit code 0
随机验证码 1(字母)
importrandom
li=[]for i in range(6):if i == 2 or i == 4:
num= random.randrange(0,10)
li.append(str(num))else:
temp= random.randrange(65,91)
c=chr(temp)
li.append(c)
result= ''.join(li)print(result)=========================================
/usr/bin/python3.5 /home/liangml/pythonscript/test.py
YY7X4V
Process finished with exit code 0
随机验证码 2(有序插入数字)
importrandom
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(num))else:
temp= random.randrange(65,91)
c=chr(temp)
li.append(c)
result= ''.join(li)print(result)==============================================
/usr/bin/python3.5 /home/liangml/pythonscript/test.py
VF95VR
Process finished with exit code 0
随机验证码 3(所有字母及数字都无序)
compile() 将字符串编译成python代码
eval() 执行表达式,并返回值
exec() 执行python代码,接受代码或者是字符串(没有返回值)
s = 'print(123)'
#编译 single,eval,exec
r = compile(s,"","exec")#执行python代码
exec(r)=============================================
/usr/bin/python3.5 /home/liangml/pythonscript/test.py123Process finished with exit code 0
compile exec 配合使用
s = '8*8'ret=eval(s)print(ret)=================================================
/usr/bin/python3.5 /home/liangml/pythonscript/test.py64Process finished with exit code 0
eval 使用
dir 快速获取一个对象提供了什么功能
help 同dir功能一样,区别在于help可以列出使用详情
print(dir(list))========================================
/usr/bin/python3.5 /home/liangml/pythonscript/test.py
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
Process finished with exit code 0
dir 实例
help(list)=================================================
/usr/bin/python3.5 /home/liangml/pythonscript/test.py
Help onclass list inmodule builtins:classlist(object)| list() ->new empty list| list(iterable) -> new list initialized from iterable's items
|
|Methods defined here:|
| __add__(self, value, /)| Return self+value.|
| __contains__(self, key, /)| Return key inself.|
| __delitem__(self, key, /)|Delete self[key].|
| __eq__(self, value, /)| Return self==value.|
| __ge__(self, value, /)| Return self>=value.|
| __getattribute__(self, name, /)|Return getattr(self, name).|
| __getitem__(...)| x.__getitem__(y) <==>x[y]|
| __gt__(self, value, /)| Return self>value.|
| __iadd__(self, value, /)| Implement self+=value.|
| __imul__(self, value, /)| Implement self*=value.|
| __init__(self, /, *args, **kwargs)| Initialize self. See help(type(self)) foraccurate signature.|
| __iter__(self, /)|Implement iter(self).|
| __le__(self, value, /)| Return self<=value.|
| __len__(self, /)|Return len(self).|
| __lt__(self, value, /)| Return self
| __mul__(self, value, /)| Return self*value.n|
| __ne__(self, value, /)| Return self!=value.|
| __new__(*args, **kwargs) frombuiltins.type| Create and return a new object. See help(type) foraccurate signature.|
| __repr__(self, /)|Return repr(self).|
| __reversed__(...)| L.__reversed__() -- returna reverse iterator over the list|
| __rmul__(self, value, /)| Return self*value.|
| __setitem__(self, key, value, /)|Set self[key] to value.|
| __sizeof__(...)| L.__sizeof__() -- size of L in memory, inbytes|
|append(...)| L.append(object) -> None --append object to end|
|clear(...)| L.clear() -> None -- remove all items fromL|
|copy(...)| L.copy() -> list --a shallow copy of L|
|count(...)| L.count(value) -> integer -- returnnumber of occurrences of value|
|extend(...)| L.extend(iterable) -> None -- extend list by appending elements fromthe iterable|
|index(...)| L.index(value, [start, [stop]]) -> integer -- returnfirst index of value.| Raises ValueError if the value is notpresent.|
|insert(...)| L.insert(index, object) --insert object before index|
|pop(...)| L.pop([index]) -> item -- remove and returnitem at index (default last).| Raises IndexError if list is empty or index isout of range.|
|remove(...)| L.remove(value) -> None --remove first occurrence of value.| Raises ValueError if the value is notpresent.|
|reverse(...)| L.reverse() -- reverse *IN PLACE*
|
|sort(...)| L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
|
| ----------------------------------------------------------------------
| Data andother attributes defined here:|
| __hash__ =None
Process finished with exit code 0
help 实例
divmod 自动求出商 余数
r = divmod(97,10)print(r)
n1,n2= divmod(97,10)=============================================
/usr/bin/python3.5 /home/liangml/pythonscript/test.py
(9, 7)
Process finished with exit code 0
divmod 实例
isinstance 判断对象是否是类的实例
s = 'liangml'r=isinstance(s,str)print(r)========================================
/usr/bin/python3.5 /home/liangml/pythonscript/test.py
True {"k1":"v1"} {'k1': 'v1'}
Process finished with exit code 0
isinstance 实例
filter map(函数可迭代对象)
两者区别
filter:函数返回True,将元素添加到结果中
map:将函数返回值添加到结果中
filter 函数讲解deff1(args):
result=[]for item inargs:if item > 22:
result.append(item)returnresult
li= [11,22,33,44,55]
ret=f1(li)print(ret)===============================================================
/usr/bin/python3.5 /home/liangml/pythonscript/test.py
[33, 44, 55]
Process finished with exit code 0+++++++++++通过lambda表达式也可以实现相同的功能(自动return)+++++++++f1= lambda a: a >30ret=f1(90)print(ret)
li= [11,22,33,44,55]
result= filter(lambda a: a > 33,li)print(list(result))=========================运行结果===========================
/usr/bin/python3.5 /home/liangml/pythonscript/test.py
True
[44, 55]
Process finished with exit code 0
filter 函数运行原理deff2(a):if a>22:returnTrue
li= [11,22,33,44,55]#result = []#for item in 第二个参数(参数)#r = 第一个参数(item)#if r:#result(item)#return result#fileter,循环第二个参数,让每个循环元素执行函数,如果函数返回值Ture,表示元素合法
ret =filter(f2,li)print(list(ret))
map 函数讲解(函数可以使用for循环)===================for循环实例==========================li= [11,22,33,44,55]deff1(args):
result=[]for i inargs:
result.append(100+i)returnresult
r=f1(li)print(r)====================运行结果=============================
/usr/bin/python3.5 /home/liangml/pythonscript/test.py
[111, 122, 133, 144, 155]
Process finished with exit code 0====================设定函数运行===========================
deff2(a):return a + 100result=map(f2,li)print(list(result))++++++++++++++++++++运行结果+++++++++++++++++++++++++++++++
/usr/bin/python3.5 /home/liangml/pythonscript/test.py
[111, 122, 133, 144, 155]
Process finished with exit code 0===================也可以使用lambda表达式来实现==============result= map(lambda a: a+200,li)print(list(result))++++++++++++++++++++运行结果+++++++++++++++++++++++++++++
/usr/bin/python3.5 /home/liangml/pythonscript/test.py
[211, 222, 233, 244, 255]
Process finished with exit code 0
filter map 实例
float 把一个数转换成浮点型
frozenset 集合set set基础上不可变的集合
globals 所有的全局变量/locals 所有的局部变量
NAME = "liangml"
defshow():
a= 123
print(locals())print(globals())
show()
globals locals 实例
hash 将某一个类型的数据转换成hash值
s = 'hhh123123123'
print(hash(s))=============运行结果=====================
/usr/bin/python3.5 /home/liangml/pythonscript/test.py105733462617069300Process finished with exit code 0
hash 实例
len 查看某个字符串的长度
s = '梁孟麟'b= bytes(s,encoding='utf-8')print(len(s))print(len(b))========================================
/usr/bin/python3.5 /home/liangml/pythonscript/test.py3
9Process finished with exit code 0
len 实例
max() 求最大值/min() 求最小值/num() 求和/pow 求次方
q = max(2,10)
w= min(2,10)
e= sum([],10)
r= pow(2,10)print(q)print(w)print(e)print(r)========================================
/usr/bin/python3.5 /home/liangml/pythonscript/test.py10
2
10
1024Process finished with exit code 0
max/min/sum/pow 实例
round 四舍五入
r = round(1,4)print(r)============================================
/usr/bin/python3.5 /home/liangml/pythonscript/test.py1Process finished with exit code 0
round 实例
slice() 切片功能
s = 'ssssssssssss'
print(s[0:2])================================
/usr/bin/python3.5 /home/liangml/pythonscript/test.py
ss
Process finished with exit code 0
slice 实例
sorted 排序
li = [11,2,1,1]
r1=li.sort()
r2=sorted(li)print(r1)print(r2)===============================
/usr/bin/python3.5 /home/liangml/pythonscript/test.py
None
[1, 1, 2, 11]
Process finished with exit code 0
sorted 实例
zip 压缩分类元素
l1 = ['liangml',11,22,33]
l2= ['is',11,22,33]
l3= ['nb',11,22,33]
r=zip(l1,l2,l3)print(list(r))============================================
/usr/bin/python3.5 /home/liangml/pythonscript/test.py
[('liangml', 'is', 'nb'), (11, 11, 11), (22, 22, 22), (33, 33, 33)]
Process finished with exit code 0
json将字符串转换成Python的基本数据类型,{},[],注意:字符串形式的字典{"k1":"v1"}内部的字符串必须是双引号
s = "[11,22,33,44,55]"s= '{"k1":"v1"}'
print(type(s),s)importjson
n=json.loads(s)print(type(n),n)=============================================
/usr/bin/python3.5 /home/liangml/pythonscript/test.py {"k1":"v1"} {'k1': 'v1'}
Process finished with exit code 0
json 实例