做一个技术girl

导航

十一、内置模块

一、json & pickle

1. 什么是序列化
序列化就是将内存中的数据类型转成另外一种格式

即:
字典---------序列化--------->其他的格式--------------->存到硬盘
硬盘---读取---->其他格式----------反序列化-------->字典

2. 为什么要序列化
1. 持久保存程序的运行状态
2. 数据的跨平台交互



3. 如何序列化
json:
优点: 这种格式是一种通用的格式,所有编程语言都能识别
缺点: 不能识别所有python类型
强调:json格式不能识别单引号

pickle
优点: 能识别所有python类型
缺点: 只能被python这门编程语言识别

二、time与datatime

# 时间分为三种格式:
import time
1. 时间戳
print(time.time())

2. 格式化的字符
print(time.strftime('%Y-%m-%d %H:%M:%S %p'))

3. 结构化的时间对象
print(time.localtime())
print(time.localtime().tm_hour)
print(time.localtime().tm_wday)
print(time.localtime().tm_yday)
print(time.gmtime())

时间转换
时间戳---->struct_time------->格式化的字符串
struct_time=time.localtime(123123)
print(struct_time)

print(time.strftime('%Y-%m-%d',struct_time))

格式化的字符串---->struct_time------->时间戳
struct_time=time.strptime('2017-03-11','%Y-%m-%d')
print(struct_time)

print(time.mktime(struct_time))

三、random模块

print(random.random())
print(random.randint(1,3))
print(random.randrange(1,3))
print(random.uniform(1,3))

print(random.choice([1,'a','c']))
print(random.sample([1,'a','c'],2))


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

随机验证码:
def make_code(max_size=5):
res=''
for i in range(max_size):
num=str(random.randint(0,9))
alp=chr(random.randint(65,90))

res+=random.choice([num,alp])

return res


print(make_code(10))


re模块


一:什么是正则?


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


常用匹配模式


模式描述
\w 匹配字母数字以及下划线
\W 匹配非字母数字下划线
\s 匹配任意空白字符
\S 匹配任意非空白字符
\d 匹配任意数字,等价于【0-9】
\D 匹配任意非数字
\A 匹配字符串开始
\Z 匹配字符串结束,如果是存在换行,只匹配到换行前的结束字符串
\z 匹配字符串结束
\G 匹配最后匹配完成的位置
\n 匹配一个换行符
\t 匹配一个制表符
^ 匹配字符串的开头
$ 匹配字符串的末尾
. 匹配任意字符,除了换行符,当re.DOTALL标记被指定时,则可以匹配包括换行符的任意字符
[...] 用来表示一组字符,单独列出:[amk]匹配'a','m'或'k'
[^...] 不在[]中的字符
* 匹配0个或多个表达式
+ 匹配1个或多个表达式
? 匹配0个或1个由前面的正则表达式定义的片段,非贪婪方式
{n} 精确匹配n个前面表达式
{n,m} 匹配n到m个由前面的正则表达式定义的片段,贪婪方式
a|b 匹配a或b
() 匹配括号内的表达式

 

hashlib模块

1. 什么是hash
   hash是一种算法,该算法接受一系列的数据,经过运算会得到一个hash值
   
   hash值具备三大特性:
       1. 只要传入的内容一样,那么得到的hash值一定是一样
       2. 只要采用hash算法固定,无论传入的内容多大,hash值的长度是固定
       3. hash值不可逆,即不能通过hash值逆推出内容

2. 为何要用hash

   特性1+2=>文件完整性校验
m=hashlib.md5()
m.update('你好'.encode('utf-8'))
m.update('hello'.encode('utf-8'))
print(m.hexdigest())

posted on 2018-12-05 18:51  戚戚~  阅读(115)  评论(0编辑  收藏  举报