1.定义一个生成器函数,生成1-10
使用next(generator)方法获取1-10
使用for循环获取
def produce_num():
for i in range(1, 11):
yield i
gen = produce_num()
print(next(gen), next(gen), next(gen), next(gen), next(gen),
next(gen), next(gen), next(gen), next(gen), next(gen))
2.模拟range的功能,自己建立一个range:MyRange
range(10)
range(1, 10)
range(1, 10, 1) =>
start, stop, step
range(10, 1, -1)
range(10, -1, -1)
range(-10, -1, 1)
range(-1, -10, -1)
class MyRange:
def __init__(self, *args):
if len(args) == 1:
self.start = 0
self.stop = args[0]
self.step = 1
if len(args) == 2:
self.start, self.stop = args
self.step = 1
if len(args) == 3:
self.start, self.stop, self.step = args
if self.step == 0:
raise ValueError('range() arg 3 must not be zero')
def __iter__(self):
return self
def __next__(self):
data = self.start
if self.step > 0:
if self.start < self.stop:
self.start += self.step
return data
else:
raise StopIteration
if self.step < 0:
if self.start > self.stop:
self.start += self.step
return data
else:
raise StopIteration
pass
print(list(MyRange(10)))
print(list(MyRange(1, 10)))
print(list(MyRange(1, 10, 1)))
print(list(MyRange(10, 1, -1)))
print(list(MyRange(10, -1, -1)))
print(list(MyRange(-10, -1, 1)))
print(list(MyRange(-1, -10, -1)))
3. re中函数的使用(自己写用例来使用)
match
fullmatch
search
findall
finditer
split
sub
subn
complie
import re
# match
pattern = "hello"
string = "hello world"
result = re.match(pattern, string)
print(result, type(result))
# fullmatch
pattern = "hello"
string = "hello"
match_obj = re.fullmatch(pattern, string)
print(match_obj)
# search
pattern = "hello"
string = "world hello"
match_obj = re.search(pattern, string)
print(match_obj)
# findall
string3 = "hello world hello"
pattern = "hello"
result = re.findall(pattern, string3)
print(result)
# finditer
string = "hello world hello"
pattern = "hello"
result = re.finditer(pattern, string)
print(result)
# split
string = "计算机,软件,网络"
pattern = ","
result = re.split(pattern, string, maxsplit=1)
print(result)
# sub
result = re.subn(",", "-", "计算机,软件,网络", )
print(result)
result = re.subn(",", "-", "计算机,软件,网络", 1)
print(result)
# subn
result = re.subn(",", "-", "计算机,软件,网络", 1)
print(result)
result = re.subn(",", "-", "计算机,软件,网络",)
print(result)
# complie
string = "hello world hello"
pattern = "hello"
compile_obj = re.compile(pattern)
print(compile_obj.search(string))
print(compile_obj.findall(string))
print(compile_obj.match(string))