1.定义一个生成器函数,生成1-10
使用next(generator)方法获取1-10
使用for循环获取
def get_num():
for num in range(1, 11):
yield num
gen = get_num()
print(type(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
'''
1
2
3
4
5
6
7
8
9
10
'''
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, start=None, stop=None, step=1):
if start is not None and stop is None: #传递一个参数
self.stop = start
self.start = 0
if start is not None and stop is not None:
self.start = start
self.stop = stop
self.step = step
def __iter__(self):
return self
def __next__(self):
if self.start < self.stop:
data = self.start
self.start += self.step
return data
else:
raise StopIteration
for i in MyRange(10):
print(i, end=' ')
print()
for i in MyRange(0, 10):
print(i, end=' ')
print()
for i in MyRange(0, 10, 2):
print(i, end=' ')
'''
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 2 4 6 8
'''
3. re中函数的使用(自己写用例来使用):
match
fullmatch
search
findall
finditer
split
sub
subn
complie
import re
pattern = "hello"
string = "hello world"
result = re.match(pattern, string)
print(result, type(result))
result = re.fullmatch(pattern, string)
print(result)
pattern = "hello"
string1 = "hello world"
string2 = "world hello"
string3 = "hello world hello"
result = re.search(pattern, string1)
print(result)
result = re.search(pattern, string2)
print(result)
result = re.search(pattern, string3)
print(result)
result = re.sub(",", "|", "张三,李四,王五")
print(result)
result = re.sub(",", "|", "张三,李四,王五", 1)
print(result)
result = re.subn(",", "|", "张三,李四,王五",)
print(result)
result = re.subn(",", "|", "张三,李四,王五", 1)
print(result)
string = "张三,李四,王五"
pattern = "|"
result = re.split(pattern, string)
print(result)
result = re.split(pattern, string, 1)
print(result)
pattern = "hello"
string3 = "hello world hello"
result = re.findall(pattern, string3)
print(result)
pattern = "hello"
string3 = "hello world hello"
result = re.finditer(pattern, string3)
print(result)
for i in result:
print(i)
pattern = "hello"
string3 = "hello world hello"
compile_obj = re.compile(pattern)
print(compile_obj.match(string3))
print(compile_obj.search(string3))
'''
<re.Match object; span=(0, 5), match='hello'> <class 're.Match'>
None
<re.Match object; span=(0, 5), match='hello'>
<re.Match object; span=(6, 11), match='hello'>
<re.Match object; span=(0, 5), match='hello'>
张三|李四|王五
张三|李四,王五
('张三|李四|王五', 2)
('张三|李四,王五', 1)
['', '张', '三', ',', '李', '四', ',', '王', '五', '']
['', '张三,李四,王五']
['hello', 'hello']
<callable_iterator object at 0x000001ADF1BD7DF0>
<re.Match object; span=(0, 5), match='hello'>
<re.Match object; span=(12, 17), match='hello'>
<re.Match object; span=(0, 5), match='hello'>
<re.Match object; span=(0, 5), match='hello'>
'''