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 ...
随机推荐
- Kruskal算法java版
/** * sample Kruskal.java Description: * kruskal算法的思想是找最小边,且每次找到的边不会和以找出来的边形成环路,利用一个一维数组group存放当前顶点所 ...
- WindowsStore页面导航
第一个页面:前台 <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}"> &l ...
- 让Windows 7变成WIFI热点
360要推便携路由器,个人觉得其主要目的是盯住了用户无线设备上的信息.因为如果用户移动设备都通过它这个路由器走的话,未加密的数据全部在他掌控之中. 其实Windows 7以上的系统是非常容易建立无线热 ...
- U3D4.X版本无法安装MONODEV编辑器
可能是由于机器无法成功安装.NET 4.0的缘故
- 设计模式——"simple Factory"
顾名思义,工厂模式就是类似于生活中的工厂,可以生产我们想要的东西,回到代码,假如我们需要一个实例,直接从工厂中拿即可. eg:假如我们定义一个“球”类的接口 public interface Ball ...
- 重构第1天:封装集合(Encapsulate Collection)
理解:封装集合就是把集合进行封装,只提供调用者所需要的功能行借口,保证集合的安全性. 详解:在大多的时候,我们没有必要把所有的操作暴露给调用者,只需要把调用者需要的相关操作暴露给他,这种情况中下我们就 ...
- xfire框架内部基本结构解析
1 概述 xfire是webservice的一个实现框架,是apache旗下CXF的前身,是一个比较被广泛使用的webservice框架,网上有很多关于如何使用xfire或cxf的hello worl ...
- Ubuntu 13.04 双显卡安装NVIDIA GT 630M驱动
[日期:2013-05-24] Linux系统:Ubuntu 13.04 安装 bumblebee 以管理双显卡,下面命令会自动安装NVIDIA显卡驱动 sudo add-apt-reposito ...
- 二十、【.Net开源】EFW框架核心类库之WebService服务
回<[开源]EFW框架系列文章索引> EFW框架源代码下载V1.1:http://pan.baidu.com/s/1qWJjo3U EFW框架实例源代码下载:http://pan.baid ...
- win7 or win8 系统访问2003系统上的数据库很慢
解决方式, 执行当前命令即可 netsh interface tcp set global autotuninglevel=disabled