文章目录
1.定义一个生成器函数,生成1-10
使用next(generator)方法获取1-10
使用for循环获取
def get_num():
for num in range(1, 11):
yield num
test = get_num()
print(type(test))
print(next(test))
print(next(test))
print(next(test))
print(next(test))
print(next(test))
print(next(test))
print(next(test))
print(next(test))
print(next(test))
print(next(test))
截图:
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')
# print(args, type(args))
# print(self.start, self.stop, self.step)
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
import re
pattern = "hello"
string = "hello world"
result = re.match(pattern, string)
print(result, type(result))
截图:
fullmatch
import re
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))
截图:
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))
截图: