1.定义一个生成器函数,生成1-10
使用next(generator)方法获取1-10
使用for循环获取
def generator():
for i in range(1, 11):
yield i
gen = generator()
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
for j in gen:
print(j)
1
2
3
4
5
6
7
8
9
10
2.模拟range的功能,自己建立一个range:MyRange
class MyRange:
def __init__(self, start, stop=None, step=1):
if step == 0:
raise ValueError('range() arg 3 must not be zero')
elif stop is None:
start, stop = 0, start
elif step > 0:
self.__length = max(0, ((stop - start - 1)//step)+1)
else:
self.__length = max(0, ((start - stop - 1)//abs(step))+1)
self.__start = start
self.__stop = stop
self.__step = step
def __iter__(self):
num = self.__start
if self.__step > 0:
while num < self.__stop:
yield num
num += self.__step
else:
while num > self.__stop:
yield num
num += self.__step
def __len__(self):
return self.__length
def __getitem__(self, k):
if k < 0:
k += self.__length
if 0 <= k < self.__length:
return self.__start + k*self.__step
else:
raise IndexError('range object index out of range')
3. re中函数的使用(正则表达式)
正则表达式(regular expression)描述了一种字符串匹配的模式(pattern),可以用来检查一个串是否含有某种子串、将匹配的子串替换或者从某个串中取出符合某个条件的子串等。
pattern 匹配的正则表达式 string 要匹配的字符串。 flags 标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等
match
re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none。
import re
str_data = "apple,hello,world"
pattern = 'a'
match_obj = re.match(pattern, str_data)
print(match_obj)
<re.Match object; span=(0, 1), match='a'>
fullmatch
search
re.search 扫描整个字符串并返回第一个成功的匹配。即找到就返回
str_data = "apple,hello,world"
pattern = 'p'
match_obj = re.search(pattern, str_data)
print(match_obj)
<re.Match object; span=(1, 2), match='p'>
findall
查找所有,以列表形式返回
str_data = "apple,hello,world"
pattern = 'p'
match_obj = re.findall(pattern, str_data)
print(match_obj)
['p', 'p']
finditer
查找所有,将查找的结果的match object放入迭代器中
str_data = "apple,hello,world"
pattern = 'a'
match_obj = re.finditer(pattern, str_data)
print(match_obj.__next__())
<re.Match object; span=(0, 1), match='a'>
split
按照正则表达式进行分割,返回一个列表
str_data = "apple,hello,world"
pattern = ' '
match_obj = re.split(pattern, str_data)
print(match_obj)
['apple,hello,world']
sub
替换
count:替换次数
str_data = "apple,hello,world"
pattern = 'a'
match_obj = re.sub(pattern, 'f', str_data, 1)
print(match_obj)
fpple,hello,world
subn
count: 替换次数
str_data = "apple,hello,world"
pattern = 'a'
match_obj = re.subn(pattern, 'f', str_data, 1)
print(match_obj)
('fpple,hello,world', 1)
complie
编译,用来生成正则表达式对象
str_data = "apple,hello,world"
pattern = 'a'
match_obj = re.compile(pattern)
print(match_obj.search(str_data))
<re.Match object; span=(0, 1), match='a'>