python函数和常用模块(二),Day4
- 内置函数2
- 装饰器
- 字符串格式化
- 生成器
- 迭代器
- 递归
- 模块
- 序列化相关
- time模块
- datetime模块
内置函数2
callable() # 是否可以被执行,是否可以被调用
chr() # ascii转字符
ord() # 字符转ascii
compile() # 编译
eval() # 执行
exec() # 执行
dict()
dir() # 快速查看对象为提供了哪些功能
help() #
divmod() #输出(商,余数)
isinstance() # 判断对象是否是某个类的实例
filter() # 函数返回True 将元素添加到结果中
map() # 函数的返回值添加到结果中
float() #
format() #
frozenset() #
globals() # 所有的全部变量
localse() #所有的局部变量
hash() # 生成哈希值
id() # 查看内存地址
issubclass() # 查看一个类是不是它的子类(派生类)
iter() #
len() # 查看长度 "李杰"3.x 长度为2(按字符计算)2.7.x中 长度为6 按字节计算
max()
min()
sum()
memoryview() # 跟内存地址相关的一个类
iter()
next()
object() # 一个类
pow() # 次方
property()
range()
repr()
reversed() # 反转
round() # 四舍五入
slice() #
sorted # 排序
vars() # 当前模块有哪些可以调用?
zip() # 实例 :随机验证码
improt random
random.randrange(1,5) import random
r = random.randrange(65, 91)
li = []
for i in range(6):
r = random.randrange(0, 5)
if r == 2 or r == 4:
temp = random.randrange(0, 10)
li.append(str(temp))
else:
temp = random.randrange(65, 91)
c = chr(temp)
li.append(c)
result = "".join(li)
print(result)
装饰器
1. 定义函数,为调用,函数内部不执行
2. 函数名 > 代指函数 @ + 函数名
功能:
1. 自动执行outer函数并且将其下面的函数f1当做参数传递
2. 将outer函数的返回值,重复赋值给f1
字符串格式化
百分号
format
tpl = "i am {}, age {}, {}".format("seven", 18, 'alex')
print(tpl)
tpl = "i am {}, age {}, {}".format(*["seven", 18, 'alex'])
print(tpl)
tpl = "i am {0}, age {1}, really {0}".format("seven", 18)
print(tpl)
tpl = "i am {0}, age {1}, really {0}".format(*["seven", 18])
print(tpl)
tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18)
print(tpl)
tpl = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18})
print(tpl)
tpl = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33])
print(tpl)
tpl = "i am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1)
print(tpl)
tpl = "i am {:s}, age {:d}".format(*["seven", 18])
print(tpl)
tpl = "i am {name:s}, age {age:d}".format(name="seven", age=18)
print(tpl)
tpl = "i am {name:s}, age {age:d}".format(**{"name": "seven", "age": 18})
print(tpl)
tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
print(tpl)
tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
print(tpl)
tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15)
print(tpl)
tpl = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)
print(tpl)
生成器
迭代器
递归
模块
* py:模块
* 其他:类库 1. 内置模块
2. 自定义模块
3. 第三方模块
安装:
* pip3
* 源码 * 先导入
* 再使用 可以是文件
可以是文件夹
序列化相关
json
#导入json模块
import json # 将python基本数据类型转换成字符串形式
json.dumps()
# 将python字符串形式转换成基本数据类型
json.loads()
# 将python基本数据类型转换成字符串形式,并写入文件
json.dump()
# 读取文件字符串,字符串形式转换成基本数据类型
json.load() 通过loads()反序列化时,一定要使用"" # 例
import json dic = {'k1': 'v1'}
print(dic, type(dic))
# 将python的基本数据类型转换成字符串形式
result = json.dumps(dic)
print(result, type(result)) # 将python字符串形式转换成基本数据类型
s1 = '{"k1": 123}'
dic1 = json.loads(s1)
print(dic1, type(dic1)) li = [11, 22, 33]
json.dump(li, open('db', 'w')) li = json.load(open('db', 'r'))
print(li, type(li))
pickle
import pickle
li = [11, 22, 33]
r = pickle.dumps(li)
print(r)
restult = pickle.loads(r)
print(restult) pickle.dumps()
pickle.loads()
pickle.dump()
pickle.load()
json更适合跨语言,字符串,基本类型做操作
pickle,python所有类型做操作
time模块
# time module
print(time.clock()) # 返回处理器时间 3.3开始废弃
print(time.process_time()) # 返回处理器时间 3.3开始废弃
print(time.time()) # 返回当前系统时间戳
print(time.ctime()) # 输出Wed Sep 14 16:16:10 2016, 当前系统时间
print(time.ctime(time.time()-86640)) # 将时间戳转为字符串格式
print(time.gmtime(time.time()-86640)) # 将时间戳转换struct_time格式
print(time.gmtime())
print(time.localtime()) # 将时间戳转换struct_time格式,但返回的是本地时间
print(time.mktime(time.localtime())) # 与time.localtiem()功能想反,将struct_time格式转回时间戳格式
# time.sleep(4)
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
print(time.strptime("2016-09-14", "%Y-%m-%d"))
datetime模块
# datetime module
print(datetime.date.today()) # 输出格式2016-09-14
print(datetime.date.fromtimestamp(time.time())) # 输出格式2016-09-14 时间戳转成日期
current_time = datetime.datetime.now()
print(current_time) # 输出格式2016-09-14 17:53:24.499480
print(current_time.timetuple()) # 返回struct_time格式 print(current_time.replace(2014, 9, 12)) # 输出2014-09-12 18:17:20.264601 返回当前时间,但是指定值将被替换 str_to_date = datetime.datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
print(str_to_date) print(datetime.datetime.now() + datetime.timedelta(days=10)) # 比现在加10天
print(datetime.datetime.now() + datetime.timedelta(days=-10)) # 比现在减10天
print(datetime.datetime.now() + datetime.timedelta(hours=10)) # 比现在加10小时
print(datetime.datetime.now() + datetime.timedelta(seconds=120)) # 比现在加120秒
logging模块
import logging
# 打印输出日志
logging.warning("user [alex] attempted wrong password more then 4 times")
logging.critical("server is down") # 将级别高于等于info的 写入日志文件
logging.basicConfig(filename='example.log', level=logging.INFO)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, to') logging.basicConfig(filename='example.log', level=logging.INFO, format='%(asctime)s %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p')
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, to')
logging还要扩展用法 以后补充
python函数和常用模块(二),Day4的更多相关文章
- Python自动化开发 - 常用模块(二)
本节内容 1.shutil模块 2.shelve模块 3.xml处理模块 4.configparser模块 5.hashlib模块 6.subprocess模块 7.re模块 一.shutil模块 高 ...
- python函数和常用模块(三),Day5
递归 反射 os模块 sys模块 hashlib加密模块 正则表达式 反射 python中的反射功能是由以下四个内置函数提供:hasattr.getattr.setattr.delattr,改四个函数 ...
- python之路----常用模块二
collections模块 在内置数据类型(dict.list.set.tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter.deque.defaultdict. ...
- python函数和常用模块(一),Day3
set集合 函数 三元运算 lambda表达式 内置函数1 文件操作 set集合 创建 se = {"123", "456"} # 直接创建一个集合 se = ...
- python笔记之常用模块用法分析
python笔记之常用模块用法分析 内置模块(不用import就可以直接使用) 常用内置函数 help(obj) 在线帮助, obj可是任何类型 callable(obj) 查看一个obj是不是可以像 ...
- 十八. Python基础(18)常用模块
十八. Python基础(18)常用模块 1 ● 常用模块及其用途 collections模块: 一些扩展的数据类型→Counter, deque, defaultdict, namedtuple, ...
- 常用模块二(hashlib、configparser、logging)
阅读目录 常用模块二 hashlib模块 configparse模块 logging模块 常用模块二 返回顶部 hashlib模块 Python的hashlib提供了常见的摘要算法,如MD5,SH ...
- python之路——常用模块
阅读目录 认识模块 什么是模块 模块的导入和使用 常用模块一 collections模块 时间模块 random模块 os模块 sys模块 序列化模块 re模块 常用模块二 hashlib模块 con ...
- python基础31[常用模块介绍]
python基础31[常用模块介绍] python除了关键字(keywords)和内置的类型和函数(builtins),更多的功能是通过libraries(即modules)来提供的. 常用的li ...
随机推荐
- Spring3系列11- Spring AOP——自动创建Proxy
Spring3系列11- Spring AOP——自动创建Proxy 在<Spring3系列9- Spring AOP——Advice>和<Spring3系列10- Spring A ...
- Spark源码系列(六)Shuffle的过程解析
Spark大会上,所有的演讲嘉宾都认为shuffle是最影响性能的地方,但是又无可奈何.之前去百度面试hadoop的时候,也被问到了这个问题,直接回答了不知道. 这篇文章主要是沿着下面几个问题来开展: ...
- WindowsCE project missing - 转
00x0 前言 之前在Windows 7系统中开发的WindowsCE项目,最近换成Windows 10系统,需要将项目进行修改,打开项目后提示如下错误: 无法读取项目文件“App.csproj”.. ...
- 查看、关闭某一runlevel下自动启动的服务
这些服务都在 /etc/init.d/ 目录下 1.查看 chkconfig --list | grep '3:on' Auditd - 安全审计工具: blk-availability 如果使用LV ...
- 关于Parallel.For/Foreach并行方法中的localInit, body, localFinally使用
对集合成员的操作往往可以通过并行来提高效率,.NET Parallel类提供了简单的方法来帮助我们实现这种并行,比如Paralle.For/ForEach/Invoke方法. 其中,For/ForEa ...
- Discuz & UCenter 修改手记 - 2014.12.19
最近在整JAVA和UCENTER的东西,受限于项目架构需要,无法完全以UCENTER为中心,所以在对接过程中遇到了许多不愉快的事情.经历多番研究,终于解决了其中了两个大问题,现记录下来,以备日后查看. ...
- ireport 导出工具类
Ireport 报表导出 Poi + ireport 导出pdf, word ,excel ,html 格式 下面是报表导出工具类 Ireport 报表导出 Poi + ireport 导出pdf, ...
- 解决访问StackOverFlow太慢的问题
Stackoverflow加载时访问了被屏蔽的站点ajax.googleapis.com,导致加载缓慢,把这个站点加到Hosts里,指向127.0.0.1即可
- How ADB works
ADB (Android Debug Bridge): How it works? 2012.2.6 early draft Tetsuyuki Kobayashi What is ADB? If y ...
- 初识js中的闭包
今天看了关于js闭包方面的文章,还是有些云里雾里,对于一个菜鸟来说,学习闭包确实有一定的难度,不说别的,能够在网上找到一篇优秀的是那样的不易. 当然之所以闭包难理解,个人觉得是基础知识掌握的不牢,因为 ...