生成器函数, 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']

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值