十一、内置模块

一、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))
 

猜你喜欢

转载自www.cnblogs.com/lanlan999/p/10072697.html