十二、python沉淀之路--内置函数

1、abs函数,求绝对值。

1 a = abs(-3)
2 print(a)

返回:3

2、all函数:判断是否是可迭代对象。

官方解释:Return True if bool(x) is True for all values x in the iterable.  If the iterable is empty, return True.

1 print(all(['2','4','9']))
2 #print(all('2','4','9'))  #会报错,因为里面不是可迭代对象
3 print(all(''))  #空字符串也是可迭代对象
4 print(all([1,2,3,'a']))
5 print(all([1,2,3,'','a']))    #False ,空 为False
6 #注:bool值里面只有几种是False,如 空、None、0 ;其余全是True,可以bool()函数来查看下
7 print(bool(''))
8 print(bool(None))
9 print(bool(0))
1 True
2 True
3 True
4 False
5 False
6 False
7 False

3、bytes  encoding   decode  编码方式,编码,解码详解

1 name = '你好'
2 print(bytes( name,encoding='utf-8'))                 #注:用什么方式编码,就必须用什么方式解码,不然会乱码
3 print(bytes(name,encoding='utf-8').decode('utf-8'))
4 
5 print(bytes(name,encoding='gbk'))
6 print(bytes(name,encoding='gbk').decode('gbk'))
7 
8 #print(bytes(name,encoding='ascii'))  # 会报错 ,因为ascii 码不能编码中文
1 b'xe4xbdxa0xe5xa5xbd'   #返回十六进制形式
2 你好
3 b'xc4xe3xbaxc3'
4 你好

4、chr函数:返回一个uniicode形式的字符串

官方解释:Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.

1 print(chr(1))
2 print(chr(9))
3 print(chr(40))
4 print(chr(45))
5 print(chr(50))

可以在电脑上自行运行结果

5、divmod函数:分页放数据函数,这很实用

1 print(divmod(10,3))  #分页函数,每页显示3条,最后还剩余一条,放到第4页
2 print(divmod(6,2))
3 print(divmod(20,5)) # 每页显示5条,返回结果为元组(4,0),表示分4页刚好放完,
1 (3, 1)
2 (3, 0)
3 (4, 0)

6、hash函数:可用于防木马等

可hash的数据类型即不可变数据类型:如字符串、元组、整型 ,不可hash的数据类型即可变数据类型:如 列表、字典、集合
1 name = 'hello'
2 print(hash(name))  #只要不修给值,每次打印出来的值都一样。
3 print(hash(name))
4 name = 'world'
5 print(hash(name))  #一旦被修改,打印出来的值就会发生变化,而且是不可逆的。
1 -5170208742037520982
2 -5170208742037520982
3 -4955782609536789689

用途:例如:下载一个程序,下载前一个hash值,下载后一个hash值,对比两个值如果一样,那么下载过程就没有被植入木马程序。

7、dir 和help 的使用以及区别

1 print(dir(dict))   #返回对象都有哪些功能
2 print(help(dict))   #返回的内容是如何使用



原文地址:https://www.cnblogs.com/jianguo221/p/8965963.html