Python基础学习(3)装饰器,正则表达式,模块,hashlib,字符串格式化,生成器

1.冒泡排序

li1 = [33, 2, 10, 1]
print(li1)
def bubbleSort(li):
    for i in range(1, len(li)):
        for j in range(len(li) - i):
            if li[j] > li[j + 1]:
                temp = li[j]
                li[j] = li[j + 1]
                li[j + 1] = temp

    return li

new_list = bubbleSort(li1)
print(new_list)




2.装饰器

只要函数应用装饰器,那么函数就被重新定义,重新定义为装饰器的内层函数

1)定义装饰器,函数

2)应用装饰器

3)简单的无参数装饰器应用示例

# 装饰器
def outer(func):
	def inner():
		print("This is the beggining of the decorator")
		print("Decorating")
		print("This is the end of the decorator")
		result = func() # 执行传入的代码,上面的都是装饰器的内容
		print("---------------------------------------")
		return result
	return inner

@outer
def f1():
    print("Function 1")

f1()
"""
1.执行outer函数,并且将其下面的函数名,当作参数
2.将outer的返回值重新赋值给f1 = outer的返回值
"""
4)带有参数的装饰器示例

def outer(func):
    def inner(a1, a2):
        print("Start")
        result = func(a1, a2)
        print("End")
        return result
    return inner

@outer
def func1(a1, a2):
    return a1 + a2

5)接收任意参数的装饰器示例

def outer(func):
    def inner(*args, **kwargs):
        print("Start")
        result = func(*args, **kwargs)
        print("End")
        return result
    return inner

@outer
def func1(a1, a2):
    return a1 + a2
把func1函数作为outer的参数去执行outer函数

index的整体放入到内存,当内层函数inner中对func1运行调用它作为一个新的函数

@outer

(1)执行outer函数,将index作为参数传递

(2)将outer的返回值,重新赋值给index

6)装饰器在web框架中的应用:用户权限的验证



3. 正则表达式

字符匹配:普通字符,元字符

1)普通字符:大多数字符和字母都会和自身匹配

例:re.findall("Daemon", "dffDevilMayCryforDaemon")

2)元字符: .  ^  $  *  +  ?  {  }  [  ]  |  (  )  \

. 匹配除了换行符以外的任意一个字符

^ 是否开始就匹配条件,控制开头

$ 是否在结尾匹配条件,控制结尾

* 匹配0到多次

+ 匹配1到多次

? 匹配0到1次

{} 匹配固定的次数,{5}匹配5次,{3,5}匹配3到5次

[] 字符集,"a[bc]de"=> "abde"或"acde","[a-z]"匹配小写字母,"[^1-9]"非数字1到9


\ 反斜杠后边跟元字符去除特殊功能;反斜杠后面跟普通字符实现特殊功能;引用序号对应的字组所匹配的字符串

re.search(r"(Bruce)(Wayne)com\2","jointhegroup") # "\2"就相当于"(eric)"

\d 匹配任何十进制数;它相当于类[0-9]

\D 匹配任何非数字字符;它相当于类[^0-9]

\s 匹配任何空白字符;它相当于类[\t\n\r\f\v]

\S 匹配任何非空白字符;它相当于类[^ \t\n\r\f\v]

\w 匹配任何字母数字字符;它相当于类[a-zA-Z0-9_]

\W 匹配任何非字母数字字符;它相当于类[^ a-zA-Z0-9_]

\b 匹配一个单词边界,也就是指单词和空格间的位置


‘*’,‘+’和‘?’都是贪婪的。可以在后面加个问号,将策略改为非贪婪,自匹配尽量少的

re.search(r"a(\d+?)","a123") # 非贪婪模式,结果为1

re.search(r"a(\d+)","a123") # 贪婪模式,结果为123

re.search(r"a(\d+?)b","a123b") # 如果前后均有限定条件,则非贪婪模式就不再起作用了


() 将某些字符划为一组,

re.findall(r"(ab)*", "abcde")

re.findall(r"(ab)*", "abcde").group()


3) 函数

(1) match: re.match(pattern, string, flags=0),从头匹配

flags 编译标志位,用于修改正则表达式的匹配方式,如:是否区别多行匹配等等

(2) search: re.search(pattern, string, flags=0).group,浏览全部字符串,

re.search("\dcom","www.123hao.123com").group()

(3) findall: 

re.findall 以列表形式返回所有匹配的字符串

re.findall 可以获取字符串中所有匹配的字符串

p = re.compile(r"\d+")

print p.findall("1one2two3three4four")

re.findall(r"\w*oo\w*", text) # 获取字符串中,包含"oo"的所有匹配

finditer(): 与findall类似,将匹配到的所有内容都放置在一个列表中

(4) sub, subn:

re.sub(pattern, repl, string, max=0)

re.sub("g.t","have","I get an apple. I got an orange.")

(5) split:

p = re.compile(r"\d+")

p.split("one1two2three3four4")

(6) re.compile(strPattern[, flag]): 可以把正则表达式编译成一个正则表达式对象。

(7) 

r = re.match("h\w+", "Hello World!")

r = re.match("(?P<n1>h)(?P<n2>\w+)","Hello World!") # 增加了?P<n1>将匹配到的结果放到groupdict中,key=n1,value="h"

r.group() # 获取匹配到的所有结果

r.groups() # 获取模型中匹配到的分组结果

r.groupdict() # 获取模型中匹配到的分组结果


4)正则表达式的工作方式

re.I 是匹配对大小写不敏感

re.L 做本地化识别(locale-aware)匹配

re.M 多行匹配,影响^和$

re.S 是.匹配包括换行在内的所有字符

re.findall(".","abc\nde", re.S)

re.U 根据Unicode字符集解析字符。这个标志影响\w, \W, \b等

re.X 该标志通过给予你更灵活的格式以便你讲正则表达式写的 


5)一旦匹配成功,就是一个match object对象,而match object对象的操作方式如下:

group() 返回被RE酦醅的字符串

group(m,n) 返回组号为n,m所匹配的字符串

a = "123,abc456"

re.search("([0-9*])([a-z*])([0-9*])",a).group(0) # 123abc456

re.search("([0-9*])([a-z*])([0-9*])",a).group(1) # 123

re.search("([0-9*])([a-z*])([0-9*])",a).group(0) # abc

re.search("([0-9*])([a-z*])([0-9*])",a).group(0) # 456

start() 返回匹配开始的位置

end() 返回匹配结束的位置

span() 返回一个元祖包含匹配(开始,结束)的位置


用正则表达式计算复杂算式:

import re

origin = "1 - 2 * ((60 - 30 + (-40.0 / 5) * (9 - 2 * 5 / 3 + 7 / 3 * 99 / 4 * 2998 + 10 * 568 / 14)) - (-4 * 3) / (16 -3 * 2))"

while "(" in origin or ")" in origin:
    origin = re.split("\(([^()]+)\)", origin, 1)
    origin[1] = str(eval(origin[1]))
    origin = ''.join(origin)
    print origin

result = str(eval(origin))
print result


4. Python常用模块

模块分为三种:自定义模块、第三方模块、内置模块

1) time模块

(1) time.clock() # 返回处理器时间,3.3开始废弃

(2) time.process_time() # 返回处理器时间,3.3开始废弃

(3) time.time() # 返回当前系统时间戳

(4) time.ctime() # 输出Mon Jan 26 00:00:00 2016,当前系统时间

(5) time.ctime(time.time()) # 将时间戳转为字符串格式

(6) time.gmtime(time.time()) # 将时间戳转换成struct_time格式

(7) time.localtime(time.time()) # 将时间戳转换成struct_time格式,但返回本地时间

(8) time.mktime(time.localtime()) # 与time.localtime()功能相反,将struct_time格式转回成时间戳格式

(9) time.strftime("%Y-%m-%d %H-%m-%d", time.gmtime()) # 将struct_time格式转成指定的字符串格式

(10) time.strptime("2016-01-18", "%Y-%m-%d") # 将字符串格式转换成struct_time格式


2) sys模块

(1) sys.argv # 命令行参数List,第一个元素是程序本身路径

(2) sys.exit(n) # 退出程序,正常退出时exit(0)

(3) sys.version # 获取Python解释程序的版本信息

(4) sys.maxint # 最大的int值

(5) sys.path # 返回模块的搜索路径,初始化时使用Python Path环境变量的值

sys.path.append("D:")

(6) sys.platform # 返回操作系统平台名称

(7) sys.stdout.write("Please: ")  # 输出相关

val = sys.stdin.readline()[:-1]

(8) sys.stdin # 输入相关

(9) sys.stderr # 错误相关


3) datetime模块

(1) datetime.date.today # 输出格式

(2) datetime.date.fromtimestamp(time.time()) # 2016-01-16 将时间戳转成日期格式

(3) datetime.datetime.now # 输出2016-01-26 19:04:30

(4) datetime.datetime.now().timetuple() # 返回struct_time格式

(5) datetime.datetime.now().replace(2014,9,12) # 输出2014-09-12 19:06:23,返回当前时间,但指定的值被替换

(6) datetime.datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M") # 将字符串转换成日期格式

(7) datetime.datetime.now() + datetime.timedelta(days=10)  # 比现在加10天

(8) datetime.datetime.now() + datetime.timedelta(days = -10) # 比现在减10天

(9) datetime.datetime.now() + datetime.timedelta(hours = -10) # 比现在减10小时

(10) datetime.datetime.now() + datetime.timedelta(seconds = 120) # 比现在多120秒


模拟进度条练习:

# -*- coding:utf-8 -*-
import sys,time

for i in range(101):
    sys.stdout.write('\r') # 每一次清空原行
    sys.stdout.write("%s%% | %s" % (str(i), "*" * i))
    sys.stdout.flush() # 强制刷新至屏幕
    time.sleep(0.3)

4) pickle模块,可以把python中的任何数据类型转化成字符串,但只能在Python中支持

pickle模块提供了四个功能:dumps, dump, loads, load

(1) pickle.dumps 将数据通过特殊的形式转换为只有python语言认识的字符串

data = {"k1":123,"k2":456}

pickle_string = pickle.dumps(data)

(2) pickle.dump 将数据通过特殊的形式转换为只有python语言认识的字符串并写入文件

with open("pickle_store1", "w") as fp:

pickle.dump(data,fp)

(3) pickle.loads(file.read()) 将数据读取出来

(4) pickle.load(file) 将数据读取出来写入文件


5) json模块,与pickle用法一样,但只能转化列表、字典、简单的变量与字符串,可以跨多个语言使用


6) os模块,用以提供系统级别的操作:

(1) os.getcwd() # 获取当前工作目录,及当前Python脚本工作的目录路径

(2) os.chdir("dirname") # 改变当前脚本工作目录;相当于shell下cd

(3) os.curdir # 返回当前目录

(4) os.pardir # 获取当前目录的父目录字符串名

(5) os.makedirs("dir1/dir2") # 可生成多层递归目录

(6) os.removedirs("dirname1") # 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,以此类推

(7) os.mkdir("dirname") # 生成单级目录;相当于shell中mkdir dirname

(8) os.rmdir("dirname") # 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname

(9) os.listdir("dirname") # 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印

(10) os.remove() # 删除一个文件

(11) os.rename("oldname", "newname") # 重命名文件/目录

(12) os.stat("path/filename") # 获取文件/目录信息

(13) os.sep # 操作系统特定的路径分隔符,win下为“\\”,Linux下为“/”

(14) os.linesep # 当前平台使用的行终止符,win下为“\t\n”,Linux下为“\n”

(15) os.pathsep # 用于分割文件路径的字符串

(16) os.name # 字符串指示当前使用平台。win为"nt",Linux为“posix”

(17) os.system("bash command") # 运行shell命令,直接显示

(18) os.environ # 获取系统环境变量

(19) os.path.abspath(path) # 返回path规范化的绝对路径

(20) os.path.split(path) # 将path分割成目录和文件名二元组返回

(21) os.path.dirname(path) # 返回path的目录。其实就是os.path.split(path) 的第一个元素

(22) os.path.basename(path) # 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素

(23) os.path.exists(path) # 如果path存在,返回True;如果path不存在,返回False

(24) os.path.isabs(path) # 如果path是绝对路径,返回True

(25) os.path.isfile(path) # 如果path是一个存在的文件,返回True,否则返回False

(26) os.path.isdir(path) # 如果path是一个存在的目录,返回Treu,否则返回False

(27) os.path.join(path[, path[, ···]]) # 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略

(28) os.path.getatime(path) # 返回path所指向的文件或者目录的最后存取时间

(29) os.path.getmtime(path) # 返回path所指向的文件或目录的最后修改时间

7) 初始requests模块

案例:检查QQ在线状态

import requests
from xml.etree import ElementTree as ET

# 使用第三方模块requests发送HTTP请求,或者XML格式内容
r = requests.get("http://www.webxml.com//webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=424662508")
result = r.text

# 解析XML格式内容
node = ET.XML(result)

# 获取内容
if node.text == "Y":
    print("在线")
else:
    print("离线")

案例:查询火车车次详细信息

import requests
from xml.etree import ElementTree as ET

# 使用requests发送http请求,获取xml格式内容
r = requests.get("http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx/getDetailInfoByTrainCode?TrainCode=K234&UserID=")
result = r.text

# 解析xml格式内容
root = ET.XML(result)
for node in root.iter("TrainDetailInfo"):
    # node.tag当前节点的标签名;node.attrib当前节点的属性
    print(node.find("TrainStation").text, node.find("StartTime").text,
          node.tag, node.attrib)

8) xml模块

(1) xml文件的解析案例

from xml.etree import ElementTree as ET

# 打开并解析文件内容
tree = ET.parse("test.xml")
root = tree.getroot()

# 顶层标签
print(root.tag)

# 遍历xml文档的第二层
for child in root:
    # 第二层节点的标签名称和标签属性
    print(child.tag, child.attrib)

    # 遍历xml文档的第三层
    for grandchildren in child:
        # 第三层节点的标签名称和内容
        print(grandchildren.tag, grandchildren.text)
(2) xml文件修改内容案例

from xml.etree import ElementTree as ET

# 打开并解析文件内容
tree = ET.parse("test.xml")
root = tree.getroot()

print(root.tag)

for node in root.iter("year"):
    new_year = int(node.text) + 1
    node.text = str(new_year)

    # 设置属性
    node.set("name", "Bill")
    node.set("age", "37")
    del node.attrib["name"]

tree.write("test.xml")
(3) 删除节点的案例

from xml.etree import ElementTree as ET

# 打开并解析文件内容
tree = ET.parse("test.xml")
root = tree.getroot()

for node in root.findall("year"):
    year = node.text

    if int(year) < 2000:
        root.remove(node)

tree.write("test.xml")

(4) 创建xml

from xml.etree import ElementTree as ET

# 创建根节点
new_xml = ET.Element("namelist")

# 创建根节点的子节点
name1 = ET.SubElement(new_xml, "name", attrib={"Chinese":"Yes"})
age1 = ET.SubElement(new_xml, "age", attrib={"Adult":"No"})
sex1 = ET.SubElement(new_xml, "sex")
sex1.text = "Male"

name2 = ET.SubElement(new_xml, "name", attrib={"Chinese":"No"})
age2 = ET.SubElement(new_xml, "age", attrib={"Adult":"Yes"})
sex3 = ET.SubElement(new_xml, "sex")
sex3.text = "Female"

# 生成文档对象
et = ET.ElementTree(new_xml)
et.write("test.xml", encoding="utf-8", xml_declaration=True)

(5) 常用方法

 tag 标签

attrib 属性

find 查找,获取第一个寻找到的子节点

set 为当前节点设置属性

iter 迭代

get 获取当前节点的属性值
append 往某个节点添加一个节点

makeelement("标签名", attrib={"k":"v"}) 创建一个节点,需要用append方法添加到某个节点上

element 创建节点,Element类型

son = ET.Element("father", {"k":"v"})

tree.getroot() 获取xml根节点

extends(self,elements) 为当前节点扩展n个子节点

iterfind(self, path, namespace=None) 获得所有指定的节点,并创建一个迭代器(可以被for循环)

iter("tag") 在当前节点的子孙中根据节点名称寻找所有的指定节点,并返回一个迭代器(可以被for循环)

 两种解析方式:

root  = ET.XML(open("test.xml", "r").read()) # 解析字符串,可以通过tree = ElementTree(root)创建tree,然后通过tree.write("test.xml", encoding="utf-8") 写文件

tree = ET.parse("test.xml") # 解析文件,获得tree

创建子节点:

father = ET.SubElement(root,"father",{"age":"56"}

son= ET.SubElement(father ,"father",{"age":"56"}


(5) 注册命名空间

from xml.etree import ElementTree as ET

ET.register_namespace("h","https://www.bing.com")

# 构建树结构
root = ET.Element("{https://www.bing.com}SEARCH")
body = ET.SubElement(root, "{https://www.bing.com}More_Search", )
body.text = "Search for everything"

tree = ET.ElementTree(root)

tree.write("test.xml",encoding="utf-8",xml_declaration=True)



5. hashlib:用于加密相关的操作,代替了md5模块和sha模块,主要提供SHA1,SHA224,SHA256,SHA384,SHA512,MD5算法

1) MD5不可逆,无法进行反解

import hashlib
hash = hashlib.md5()
hash.update(bytes("123"))
print(hash.hexdigest())
print(hash.digest())
2) SHA1

import hashlib
hash = hashlib.sha1()
hash.update(bytes("456"))
print(hash.hexdigest())
print(hash.digest())
3) SHA256

import hashlib
hash = hashlib.sha256()
hash.update(bytes("789"))
print(hash.hexdigest())
print(hash.digest())
4) SHA384
import hashlib
hash = hashlib.sha384()
hash.update(bytes("789"))
print(hash.hexdigest())
print(hash.digest())
5) SHA512
import hashlib
hash = hashlib.sha512()
hash.update(bytes("789"))
print(hash.hexdigest())
print(hash.digest())
6) 对密码进行加密的练习

import hashlib
def md5(arg):
    code = hashlib.md5("sad;fj;k")
    code.update(bytes(arg))
    return code.hexdigest()

def register(user,pwd):
    with open("db", "a") as f:
        temp = user + "|" + md5(pwd)
        f.write(temp)

def login(user,pwd):
    with open("db", "r") as f:
        for line in f:
            u,p = line.strip().split("|")
            if u == user and p == md5(pwd):
                return True

i = raw_input("1.登录;2.注册")
if i == "2":
    user = raw_input("用户名: ")
    pwd = raw_input("密码: ")
    register(user,pwd)
elif i == "1":
    user = raw_input("用户名: ")
    pwd = raw_input("密码: ")
    if login(user,pwd):
        print "登陆成功"
    else:
        print "登录失败"

9) configparser模块

(1) 配置文件格式:

# 注释1

; 注释2


[section1] # 节点

k1 = v1 # 值

k2: v2 # 值


[seciton2] # 节点

k1 = v1 # 值

import configparser

con = configparser.ConfigParser()
# con对象的read功能,打开文件读取,并将数据放入内存
con.read("ini",encoding="utf-8")

# 找到配置文件中的所有节点
sections = con.sections()
print(sections)

# 获取指定节点下所有的键值对
key_values = con.items("Steve")
print(key_values)

# 获取指定节点下所有的键
keys = con.options("Steve")
print(keys)

# 获取指定节点下制定key的值
value = con.get("Steve", "age")
# value = con.getint("Steve", "age")
# value = con.getfloat("Steve", "age")
# value = con.getboolean("Steve", "age")
print(value)

# 检查节点
has_sec = con.has_section("Steve")
print(has_sec)

# 添加节点
con.add_section("John")
con.write(open("ini", "w"))

# 删除节点
con.remove_section("John")
con.write(open("ini", "w"))

# 检查指定组内的键值对
has_opt = con.has_option("Steve", "age")
print(has_opt)

# 删除指定组内的键值对
con.remove_option("Steve","age")
con.write(open("ini", "w"))

# 设置指定组内的键值对
con.set("Steve", "gender", "Female")
con.write(open("ini", "w"))

10) shutil,对文件、文件夹、压缩包处理的高级模块

import shutil

# shutil.copyfileobj(fsrc, fdst[, length])将文件内容拷贝到另一个文件中
shutil.copyfileobj(open("ini", "r"), open("new", "w"))

# shutil.copyfile(src, dst)拷贝文件
shutil.copyfile("ini", "new")

# shutil.copymode(src, dst)仅拷贝权限。内容、组、用户均不变
shutil.copymode("ini", "new")

# shutil.copystat(src, dst) 拷贝状态的信息,包括:mode bits, atime, mtime, flags
shutil.copystat("int", "new")

# shutil.copy(src, dst)拷贝文件和权限
shutil.copy("ini", "new")

# shutil.copy2(src, dst)拷贝文件和状态信息
shutil.copy2("ini", "new")

# shutil.copytree(src, dst, symlinks=False, ignore=None)递归得去拷贝文件夹
shutil.copytree("folder1", "folder2", ignore=shutil.ignore_patterns("*.pyc", "tmp"))

# shutil.rmtree(path[,ignore_errors[,onerror]])递归地去删除文件
shutil.rmtree("folder1")

# shutil.move(src, dst) 递归地去移动文件,类似mv命令,其实就是重命名
shutil.move("folder1", "folder2")

# shutil.make_archive(base_name, format....)创建压缩包并返回文件路径
# base_name:压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径
# format: 压缩包种类,"zip", "tar", "bztar", "gztar"
# root_dir: 要压缩的文件夹路径(默认当前目录)
# owner:用户,默认当前用户
# group:组,默认当前组
# logger:用于记录日志,通常是logging.Logger对象
ret = shutil.make_archive("new_file", "tar", root_dir="/User/Steve/Downloads/spark.log")
(1) shuitl底层实现zip压缩使用的是zipfile

import zipfile

# 压缩
z = zipfile.ZipFile("photo.zip", "w")
z.write("Harry.jpg")
z.write("Ron.png")
z.close()

# 解压
z = zipfile.ZipFile("photo.zip", "r")
z.extractall()
z.close()
(2) shuitl底层实现tar压缩使用的是tarfile
import tarfile

# 压缩
tar = tarfile.open("new.tar","w")
tar.add("/User/Steve/logs/f1.log", arcname="file1.log")
tar.add("/User/Steve/logs/f2.log", arcname="file2.log")
tar.close()

# 解压
tar = tarfile.open("new.tar","r")
tar.extractall()
tar.close()

11) subprocess模块

import subprocess

# 专门用于python执行系统命令

# call执行命令,返回状态码
subprocess.call("ipconfig")
ret = subprocess.call(["ls","-l"], shell=False)
ret = subprocess.call("ls -l", shell=True)

# check_call执行命令。如果执行状态码是0,则返回0,否则报异常
subprocess.check_call(["ls","-l"])
subprocess.check_call("exit 1", shell=True)

# check_output执行命令,如果状态码是0,则返回执行结果,否则报异常
subprocess.check_output(["echo", "Hello World"])
subprocess.check_output("exit 1", shell=True)

# subprocess.Popen(...)用于执行复杂的系统命令
# args:shell命令,可以使字符串或者序列类型
# bufsize:指定缓冲,0无缓冲,1行缓冲,其他缓冲区大小,负值系统缓冲
# stdin,stdout,stderr:分别表示程序的标准输入、输出,错误句柄
# preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在紫禁城运行之前被调用
# close_fds:在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。所以不能close_fds设置为True同时重定向子进程的标准输入、输出与错误
# shell:同上
# cwd:用于设置子进程的当前目录
# env:用于指定子进程的环境变量,如果env=None,子进程的环境变量将从父进程中继承
# universal_newline:不同系统的换行符不同,True-》同意使用\n
# startupinfo与createionflags只在windows下有效
# 将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等
ret1 = subprocess.Popen(["mkdir", "t1"])
ret2 = subprocess.Popen("mkdir t2", shell=True)
(1) 执行普通命令

终端输入的命令分为两种:

输入即可得到输出,如:ifconfig

输入进行某环境,依赖再输入,如:python

12) logging模块

import logging

logging.basicConfig(filename='log.log',
                    format='%(asctime)s - %(name)s - %(levelname)s - %(module)s: %(message)s',
                    datefmt='%Y-%m-%d %H:%H:S %p',
                    level=10)
"""
CRITICAL = 50
FATAl = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0
"""
logging.critical("critical")
logging.fatal("fatal")
logging.error("error")
logging.warning("warning")
logging.info("info")
logging.debug("debug")
logging模块写多文件日志

import logging

# 创建文件
file_1 = logging.FileHandler("1_1.log", "a")
# 创建格式
fmt = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s - %(module)s: %(message)s")
# 文件应用格式
file_1.setFormatter(fmt)

file_2 = logging.FileHandler("1_2.log", "a")
fmt = logging.Formatter()
file_2.setFormatter(fmt)

logger1 = logging.Logger("s1", level=logging.ERROR)
logger1.addHandler(file_1)
logger1.addHandler(file_2)

# 写日志
logger1.critical("1111")





6. 字符串格式化

Python的字符串格式化有两种方式:百分号方式,format方式

1) 百分号方式

% [(name)][flags][width].[precision]typecode

(1) (name) 可选,用于选择指定的key

s = "Hello %(n1)s" % {"n1" : "World"}

(2) flags 可选,可供选择的值有:

+ 右对齐:正数前加正好,负号前加负号,例:s = "Hello %(n1)+10s" % {"n1" : "World"}

- 左对齐:正数前无符号,负数前加负号

空格 右对齐:正数前加空格,负数前加负号

0 右对齐:正数前无符号,负数前加负号;用0填充空白处

(3) width 可选,占有宽度

(4) .precision 可选,小数点后保留的位数,例:s = "Hello %.3f" % (1.2563)

(5) typecode 必选

s 获取传入对象的__str__方法的返回值,并将其格式化到指定位置

r 获取传入对象的__repr__方法的返回值,并将其格式化到指定位置

c 整数:将数字转换成其unicode对应的值,10进制范围为0 <= i <= 1114111: 字符: 将字符添加到指定位置

o 将整数转换成八进制表示,并将其格式化到指定位置

x 将证书转换成十六进制表示,并将其格式化到指定位置

d 将整数、浮点数转换成十进制表示,并将其格式化到指定位置

e 将证书、浮点数转换成科学计数法,并将其格式化到指定位置

E 将证书、浮点数转换成科学计数法,并将其格式化到指定位置

f 将整数、浮点数转换成浮点数表示,并将其格式化到指定位置

F 同上

g 自动调整将整数、浮点数转换成浮点型或科学计数法表示(超过6位用科学计数法),并将其格式化到指定位置

G 自动调整将整数、浮点数转换成浮点型或科学计数法表示(超过6位用科学计数法),并将其格式化到指定位置


2)Format方式

[[fill]align][sign][#][0][width][,][.precision][type]

(1) fill 可选,空白处填充的字符

(2) align 可选,对齐方式(需配合width使用)

< 内容左对齐

> 内容右对齐

= 内容右对齐,将符号放置在填充字符的左侧,且只对数字类型有效,即:符号+填充物+数字

^ 内容居中

(3) sign 可选,有无符号数字

+ 正号加正,负号加负

- 正号不变,负号加负

空格 正号空格,负号加负

(4) # 可选,对于二进制、八进制、十六进制,如果加上#会显示0b/0o/0x,否则不显示

(5) ,可选,为数字添加分隔符,如1,000,000

(6) width 可选,格式化位所占宽度

(7) .precision 可选,小数位保留精度

(8) type 可选,格式化类型
传入“字符串类型”的参数

s 格式化字符串数据类型

空格 未指定类型,则默认是None,同s
传入“整数类型”的参数


7. 生成器,执行时才会创建

def xrange():
    for i in range(10):
        yield i

ite1 = xrange()

for j in ite1:
    print(j)



猜你喜欢

转载自blog.csdn.net/wayne12081213/article/details/78825527
今日推荐