• 内置函数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的更多相关文章

  1. Python自动化开发 - 常用模块(二)

    本节内容 1.shutil模块 2.shelve模块 3.xml处理模块 4.configparser模块 5.hashlib模块 6.subprocess模块 7.re模块 一.shutil模块 高 ...

  2. python函数和常用模块(三),Day5

    递归 反射 os模块 sys模块 hashlib加密模块 正则表达式 反射 python中的反射功能是由以下四个内置函数提供:hasattr.getattr.setattr.delattr,改四个函数 ...

  3. python之路----常用模块二

    collections模块 在内置数据类型(dict.list.set.tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter.deque.defaultdict. ...

  4. python函数和常用模块(一),Day3

    set集合 函数 三元运算 lambda表达式 内置函数1 文件操作 set集合 创建 se = {"123", "456"} # 直接创建一个集合 se = ...

  5. python笔记之常用模块用法分析

    python笔记之常用模块用法分析 内置模块(不用import就可以直接使用) 常用内置函数 help(obj) 在线帮助, obj可是任何类型 callable(obj) 查看一个obj是不是可以像 ...

  6. 十八. Python基础(18)常用模块

    十八. Python基础(18)常用模块 1 ● 常用模块及其用途 collections模块: 一些扩展的数据类型→Counter, deque, defaultdict, namedtuple, ...

  7. 常用模块二(hashlib、configparser、logging)

    阅读目录 常用模块二 hashlib模块 configparse模块 logging模块   常用模块二 返回顶部 hashlib模块 Python的hashlib提供了常见的摘要算法,如MD5,SH ...

  8. python之路——常用模块

    阅读目录 认识模块 什么是模块 模块的导入和使用 常用模块一 collections模块 时间模块 random模块 os模块 sys模块 序列化模块 re模块 常用模块二 hashlib模块 con ...

  9. python基础31[常用模块介绍]

    python基础31[常用模块介绍]   python除了关键字(keywords)和内置的类型和函数(builtins),更多的功能是通过libraries(即modules)来提供的. 常用的li ...

随机推荐

  1. myeclipse不编译解决方法

    在开发中经常遇到myeclipse不编译的情况,但不同情况的解决方法又不一样,今天同样是遇到此类情况,在网上狂搜,终于找到一篇好文,它囊括了解决这种情况的常用的方法,现在发出来与大家分享.我遇到的情况 ...

  2. JavaScript中的String对象

        String对象提供的方法用于处理字符串及字符. 常用的一些方法: charAt(index):返回字符串中index处的字符. indexOf(searchValue,[fromIndex] ...

  3. 阿里云ubuntu环境笔记

    安装jdk8 1.下载JDK 从官网下载jdk8 jdk-8u5-linux-x64.tar.gz 2.解压 $ tar -zxvf jdk-8u5-linux-x64.tar.gz 解压出来是一个j ...

  4. easyui textbox event 添加

    $('#tt').textbox({ inputEvents:$.extend({},$.fn.textbox.defaults.inputEvents,{ keyup:function(e){ co ...

  5. Turtle Online:致力于打造超接地气的PC前端架构,组件+API,快速搭建前端开发

    架构创作初衷 每当新开一个项目时,都会绞尽脑汁去考虑采用哪种框架:requirejs/seajs.jquery/zepto.backbone.easeUI/Bootstrap/AngularJS……, ...

  6. Qt4.8.6 Embedded Linux 的编译与移植

    最近买了个飞凌ok6410 的开发板,于是在其中搭建qt4.8.6运行环境.费了两三天时间,主要还是对Linux系统的生疏,在一些问题上徘徊很久,在这里做一些过程笔记.烧写ARM-Linux系统,根据 ...

  7. 移动安全时代,如何保护你的app

    Android系统的安全性历来备受诟病,在强大的反编译工具下,APK中的代码逻辑一览无余:重打包技术使得各种盗版软件层出不穷,充斥着Android市场,特别是对于金融.电商.游戏等产品的盗版应用,严重 ...

  8. Core Animation 学习

    core animation 是在UIKit层之下的一个图形库,用于在iOS 和 OS X 实现动画. Core Animation管理App内容 core animation不是一个完整的绘图系统, ...

  9. DDD:Can I DDD?

    下面是<实现领域驱动>的作者给出的一段话: You can implement DDD if you have: A passion for creating excellent soft ...

  10. Pace.js – 超赞的页面加载进度自动指示和 Ajax 导航效果

    在页面中引入 Pace.js  和您所选择主题的 CSS 文件,就可以让你的页面拥有漂亮的加载进度和 Ajax 导航效果.不需要挂接到任何代码,自动检测进展.您可以选择颜色和多种效果,有简约,闪光灯, ...