生成器,re, range函数
一、定义一个生成器函数,
1、生成1-10使用next(generator)方法获取1-10
2、使用for循环获取
def data():
for i in range(1,11):
yield i
data =data()
print(next(data))
for i in data:
print(i)
1
2
3
4
5
6
7
8
9
二、模拟range的功能,自己建立一个range:MyRange
class MyIterator:
def __init__(self, start=0, stop=0, step=0):
self.start = start
self.stop = stop
self.step = step
def __iter__(self):
return self
def __next__(self):
data = self.start
if self.start < self.stop:
self.start += self.step
return data
else:
raise StopIteration
for i in MyIterator(1, 10, 3):
print(i)
1
4
7
三、re中函数的使用
match
fullmatch
search
findall
finditer
split
sub
subn
complie
str_var = 'abc'
data = 'aabcbcabca'
obj_match = re.match(str_var, data)
print(obj_match)
# fullmatch
obj_full = re.fullmatch(str_var, data)
print(obj_full)
# search
obj_sea = re.search(str_var, data)
print(obj_sea)
# findall
obj_fin = re.findall(str_var, data)
print(obj_fin)
# finditer
obj_findier = re.finditer(str_var, data)
print(list(obj_findier))
# split
str_data = "西安培华,西安鸥鹏,西京"
pattern = ","
result = re.split(pattern, str_data, 1)
print(result)
# sub
str_data = "西安培华,西安鸥鹏,西京"
pattern = ","
result = re.sub(",", "|", str_data, 1)
print(result)
# subn
result = re.subn(",", "|", str_data)
print(result)
# complie
# 获取编译对象的函数
pattern = "abc"
str_data = "abcabcabc"
compile_obj = re.compile(pattern)
print(compile_obj)
print(compile_obj.match(str_data))
print(compile_obj.search(str_data))
print(compile_obj.findall(str_data))
# 输出
None
None
<re.Match object; span=(1, 4), match='abc'>
['abc', 'abc']
[<re.Match object; span=(1, 4), match='abc'>, <re.Match object; span=(6, 9), match='abc'>]
['西安培华', '西安鸥鹏,西京']
西安培华|西安鸥鹏,西京
('西安培华|西安鸥鹏|西京', 2)
re.compile('abc')
<re.Match object; span=(0, 3), match='abc'>
<re.Match object; span=(0, 3), match='abc'>
['abc', 'abc', 'abc']