Python 基础学习

https://blog.csdn.net/ityard/category_9466550.html

基础语句

1 条件语句

if 判断条件1:
    执行语句1...
elif 判断条件2:
    执行语句2...
elif 判断条件3:
    执行语句3...
else:
    执行语句4...

2 循环语句

##2.1 for 循环

#for 循环可以遍历任何序列,比如:字符串。如下所示:
str = 'Python'
for s in str:
  print(s)

##2.2 while 循环

#while 循环,满足条件时进行循环,不满足条件时退出循环。如下所示:
sum = 0
m = 10
while m > 0:
    sum = sum + m
    m = m - 1
print(sum)

##2.3 break

# break 用在 for 循环和 while 循环语句中,用来终止整个循环。如下所示:

str = 'Python'
for s in str:
    if s == 'o':
        break
    print(s)

##2.4 continue

# continue 用在 for 循环和 while 循环语句中,用来终止本次循环。如下所示:


str = 'Python'
for s in str:
    if s == 'o':
        continue
    print(s)

3 pass 语句

#pass 是空语句,它不做任何事情,一般用做占位语句,作用是保持程序结构的完整性。如下所示:

if True:
    pass

字符串

4 格式化

# %s	格式化字符串
# %d	格式化整数
# %f	格式化浮点数

print('Hello %s' % 'Python')

5 索引

str = 'Python'
print('str[0] str[-6] =', str[0], str[-6])
print('str[5] str[-1] =', str[5], str[-1])

6 切片

str = 'Python'
print(str[:3])
print(str[3:])
print(str[:])

7 相加

str1 = 'Python'
str2 = 'Python'
print('str1 + str2 --> ',str1 + str2)

8 相乘

str = 'Python'
print('2 * str --> ',2 * str)

序列

9 元素是否在序列中

str = 'Python'
print('on'in str)

10 内置函数

str = 'dbcae'
print('len -->', len(str))
print('max -->', max(str))
print('sorted -->', sorted(str))

列表与元组

11 列表

## 创建

l = [1024, 0.5, 'Python']

## 访问

l = [1024, 0.5, 'Python']
print('l[0] -->', l[0])
print('l[1:] -->', l[1:])

## 更新

l = [1024, 0.5, 'Python']
# 修改列表中第二个元素
l[1] = 5
# 向列表中添加新元素
l.append('Hello')
print('l[1] -->', l[1])
print('l -->', l)

## 删除

l = [1024, 0.5, 'Python']
# 删除列表中第二个元素
del l[1]
print('l -->', l)

## 常用方法

l = ['d', 'b', 'a', 'f', 'd']
print("l.count('d') -->", l.count('d')) ## 统计列表中某一元素出现的次数

l = ['d', 'b', 'a', 'f', 'd']
print("l.index('d') -->", l.index('d'))  ## 查找某个元素在列表中首次出现的位置

l = ['d', 'b', 'a', 'f', 'd']
l.remove('d')  ## 移除元素
print("l -->", l)

l = ['d', 'b', 'a', 'f', 'd']
l.sort()   ## 对列表中的元素进行排序
print('l -->', l)

l = ['d', 'b', 'a', 'f', 'd']
lc = l.copy()  ## 复制列表
print('lc -->', lc)

12 元组

## 创建

t = (1024, 0.5, 'Python')

## 访问

t = (1024, 0.5, 'Python')
print('t[0] -->', t[0])
print('t[1:] -->', t[1:])

## 修改

t = (1024, 0.5, 'Python')
t = (1024, 0.5, 'Python', 'Hello')
print('t -->', t)

## 删除

t = (1024, 0.5, 'Python')
del t
print('t -->', t)

## 常用方法

t = (1024, 0.5, 'Python')
print('len(t) -->', len(t))  ## 元组中元素个数

t = ('d', 'b', 'a', 'f', 'd')
print('max(t) -->', max(t))
print('min(t) -->', min(t))

l = ['d', 'b', 'a', 'f', 'd']
t = tuple(l)  ## 列表转化为元组
print('t -->', t)

list(t)  ## 元组转化为列表

字典与集合

13 字典

## 使用

d = {'name':'小明', 'age':'18'}

# 使用 dict 函数
# 方式一
l = [('name', '小明'), ('age', 18)]
d = dict(l)
# 方式二
d = dict(name='小明', age='18')

# 空字典
d = dict()
d = {}

## 访问

d = dict(name='小明', age='18')
d['name']

# 使用 get 方法
d.get('name')

## 修改

d = dict(name='小明', age='18')
d['age'] = '20'
d['age']

## 清空集合

d.clear()

## 获取字典的长度

len(d)

14 集合

#集合(set)与字典相同均存储 key,但也只存储 key,因 key 不可重复,所以 set 的中的值不可重复,也是无序的。

## 使用

s = {'a', 'b', 'c'}

# 使用 set 函数
s = set(['a', 'b', 'c'])

# 空集合
s = set()

s = {'a', 'b', 'c'}
s.add("d") ## 添加元素

s.update("e") ## 更新元素

s.remove("a")

s.clear()

len(s)

与时间相关的模块

15 与时间相关的模块

## 1 time模块

import time
t = time.localtime()
print('t-->', t)
print('tm_year-->', t.tm_year)
print('tm_year-->', t[0])

## 常用函数
import time

print(time.time())
print(time.gmtime())
print(time.localtime())
print(time.asctime(time.localtime()))
print(time.tzname)
# strftime 使用
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))

## 2 date time 模块

import datetime
import time

print(datetime.date.today())
print(datetime.date.fromtimestamp(time.time()))
print(datetime.date.min)
print(datetime.date.max)

import datetime

td = datetime.date.today()
print(td.replace(year=1945, month=8, day=15))
print(td.timetuple())
print(td.weekday())
print(td.isoweekday())
print(td.isocalendar())
print(td.isoformat())
print(td.strftime('%Y %m %d %H:%M:%S %f'))
print(td.year)
print(td.month)
print(td.day)

import datetime

t = datetime.time(10, 10, 10)
print(t.isoformat())
print(t.replace(hour=9, minute=9))
print(t.strftime('%I:%M:%S %p'))
print(t.hour)
print(t.minute)
print(t.second)
print(t.microsecond)
print(t.tzinfo)  ## 时区

import datetime

print(datetime.datetime.today())
print(datetime.datetime.now())
print(datetime.datetime.utcnow())
print(datetime.datetime.fromtimestamp(time.time()))
print(datetime.datetime.utcfromtimestamp(time.time()))
print(datetime.datetime.combine(datetime.date(2019, 12, 1), datetime.time(10, 10, 10)))
print(datetime.datetime.min)
print(datetime.datetime.max)

import datetime

td = datetime.datetime.today()
print(td.date())
print(td.time())
print(td.replace(day=11, second=10))
print(td.weekday())
print(td.isoweekday())
print(td.isocalendar()) ## 返回格式为 (year,month,day) 的元组
print(td.isoformat()) ## 返回一个以 ISO 8601 格式表示日期和时间的字符串 YYYY-MM-DDTHH:MM:SS.ffffff
print(td.strftime('%Y-%m-%d %H:%M:%S .%f'))
print(td.year)
print(td.month)
print(td.month)
print(td.hour)
print(td.minute)
print(td.second)
print(td.microsecond)
print(td.tzinfo)

## 3 calendar 模块

import calendar

calendar.setfirstweekday(1) ## 设置每一周的开始(0 表示星期一,6 表示星期天)
print(calendar.firstweekday()) 
print(calendar.isleap(2019)) ## 是否是闰年
print(calendar.leapdays(1945, 2019))  ## 返回1945和2019之间的闰年的数量
print(calendar.weekday(2019, 12, 1))  ## 返回指定日期的星期值
print(calendar.monthrange(2019, 12))  ## 返回指定年份的指定月份第一天是星期几和这个月的天数
print(calendar.month(2019, 12))
print(calendar.prcal(2019))


from calendar import Calendar

c = Calendar()
print(list(c.iterweekdays()))  ## 返回一个迭代器,迭代器的内容为一星期的数字
for i in c.itermonthdates(2019, 12):  ## 返回一个迭代器,迭代器的内容为年 、月的日期
    print(i)

from calendar import TextCalendar  ## 生成纯文本日历

tc = TextCalendar()
print(tc.formatmonth(2019, 12))
print(tc.formatyear(2019))

from calendar import HTMLCalendar

hc = HTMLCalendar()
print(hc.formatmonth(2019, 12))
print(hc.formatyear(2019))
print(hc.formatyearpage(2019))

函数

16 函数

## 自定义函数
# 空函数
def my_empty():
    pass

# 无返回值
def my_print(name):
    print('Hello', name)

# 有返回值
def my_sum(x, y):
    s = x + y
    print('s-->', s)
    return s
    
# 不定长参数
def my_variable(*params):
    for p in params:
        print(p)

# 匿名函数
my_sub = lambda x, y: x - y

## 函数调用
my_empty()
my_print('Jhon')
result = my_sum(1, 2)
my_variable(1, 2, 3, 4, 5, 6)
print(my_sub(2, 1))

模块与包

17 模块与包

## 模块  Python 中一个以 .py 结尾的文件就是一个模块,模块中定义了变量、函数等来实现一些类似的功能

## 包  包是存放模块的文件夹,包中包含 __init__.py 和其他模块,__init__.py 可为空也可定义属性和方法

# a 模块中引入 b 模块
import pg1.b
from pg1 import b

# a 模块中引入 c 模块
import pg2.c
from pg2 import c

# a 模块中引入 c 模块和 d 模块
import pg2.c,pg2.d
from pg2 import c,d

# a 模块中引入包 pg2 下的所有模块
from pg2 import *

# a 模块中引入 d 模块中函数 d()
from pg2.d import d
# 调用函数 d()
d()

面向对像

18.1 类

## 类
class Cat:
	# 属性
    color = 'black'
    # 构造方法
    def __init__(self, name):
        self.name = name
    # 自定义方法
    def eat(self, food):
        self.food = food
        print(self.name, '正在吃'+food)
print('color-->', Cat.color)

class Cat:
    __cid = '1'    ## 私有属性和方法
    def __run(self):
        pass

18.2 对象

## 对象

# 创建对象
c = Cat('Tom')

# 访问属性
print('name-->', c.name)
print('color-->', c.color)
# 调用方法
c.eat('鱼')

class Cat:
    __cid = '1'
    def __run(self, speed):
        print('__cid是'+self.__cid+'的猫', '以'+speed+'的速度奔跑')
    def run(self, speed):
        self.__run(speed)

c=Cat()
c.run('50迈')

18.3 继承

## 继承

# 波斯猫类
class PersianCat(Cat):
    def __init__(self, name):
        self.name = name
    def eat(self, food):
        print(self.name, '正在吃'+food)
#加菲猫类
class GarfieldCat(Cat):
    def __init__(self, name):
        self.name = name
    def run(self, speed):
        print(self.name, '正在以'+speed+'的速度奔跑')
# 单继承
class SingleCat(PersianCat):
    pass
# 多继承
class MultiCat(PersianCat, GarfieldCat):
    pass

#调用
sc = SingleCat('波斯猫1号')
sc.eat('鱼')

mc = MultiCat('波斯加菲猫1号')
mc.eat('鱼')
mc.run('50迈')

## 如果继承的父类方法不能满足我们的需求,这时子类可以重写父类方法,如下所示:
class SingleCat(PersianCat):
    def eat(self, food ):
        print(self.name, '正在吃'+food, '十分钟后', self.name+'吃饱了')
sc = SingleCat('波斯猫1号')
sc.eat('鱼')

文件基本操作

19.1 创建

## 创建
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

mata = open('mata.txt', mode='w',encoding='utf-8')

mata.write('Tom\n')
mata.writelines(['Hello\n', 'Python'])
# 关闭
mata.close()   

19.2 读取

## 读取
with open('mata.txt', 'r', encoding='utf-8') as rf:  ## with 在完成操作后会自动关闭文件
    print('readline-->', rf.readline())
    print('read-->', rf.read(6))
    print('readlines-->', rf.readlines())
    print(rf.read(:))

19.3 定位

## 定位
with open('mata.txt', 'rb+') as f:
    f.write(b'123456789')
    # 文件对象位置
    print(f.tell())
    # 移动到文件的第四个字节
    f.seek(3)
    # 读取一个字节,文件对象向后移动一位
    print(f.read(1))
    print(f.tell())
    # 移动到倒数第二个字节
    f.seek(-2, 2)
    print(f.tell())
    print(f.read(1))

19.4 其他

## 其他
with open('mata.txt', 'r+') as f:
    # 检测文件对象是否连接到终端设备
    print(f.isatty())
    # 截取两个字节
    f.truncate(2)
    print(f.read())

os模块

20 os模块常用函数

import os
print(os.getcwd()) ## 查看当前工作路径

print(os.listdir('E:/'))  ## 返回指定目录下包含的文件和目录名列表

print(os.path.abspath('.')) ## 返回路径 path 的绝对路径

print(os.path.split('E:/tmp.txt')) ## 将路径 path 拆分为目录和文件两部分,返回结果为元组类型

print(os.path.join('E:/', 'tmp.txt')) ## 将一个或多个 path(文件或目录) 进行拼接

import os
import datetime
print(datetime.datetime.utcfromtimestamp(os.path.getctime('E:/'))) ## 返回 path(文件或目录) 在系统中的创建时间

print(datetime.datetime.utcfromtimestamp(os.path.getmtime('E:/'))) ## 返回 path(文件或目录) 在系统中的最后修改时间

print(datetime.datetime.utcfromtimestamp(os.path.getatime('E:/tmp.txt'))) ## 返回 path(文件或目录)的最后访问时间

print(os.path.exists('E:/tmp.txt')) ## 判断文件或路径是否存在

print(os.path.isdir('E:/')) ## 判断 path 是否为目录

print(os.path.isfile('E:/tmp.txt'))  ## 判断 path 是否为文件

print(os.path.getsize('E:/messages.xml')) ## 返回 path 的大小,以字节为单位,若 path 是目录则返回 0
print(os.path.getsize('E:/高程'))

os.mkdir('E:/test')  ## 创建一个目录
os.makedirs('E:/test1/test2')

print(os.getcwd())
os.chdir('/test')
print(os.getcwd())

print(os.system('ping www.baidu.com'))  ## 调用shell脚本

错误和异常

21.1 错误

## 语法错误
#print前面少了 : 
if True
    print("hello python")

## 逻辑错误

#0 是不能作为被除数的
a  = 5
b = 0
print(a/b)

21.2 异常

#1、被除数为 0,未捕获异常
def getNum(n):
        return 10 / n
print(getNum(0))

#2、捕获异常
def getNum(n):
    try:
        return 10 / n
    except IOError:
        print('Error: IOError argument.')
    except ZeroDivisionError:
        print('Error: ZeroDivisionError argument.')
print(getNum(0))

## try/except 处理异常
def getNum(n):
    try:
        print('try --> ',10 / n)
    except ZeroDivisionError:
        print('except --> Error: ZeroDivisionError argument.')
    else:
        print('else -->')
    finally:
        print('finally -->')

getNum(0)
getNum(1)

raise NameError('HiThere')
#自定义异常类 MyExc
class MyExc(Exception):  #继承Exception类
    def __init__(self, value):
        self.value = value
    def __str__(self):
        if self.value == 0:
            return '被除数不能为0'
#自定义方法
def getNum(n):
    try:
        if n == 0:
            exc = MyExc(n)
            print(exc)
        else:
            print(10 / n)
    except:
        pass

枚举

22.1 创建

from enum import Enum

class WeekDay(Enum):
    Mon = 0
    Tue = 1
    Wed = 2
    Thu = 3
    Fri = 4

22.2 访问

# 枚举成员
print(WeekDay.Mon)
# 枚举成员名称
print(WeekDay.Mon.name)
# 枚举成员值
print(WeekDay.Mon.value)

# 方式 1
for day in WeekDay:
    # 枚举成员
    print(day)
    # 枚举成员名称
    print(day.name)
    # 枚举成员值
    print(day.value)

# 方式 2
print(list(WeekDay))

22.3 比较

print(WeekDay.Mon is WeekDay.Thu)
print(WeekDay.Mon == WeekDay.Mon)
print(WeekDay.Mon.name == WeekDay.Mon.name)
print(WeekDay.Mon.value == WeekDay.Mon.value)

WeekDay.Mon < WeekDay.Thu  ## 枚举成员不能进行大小比较

22.4 确保枚举值唯一

 from enum import Enum, unique

@unique
class WeekDay(Enum):
	Mon = 0

迭代器与生成器

23.1 迭代器

for i in 'Hello':
    print(i)

from collections import Iterable

print(isinstance('abc', Iterable))  ## 判断是否为可迭代对象
print(isinstance({1, 2, 3}, Iterable))
print(isinstance(1024, Iterable))

## 迭代器  迭代器对象本质是一个数据流,它通过不断调用 __next__() 方法或被内置的 next() 方法调用返回下一项数据,当没有下一项数据时抛出 StopIteration 异常迭代结束
class MyIterator:
    def __init__(self):
        self.s = '程序之间'
        self.i = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.i < 4:
            n = self.s[self.i]
            self.i += 1
            return n
        else:
            raise StopIteration

mi = iter(MyIterator())
for i in mi:
    print(i)

23.2 生成器

## 生成器
def reverse(data):
    for i in range(len(data)-1, -1, -1):
        yield data[i]
for char in reverse('Hello'):
    print(char)

# 列表
lis = [x*x for x in range(5)]
print(lis)

# 生成器
gen = (x*x for x in range(5))
for g in gen:
    print(g)

装饰器

24 装饰器

def x(id):
    def y(name):
        print ('id:', id, 'name:', name)
    return y

y = x('ityard')
y('程序之间')

# 装饰函数
def funA(fun):
    def funB(*args, **kw):
        print('函数 ' + fun.__name__ + ' 开始执行')
        fun(*args, **kw)
        print('函数 ' + fun.__name__ + ' 执行完成')
    return funB

@funA
# 业务函数
def funC(name):
  print('Hello', name)

funC('Jhon')

# 装饰函数
def funA(flag):
    def funB(fun):
        def funC(*args, **kw):
            if flag == True:
                print('==========')
            elif flag == False:
                print('----------')
            fun(*args, **kw)
        return funC
    return funB

@funA(False)
# 业务函数
def funD(name):
  print('Hello', name)

funD('Jhon')

class Test(object):
    def __init__(self, func):
        print('函数名是 %s ' % func.__name__)
        self.__func = func
    def __call__(self, *args, **kwargs):
        self.__func()
@Test
def hello():
    print('Hello ...')
    
hello()

命名空间 & 作用域

Python 有如下四种作用域:

  • # 局部:最先被搜索的最内部作用域,包含局部名称。
    # 嵌套:根据嵌套层次由内向外搜索,包含非全局、非局部名称。
    # 全局:倒数第二个被搜索,包含当前模块的全局名称。
    # 内建:最后被搜索,包含内置名称的命名空间。

25.1 全局作用域

g = 1
def outer():
    # 嵌套作用域
    e = 2
    def inner():
        # 局部作用域
        i = 3

25.2 全局变量

d = 0
def sub(a, b):
    # d 在这为局部变量
    d = a - b
    print('函数内 : ', d)

sub(9, 1)
print('函数外 : ', d)

25.3 编辑全局变量

d = 0
def sub(a, b):
    # 使用 global 声明 d 为全局变量
    global d
    d = a - b
    print('函数内 : ', d)

sub(9, 1)
print('函数外 : ', d)
def outer():
    d = 1
    def inner():
        d = 2
        print('inner:', d)
    inner()
    print('outer:', d)
outer()
def outer():
    d = 1
    def inner():
        nonlocal d  ## 声明非全局变量
        d = 2
        print('inner:', d)
    inner()
    print('outer:', d)
outer()

数字相关模块

26.1. math 模块

import math

dir(math)

x = -1.5
print(math.ceil(x))  ## 返回 x 的上限,即大于或者等于 x 的最小整数
print(math.floor(x))  ## 返回 x 的向下取整,小于或等于 x 的最大整数
print(math.fabs(x))  ## 返回x的绝对值
x= 3
y=2
print(math.fmod(x, y)) ## 返回 x/y 的余数,值为浮点数
x = 3
print(math.factorial(3))  ## 返回x的阶乘

x = 3
y = 2
print(math.pow(x, y))  ## 返回 x 的 y 次幂

print(math.fsum((1, 2, 3, 4, 5)))  ## 返回迭代器中所有元素的和

x = 9
y = 6
print(math.gcd(x, y))   ## 返回整数 x 和 y 的最大公约数

x = 9
print(math.sqrt(x))  ##  返回 x 的平方根
x = 1.1415926
print(math.trunc(x))  ## 返回 x 的整数部分

x = 2
print(math.exp(x))  ## 返回 e 的 x 次幂

x = 10
y = 10
# 不指定底数
print(math.log(x))  ## 返回 x 的对数,底数默认为 e
# 指定底数
print(math.log(x, y))

# 常量 e
print(math.e)
# 常量 π
print(math.pi)
print(math.tan(math.pi / 3))  ##返回 x 弧度的正切值
print(math.atan(1))   ##  返回 x 的反正切值
print(math.sin(math.pi / 3)) ##  返回 x 弧度的正弦值
print(math.asin(1))  ##  返回 x 的反正弦值
print(math.cos(math.pi / 3))  ## 返回 x 弧度的余弦值
print(math.acos(1))  ## 返回 x 的反余弦值

26.2 decimal 模块

from decimal import  *
getcontext()

d1 = decimal.Decimal(1.1)
d2 = decimal.Decimal(9.9)
print(d1 + d2)
print(d1 - d2)
print(d1 * d2)
print(d1 / d2)

decimal.getcontext().prec = 2  ##  修改默认精度
d1 = decimal.Decimal(1.1)
d2 = decimal.Decimal(9.9)
print(d1 + d2)
print(d1 - d2)
print(d1 * d2)
print(d1 / d2)

26.3 random 模块

import random

print(random.random())  ## 返回 [0.0, 1.0) 范围内的一个随机浮点数

print(random.uniform(1.1, 9.9))  ##  返回 [a, b) 范围内的一个随机浮点数

print(random.randint(1, 10)) ## 返回 [a, b] 范围内的一个随机整数

print(random.randrange(1, 10))
print(random.randrange(1, 10, 2)) ## 返回 [start, stop) 范围内步长为 step 的一个随机整数

print(random.choice('123456'))
print(random.choice('abcdef'))  ## 从非空序列 seq 返回一个随机元素

l = [1, 2, 3, 4, 5, 6]
random.shuffle(l)
print(l)  ## 将序列 x 随机打乱位置

l = [1, 2, 3, 4, 5, 6]
print(random.sample(l, 3))  ##  返回从总体序列或集合中选择的唯一元素的 k 长度列表,用于无重复的随机抽样

27 sys 模块

import sys
dir(sys)

if __name__ == '__main__': ##返回传递给 Python 脚本的命令行参数列表
    args = sys.argv
    print(args)
    print(args[1])
# version
# 返回 Python 解释器的版本信息。
# winver
# 返回 Python 解释器主版号。
# platform
# 返回操作系统平台名称。
# path
# 返回模块的搜索路径列表。
# maxsize
# 返回支持的最大整数值。
# maxunicode
# 返回支持的最大 Unicode 值。
# copyright
# 返回 Python 版权信息。
# modules
# 以字典类型返回系统导入的模块。
# byteorder
# 返回本地字节规则的指示器。
# executable
# 返回 Python 解释器所在路径。

print(sys.version)
print(sys.winver)
print(sys.platform)
print(sys.path)
print(sys.maxsize)
print(sys.maxunicode)
print(sys.copyright)
print(sys.modules)
print(sys.byteorder)
print(sys.executable)

sys.stdout.write('Hi' + '\n')  ## 等价 标准输出
print('Hi')

s1 = input()
s2 = sys.stdin.readline()  ## 标准输入
print(s1)
print(s2)

sys.stderr.write('this is a error message')  ## 错误输出

print('Hi')
sys.exit()
print('Jhon')

# getdefaultencoding()
# 返回当前默认字符串编码的名称。
# getrefcount(obj)
# 返回对象的引用计数。
# getrecursionlimit()
# 返回支持的递归深度。
# getsizeof(object[, default])
# 以字节为单位返回对象的大小。
# setswitchinterval(interval)
# 设置线程切换的时间间隔。
# getswitchinterval()
# 返回线程切换时间间隔。

print(sys.getdefaultencoding())
print(sys.getrefcount('123456'))
print(sys.getrecursionlimit())
print(sys.getsizeof('abcde'))
sys.setswitchinterval(1)
print(sys.getswitchinterval())

28 argparse 模块

import argparse

# 创建解析对象
parser = argparse.ArgumentParser()
# 解析
parser.parse_args()

usage: test.py [-h]

optional arguments:

parser = argparse.ArgumentParser()
parser.add_argument(
        '-n', '--name', dest='rname', required=True,
        help='increase output name'
    )
args = parser.parse_args()
name = args.rname
print('Hello', name)

test.py [-h] -n RNAME

optional arguments:
  -h, --help            show this help message and exit
  -n RNAME, --name RNAME
                        increase output name

29 正则表达式

29.1 re 模块

在这里插入图片描述


import re
re.compile(r'abc', re.I)

print(re.search(r'abc', 'abcef')) ## 扫描整个字符串找到匹配样式的第一个位置,并返回一个相应的匹配对象;如果没有匹配,就返回一个 None
print(re.search(r'abc', 'aBcef'))

print(re.match(r'abc', 'abcef')) # 如果 string 开始的 0 或者多个字符匹配到了正则表达式样式,就返回一个相应的匹配对象;如果没有匹配,就返回 None

print(re.fullmatch(r'abc', 'abcef'))
print(re.fullmatch(r'abc', 'abc'))  ## 如果整个 string 匹配到正则表达式样式,就返回一个相应的匹配对象;否则就返回一个 None

print(re.split(r'\W+', 'ityard, ityard, ityard.'))
print(re.split(r'(\W+)', 'ityard, ityard, ityard.'))
print(re.split(r'\W+', 'ityard, ityard, ityard.', 1))
print(re.split('[a-f]+', '1A2b3', flags=re.IGNORECASE)) ## 用 pattern 分开 string,如果在 pattern 中捕获到括号,那么所有的组里的文字也会包含在列表里,如果 maxsplit 非零,最多进行 maxsplit 次分隔,剩下的字符全部返回到列表的最后一个元素

print(re.findall(r'ab', 'abefabdeab'))  ## 对 string 返回一个不重复的 pattern 的匹配列表,string 从左到右进行扫描,匹配按找到的顺序返回,如果样式里存在一到多个组,就返回一个组合列表,空匹配也会包含在结果里

it = re.finditer(r'\d+', '12ab34cd56')  
for match in it:
    print(match)  ## pattern 在 string 里所有的非重复匹配,返回为一个迭代器 iterator 保存了匹配对象,string 从左到右扫描,匹配按顺序排列
    
str = 'ityard # 是我的名字'
print(re.sub(r'#.*$', '', str))  ## 返回通过使用 repl 替换在 string 最左边非重叠出现的 pattern 而获得的字符串,count 表示匹配后替换的最大次数,默认 0 表示替换所有的匹配

str = 'ityard # 是我的名字'  
print(re.subn(r'#.*$', '', str))  ## 行为与 re.sub() 相同,但返回的是一个元组

print(re.escape('https://blog.csdn.net/ityard')) ## 转义 pattern 中的特殊字符

re.purge() ## 清除正则表达式缓存

29.2 正则对象

pattern = re.compile(r'bc', re.I)
print(pattern.search('aBcdef'))
print(pattern.search('aBcdef', 1, 3))

pattern = re.compile(r'bc', re.I)
print(pattern.match('aBcdef'))
print(pattern.match('aBcdef', 1, 3))

pattern = re.compile(r'bc', re.I)
print(pattern.fullmatch('Bc'))
print(pattern.fullmatch('aBcdef', 1, 3))

pattern = re.compile(r'bc', re.I)
print(pattern.split('abc, aBcd, abcde.'))

pattern = re.compile(r'bc', re.I)
print(pattern.findall('abcefabCdeABC'))
print(pattern.findall('abcefabCdeABC', 0, 6))

pattern = re.compile(r'bc', re.I)
it = pattern.finditer('12bc34BC56', 0, 6)
for match in it:
    print(match)

pattern = re.compile(r'#.*$')
str = 'ityard # 是我的名字'
print(pattern.sub('', str))

pattern = re.compile(r'#.*$')
str = 'ityard # 是我的名字'
print(pattern.subn('', str))

29.3 匹配对象

match = re.match(r'(?P<year>\w+) (?P<month>\w+)','2020 01')
print(match.expand(r'现在是 \1 年 \2 月'))

match = re.match(r'(?P<year>\w+) (?P<month>\w+)','2020 01')
print(match.group(0))
print(match.group(1))
print(match.group(2))

match = re.match(r'(?P<year>\w+) (?P<month>\w+)','2020 01')
print(match.groups())

match = re.match(r'(?P<year>\w+) (?P<month>\w+)','2020 01')
print(match.groupdict())

match = re.match(r'(?P<year>\w+) (?P<month>\w+)','2020 01')
print(match.start())
print(match.end())

match = re.match(r'(?P<year>\w+) (?P<month>\w+)','2020 01')
print(match.span())
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值