Backend Development
Python Tutorial
Detailed explanation of Python's decorators, iterators & generators, re regular expressions, and string formattingDetailed explanation of Python's decorators, iterators & generators, re regular expressions, and string formatting
本章内容:
装饰器
迭代器 & 生成器
re 正则表达式
字符串格式化
装饰器
装饰器是一个很著名的设计模式,经常被用于有切面需求的场景,较为经典的有插入日志、性能测试、事务处理等。装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量函数中与函数功能本身无关的雷同代码并继续重用。概括的讲,装饰器的作用就是为已经存在的对象添加额外的功能。
先定义一个基本的装饰器:
########## 基本装饰器 ##########
def orter(func): #定义装饰器
def inner():
print("This is inner before.")
s = func() #调用原传入参数函数执行
print("This is inner after.")
return s #return原函数返回值
return inner #将inner函数return给name函数
@orter #调用装饰器(将函数name当参数传入orter装饰器)
def name():
print("This is name.")
return True #name原函数return True
ret = name()
print(ret)
输出结果:
This is inner before.
This is name.
This is inner after.
True
给装饰器传参数:
############ 装饰器传参数 ###########
def orter(func):
def inner(a,b): #接收传入的2个参数
print("This is inner before.")
s = func(a,b) #接收传入的原函数2个参数
print("This is inner after.")
return s
return inner
@orter
def name(a,b): #接收传入的2个参数,并name整体函数当参数传入orter装饰器
print("This is name.%s,%s"%(a,b))
return True
ret = name('nick','jenny') #传入2个参数
print(ret)
输出结果:
This is inner before.
This is name.nick,jenny
This is inner after.
True
给装饰器传万能参数:
########## 万能参数装饰器 ##########
def orter(func):
def inner(*args,**kwargs): #万能参数接收多个参数
print("This is inner before.")
s = func(*args,**kwargs) #万能参数接收多个参数
print("This is inner after.")
return s
return inner
@orter
def name(a,b,c,k1='nick'): #接受传入的多个参数
print("This is name.%s,%s"%(a,b))
return True
ret = name('nick','jenny','car')
print(ret)
输出结果:
This is inner before.
This is name.nick,jenny
This is inner after.
True
一个函数应用多个装饰器方法:
########### 一个函数应用多个装饰器 #########
def orter(func):
def inner(*args,**kwargs):
print("This is inner one before.")
print("This is inner one before angin.")
s = func(*args,**kwargs)
print("This is inner one after.")
print("This is inner one after angin.")
return s
return inner
def orter_2(func):
def inner(*args,**kwargs):
print("This is inner two before.")
print("This is inner two before angin.")
s = func(*args,**kwargs)
print("This is inner two after.")
print("This is inner two after angin.")
return s
return inner
@orter #将以下函数整体当参数传入orter装饰器
@orter_2 #将以下函数当参数传入orter_2装饰器
def name(a,b,c,k1='nick'):
print("This is name.%s and %s."%(a,b))
return True
ret = name('nick','jenny','car')
print(ret)
输出结果:
This is inner one before.
This is inner one before angin.
This is inner two before.
This is inner two before angin.
This is name.nick and jenny.
This is inner two after.
This is inner two after angin.
This is inner one after.
This is inner one after angin.
True

迭代器 & 生成器
1、迭代器
迭代器只不过是一个实现迭代器协议的容器对象。
特点:
访问者不需要关心迭代器内部的结构,仅需通过next()方法不断去取下一个内容
不能随机访问集合中的某个值 ,只能从头到尾依次访问
访问到一半时不能往回退
便于循环比较大的数据集合,节省内存
a = iter([1,2,3,4]) print a print a.next() print a.next() print a.next() print a.next() print a.next() <listiterator> 1 2 3 4 Traceback (most recent call last): File "D:/python/untitled4/test.py", line 23, in <module> print a.next() StopIteration</module></listiterator>
2、生成器
一个函数调用时返回一个迭代器,那这个函数就叫做生成器(generator);如果函数中包含yield语法,那这个函数就会变成生成器。
def xran():
print ("one")
yield 1
print "two"
yield 2
print "sr"
yield 3
ret = xran()
#print ret #<generator>
result = ret.next()
print result
result = ret.next()
print result
result = ret.next()
print result
# ret.next() #循环完毕抛出异常
# ret.close() #关闭生成器
one
1
two
2
sr
3</generator>
生成器的表达式:
a = [1,2,3] b = [i+3 for i in a] print b print type(b) ib = (i+3 for i in a) print ib print ib.next() print ib.next() print ib.next() [4, 5, 6] <type> <generator> at 0x00000000023E8A20> 4 5 6</generator></type>
正则表达式:
正则表达式是用来匹配字符串非常强大的工具,在其他编程语言中同样有正则表达式的概念。就其本质而言,正则表达式(或 RE)是一种小型的、高度专业化的编程语言,(在Python中)它内嵌在Python中,并通过 re 模块实现。正则表达式模式被编译成一系列的字节码,然后由用 C 编写的匹配引擎执行。
#导入 re 模块 import re s = 'nick jenny nice' # 匹配方式(一) b = re.match(r'nick',s) q = b.group() print(q) # 匹配方式(二) # 生成Pattern对象实例,r表示匹配源字符串 a = re.compile(r'nick') print(type(a)) #<class> b = a.match(s) print(b) #<_sre.sre_match> q = b.group() print(q) #被匹配的字符串放在string中 print(b.string) #nick jenny nice #要匹配的字符串放在re中</_sre.sre_match></class>
两种匹配方式区别在于:第一种简写是每次匹配的时候都要进行一次匹配公式的编译,第二种方式是提前对要匹配的格式进行了编译(对匹配公式进行解析),这样再去匹配的时候就不用在编译匹配的格式。
匹配规则:

<br># "." 匹配任意字符(除了\n) a = re.match(r".","95nick") b = a.group() print(b) # [...] 匹配字符集 a = re.match(r"[a-zA-Z0-9]","123Nick") b = a.group() print(b)

# \d \D 匹配数字/非数字 a = re.match(r"\D","nick") b = a.group() print(b) # \s \S 匹配空白/非空白字符 a = re.match(r"\s"," ") b = a.group() print(b) # \w \W 匹配单词字符[a-zA-Z0-9]/非单词字符 a = re.match(r"\w","123Nick") b = a.group() print(b) a = re.match(r"\W","+-*/") b = a.group() print(b)

# "*" 匹配前一个字符0次或者无限次
a = re.match(r"[A-Z][a-z]*","Aaaaaa123") #可以只匹配A,123不会匹配上
b = a.group()
print(b)
# “+” 匹配前一个字符1次或者无限次
a = re.match(r"[_a-zA-Z]+","nick")
b = a.group()
print(b)
# “?” 匹配一个字符0次或者1次
a = re.match(r"[0-8]?[0-9]","95") #(0-8)没有匹配上9
b = a.group()
print(b)
# {m} {m,n} 匹配前一个字符m次或者m到n次
a = re.match(r"[\w]{6,10}@qq.com","630571017@qq.com")
b = a.group()
print(b)
# *? +? ?? 匹配模式变为非贪婪(尽可能少匹配字符串)
a = re.match(r"[0-9][a-z]*?","9nick")
b = a.group()
print(b)
a = re.match(r"[0-9][a-z]+?","9nick")
b = a.group()
print(b)

# "^" 匹配字符串开头,多行模式中匹配每一行的开头。
li = "nick\nnjenny\nsuo"
a = re.search("^s.*",li,re.M)
b = a.group()
print(b)
# "$" 匹配字符串结尾,多行模式中匹配每一行的末尾。
li = "nick\njenny\nnick"
a = re.search(".*y$",li,re.M)
b = a.group()
print(b)
# \A 仅匹配字符串开头
li = "nickjennyk"
a = re.findall(r"\Anick",li)
print(a)
# \Z 仅匹配字符串结尾
li = "nickjennyk"
a = re.findall(r"nick\Z",li)
print(a)
# \b 匹配一个单词边界,也就是指单词和空格间的位置
a = re.search(r"\bnick\b","jenny nick car")
b = a.group()
print(b)

# "|" 匹配左右任意一个表达式
a = re.match(r"nick|jenny","jenny")
b = a.group()
print(b)
# (ab) 括号中表达式作为一个分组
a = re.match(r"[\w]{6,10}@(qq|163).com","630571017@qq.com")
b = a.group()
print(b)
# \<number> 引用编号为num的分组匹配到的字符串
a = re.match(r")[\w]+\1","<book>nick</book>")
b = a.group()
print(b)
# (?P<key>vlace) 匹配输出字典
li = 'nick jenny nnnk'
a = re.match("(?P<k1>n)(?P<k2>\w+).*(?P<k3>n\w+)",li)
print(a.groupdict())
输出结果:
{'k2': 'ick', 'k1': 'n', 'k3': 'nk'}
# (?P<name>) 分组起一个别名
# (?P=name) 引用别名为name的分组匹配字符串
a = re.match(r"[\w]+>)[\w]+(?P=jenny)","<book>nick</book>")
b = a.group()
print(b)</name></k3></k2></k1></key></number>
模块方法介绍

######## 模块方法介绍 #########
# match 从头匹配
# search 匹配整个字符串,直到找到一个匹配
# findall 找到匹配,返回所有匹配部分的列表
# findall 加括号
li = 'nick jenny nick car girl'
r = re.findall('n\w+',li)
print(r)
#输出结果:['nick', 'nny', 'nick']
r = re.findall('(n\w+)',li)
print(r)
#输出结果:['nick', 'nny', 'nick']
r = re.findall('n(\w+)',li)
print(r)
#输出结果:['ick', 'ny', 'ick']
r = re.findall('(n)(\w+)(k)',li)
print(r)
#输出结果:[('n', 'ic', 'k'), ('n', 'ic', 'k')]
r = re.findall('(n)((\w+)(c))(k)',li)
print(r)
#输出结果:[('n', 'ic', 'i', 'c', 'k'), ('n', 'ic', 'i', 'c', 'k')]
# finditer 返回一个迭代器,和findall一样
li = 'nick jenny nnnk'
a = re.finditer(r'n\w+',li)
for i in a:
print(i.group())
# sub 将字符串中匹配正则表达式的部分替换为其他值
li = 'This is 95'
a = re.sub(r"\d+","100",li)
print(a)
li = "nick njenny ncar ngirl"
a = re.compile(r"\bn")
b = a.sub('cool',li,3) #后边参数替换几次
print(b)
#输出结果:
#coolick cooljenny coolcar ngirl
# split 根据匹配分割字符串,返回分割字符串组成的列表
li = 'nick,suo jenny:nice car'
a = re.split(r":| |,",li) # 或|,分割 :, 空白符
print(a)
li = 'nick1jenny2car3girl5'
a = re.compile(r"\d")
b = a.split(li)
print(b)
#输出结果:
#['nick', 'jenny', 'car', 'girl', ''] #注意后边空元素

li = 'nick jenny nnnk'
a = re.match("n\w+",li)
print(a.group())
a = re.match("(n)(\w+)",li)
print(a.groups())
a = re.match("(?P<k1>n)(?P<k2>\w+).*(?P<k3>n\w+)",li)
print(a.groupdict())
-----------------------------------------------
import re
a = "123abc456"
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(2) #abc
re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(3) #456
group(1) 列出第一个括号匹配部分,group(2) 列出第二个括号匹配部分,group(3)列出第三个括号匹配部分。
-----------------------------------------------</k3></k2></k1>

#re.I 使匹配对大小写不敏感
a = re.search(r"nick","NIck",re.I)
print(a.group())
#re.L 做本地化识别(locale-aware)匹配
#re.U 根据Unicode字符集解析字符。这个标志影响 \w, \W, \b, \B.
#re.S:.将会匹配换行符,默认.逗号不会匹配换行符
a = re.findall(r".","nick\njenny",re.S)
print(a)
输出结果:
['n', 'i', 'c', 'k', '\n', 'j', 'e', 'n', 'n', 'y']
#re.M:^$标志将会匹配每一行,默认^只会匹配符合正则的第一行;默认$只会匹配符合正则的末行
n = """12 drummers drumming,
11 pipers piping, 10 lords a-leaping"""
p = re.compile("^\d+")
p_multi = re.compile("^\d+",re.M)
print(re.findall(p,n))
print(re.findall(p_multi,n))
常见正则列子:
匹配手机号:
# 匹配手机号
phone_num = '13001000000'
a = re.compile(r"^1[\d+]{10}")
b = a.match(phone_num)
print(b.group())
匹配IPv4:
# 匹配IP地址
ip = '192.168.1.1'
a = re.compile(r"(((1?[0-9]?[0-9])|(2[0-4][0-9])|(25[0-5]))\.){3}((1?[0-9]?[0-9])|(2[0-4][0-9])|(25[0-5]))$")
b = a.search(ip)
print(b)
匹配email:
# 匹配 email
email = '630571017@qq.com'
a = re.compile(r"(.*){0,26}@(\w+){0,20}.(\w+){0,8}")
b = a.search(email)
print(b.group())
字符串格式化:
1、百分号方式
%[(name)][flags][width].[precision]typecode
(name) 可选,用于选择指定的key
flags 可选,可供选择的值有:width 可选,占有宽度
+ 右对齐;正数前加正好,负数前加负号;
- 左对齐;正数前无符号,负数前加负号;
空格 右对齐;正数前加空格,负数前加负号;
0 右对齐;正数前无符号,负数前加负号;用0填充空白处
.precision 可选,小数点后保留的位数
typecode 必选
s,获取传入对象的__str__方法的返回值,并将其格式化到指定位置
r,获取传入对象的__repr__方法的返回值,并将其格式化到指定位置
c,整数:将数字转换成其unicode对应的值,10进制范围为 0
o,将整数转换成 八 进制表示,并将其格式化到指定位置
x,将整数转换成十六进制表示,并将其格式化到指定位置
d,将整数、浮点数转换成 十 进制表示,并将其格式化到指定位置
e,将整数、浮点数转换成科学计数法,并将其格式化到指定位置(小写e)
E,将整数、浮点数转换成科学计数法,并将其格式化到指定位置(大写E)
f, 将整数、浮点数转换成浮点数表示,并将其格式化到指定位置(默认保留小数点后6位)
F,同上
g,自动调整将整数、浮点数转换成 浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是e;)
G,自动调整将整数、浮点数转换成 浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是E;)
%,当字符串中存在格式化标志时,需要用 %%表示一个百分号
常用格式化:
tpl = "i am %s" % "nick"
tpl = "i am %s age %d" % ("nick", 18)
tpl = "i am %(name)s age %(age)d" % {"name": "nick", "age": 18}
tpl = "percent %.2f" % 99.97623
tpl = "i am %(pp).2f" % {"pp": 123.425556, }
tpl = "i am %.2f %%" % {"pp": 123.425556, }
2、Format方式
[[fill]align][sign][#][0][width][,][.precision][type]
fill 【可选】空白处填充的字符
align 【可选】对齐方式(需配合width使用)
>,内容右对齐(默认)
=,内容右对齐,将符号放置在填充字符的左侧,且只对数字类型有效。 即使:符号+填充物+数字
^,内容居中
sign 【可选】有无符号数字
+,正号加正,负号加负;
-,正号不变,负号加负;
空格 ,正号空格,负号加负;
# 【可选】对于二进制、八进制、十六进制,如果加上#,会显示 0b/0o/0x,否则不显示
, 【可选】为数字添加分隔符,如:1,000,000
width 【可选】格式化位所占宽度
.precision 【可选】小数位保留精度
type 【可选】格式化类型
传入” 字符串类型 “的参数
传入“ 整数类型 ”的参数
传入“ 浮点型或小数类型 ”的参数
s,格式化字符串类型数据
空白,未指定类型,则默认是None,同s
b,将10进制整数自动转换成2进制表示然后格式化
c,将10进制整数自动转换为其对应的unicode字符
d,十进制整数
o,将10进制整数自动转换成8进制表示然后格式化;
x,将10进制整数自动转换成16进制表示然后格式化(小写x)
X,将10进制整数自动转换成16进制表示然后格式化(大写X)
e, 转换为科学计数法(小写e)表示,然后格式化;
E, 转换为科学计数法(大写E)表示,然后格式化;
f , 转换为浮点型(默认小数点后保留6位)表示,然后格式化;
F, 转换为浮点型(默认小数点后保留6位)表示,然后格式化;
g, 自动在e和f中切换
G, 自动在E和F中切换
%,显示百分比(默认显示小数点后6位)
常用格式化:
tpl = "i am {}, age {}, {}".format("nick", 18, 'jenny')
tpl = "i am {}, age {}, {}".format(*["nick", 18, 'jenny'])
tpl = "i am {0}, age {1}, really {0}".format("nick", 18)
tpl = "i am {0}, age {1}, really {0}".format(*["nick", 18])
tpl = "i am {name}, age {age}, really {name}".format(name="nick", age=18)
tpl = "i am {name}, age {age}, really {name}".format(**{"name": "nick", "age": 18})
tpl = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33])
tpl = "i am {:s}, age {:d}, money {:f}".format("nick", 18, 88888.1)
tpl = "i am {:s}, age {:d}, money {:0.2f}".format("nick", 18, 88888.111111111111)
tpl = "i am {:s}, age {:d}".format(*["nick", 18])
tpl = "i am {name:s}, age {age:d}".format(name="nick", age=18)
tpl = "i am {name:s}, age {age:d}".format(**{"name": "nick", "age": 18})
tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15)
tpl = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)The above is the detailed content of Detailed explanation of Python's decorators, iterators & generators, re regular expressions, and string formatting. For more information, please follow other related articles on the PHP Chinese website!
Python vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AMPython is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.
Python vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AMPython and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.
Python for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AMPython's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.
Python and C : Finding the Right ToolApr 19, 2025 am 12:04 AMWhether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.
Python for Data Science and Machine LearningApr 19, 2025 am 12:02 AMPython is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.
Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AMIs it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.
Python for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AMKey applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code
Python vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AMPython is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Notepad++7.3.1
Easy-to-use and free code editor

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6
Visual web development tools





