栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python(10)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python(10)

"""
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))
# print(next(gen))
for i in gen: # 获取迭代器gen => gen.__next__()
    print(i)
print("=" * 80)
"""
2.# 自己定义一个MyIterator, 实现range的功能
 # # range(start, stop, step) => MyIterator
 # # range(10) # start=0, stop=10, step=1
 # # rang(10) # range(start=0, stop, step=1) =>start=10
 # # range(0,10)
 # # range(0,10,2)
 # # MyIterator(10)
 # # MyIterator(0,10)
 # # MyIterator(0,10,2)
"""
class Myrange(object):
    def __init__(self, stop=None, start=None, step=1):
        self.start = start
        self.stop = stop
        self.step = step
        print(start)

    def __iter__(self):
        self.cur_val = self.start
        return self

    def __next__(self):

        self.cur_val += self.step
        if self.cur_val < self.stop:

            return self.cur_val

        else:
            raise StopIteration


for i in Myrange(start=-2, stop=13, step=2):
    print(i)
print("=" * 80)
"""
3. re中函数的使用(自己写用例来使用):
 match
 fullmatch
 search
 findall
 finditer
 split
 sub
 subn
 complie
"""
import re
# match
pattern = "hello"
string = "hello world"
result = re.match(pattern, string)
print(result, type(result))
print("=" * 80)
#  fullmatch
pattern = "hello"
string = "hello"
match_obj = re.fullmatch(pattern, string)
print(match_obj)
print("=" * 80)
#  search
pattern = "hello"
string1 = "hello world"
string2 = "world hello"
string3 = "hello world hello"
match_obj = re.search(pattern, string1)
print(match_obj)
match_obj = re.search(pattern, string2)
print(match_obj)
match_obj = re.search(pattern, string3)
print(match_obj)
print("=" * 80)
#  findall
string3 = "hello world hello"
pattern = "hello"
result = re.findall(pattern, string3)
print(result)
print("=" * 80)
#  finditer
string3 = "hello world hello"
pattern = "hello"
result = re.finditer(pattern, string3)
print(result)
for i in result:
    print(i)
print("=" * 80)
#  split
result = re.split(pattern, string, maxsplit=1)
print(result)
print("=" * 80)
#  sub
result = re.sub(",", "-", "计算机,软件,网络", 1)
print(result)
print("=" * 80)
#  subn
result = re.subn(",", "-", "计算机,软件,网络", 1)
print(result)
print("=" * 80)
#  complie
string3 = "hello world hello"
pattern = "hello"

compile_obj = re.compile(pattern)
print(compile_obj.search(string3))
print(compile_obj.findall(string3))
print(compile_obj.match(string3))
print("=" * 80)

运行结果:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/503819.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号