欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python-语法模板大全(常用)

程序员文章站 2022-07-02 16:53:26
[TOC] 1.怎么存数据 变量: age =10 字符串: name = "python" 列表: [1,2,3,"python"] 元组: (1,2,3)(不可以更改) 字典: {"a":100, "b":"666"} 2.怎么用数据 数字操作符: +、 、 、/、%、//、\ \ 判断循环: ......

目录

1.怎么存数据

  • 变量: age =10
  • 字符串: name = "python"
  • 列表: [1,2,3,"python"]
  • 元组: (1,2,3)(不可以更改)
  • 字典: {"a":100, "b":"666"}

2.怎么用数据

  • 数字操作符: +、-、*、/、%、//、**
  • 判断循环:
    • if判断:
    if a>10:
    b = a + 20
    if b>20:
      pass
    elif: a>8:
    pass
    else:
    pass
    • while循环
while i<5:
  # do something
  pass
  i = i + 1

while true:
  pass

3.函数

# 位置参数  
def person(name, age):
  print(name,age)

# 默认参数  

def person(name,age=20):
  print(name, age)

# 关键字参数
def person(name, age, **kw):
    print('name:', name, 'age:', age, 'other:', kw)  

person('hao', 20) # name: michael age: 30 other: {}
person('hao', 20, gener = 'm', job = 'engineer') # name: adam age: 45 other: {'gender': 'm', 'job': 'engineer'}  
extra = {'city': 'beijing', 'job': 'engineer'}
person('jack', 24, **extra)  

# 命名关键字参数
def person(name, age, *, city='beijing', job):
    print(name, age, city, job)

person('jack', 24, job = '123')
person('jack', 24, city = 'beijing', job = 'engineer')

# combination
# 可变 + 关键字参数
def f1(a, b, c=0, *args, **kw):
    print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)

f1(1, 2, 3, 'a', 'b')   # a = 1 b = 2 c = 3 args = ('a', 'b') kw = {'x': 99}
f1(1, 2, 3, 'a', 'b', x=99) # a = 1 b = 2 c = 0 d = 99 kw = {'ext': none}

# 默认参数 + 命名关键字参数 + 关键字参数
def f2(a, b, c=0, *, d, **kw):
    print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)

f2(1, 2, d=99, ext=none) # a = 1 b = 2 c = 0 d = 99 kw = {'ext': none}

4. 类和对象

4.1. 定义类的模板

class student(object):
    def __init__(self, name, score):
        self.__name = name
        self.__score = score

    # print(mike)
    def __str__(self):
        msg = "name: " + self.__name + "score: " + str(self.__score)
        return msg

    # mike
    __repr__ = __str__
    # mike()
    __call__ = __str__

    @property
    def name(self):
        return self.__name

    @name.setter
    def name(self, value):
        if type(value) == str:
            self.__name = value
        else:
            raise valueerror('bad name')

    @property
    def score(self):
        return self.__score

    @score.setter
    def score(self, value):
        if 0 <= value <= 100:
            self.__score = value
        else:
            raise valueerror('bad score')

    def final_report(self):
        if self.__score >= 90:
            level = 'a'
        elif self.__score >= 70:
            level = 'b'
        elif self.__score >= 60:
            level = 'c'
        else:
            level = 'd'
        msg = "your final value is: " + level
        return msg

# 调用

mike = student('mike', 85)
print("-" * 20 + "print property" + "-" * 20)
print(mike)
print("name: %s" % (mike.name))
print("-" * 30 + "print methods" + "-" * 20)
print(mike.final_report())
print("-" * 30 + "print modified infor" + "-" * 20)
mike.name = "obama"
mike.score = 50
print("-" * 30)
print("modified name: %s" % (mike.name))
--------------------print property--------------------
name: mikescore: 85
name: mike
------------------------------print methods--------------------
your final value is: b
------------------------------print modified infor--------------------
------------------------------
modified name: obama

4.2.继承

class sixgrade(student):
    def __init__(self, name, score, grade):
        super().__init__(name, score)
        self.__grade = grade

    # grade是一个只读属性
    @property
    def grade(self):
        return self.__grade

    def final_report(self, comments):
        # 子类中调用父类方法
        text_from_father = super().final_report()
        print(text_from_father)
        msg = "commants from teacher: " + comments
        print(msg)

print("-" * 20 + "继承" + "-" * 20)
fangfang = sixgrade('fang', 95, 6)
fangfang.final_report("you are handsome")
print(fangfang.grade)
--------------------继承--------------------
your final value is: a
commants from teacher: you are handsome
6

4.3 多态

class sixgrade(student):
    pass
    
class fivegrade(student):
    pass
    
def print_level(student):
    msg = student.final_report()
    print(msg)
    
print_level(student('from class', 90))
print_level(sixgrade('from subclass-1', 56))
print_level(fivegrade('from subclass-2', 85))
your final value is: a
your final value is: d
your final value is: b

5. io文件操作和os目录操作

os操作

import os
# 获取当前目录的绝对路径 
path = os.path.abspath('.')
# 创建一个目录
os.path.join('/users/michael', 'testdir')
os.mkdir('/users/michael/testdir')
# 删除一个目录
os.rmdir('/users/michael/testdir')
# 拆分路径
os.path.split('/users/michael/testdir/file.txt')  # ('/users/michael/testdir', 'file.txt')
os.path.splitext('/path/to/file.txt')  # ('/path/to/file', '.txt')
# 重命名
os.rename('test.txt', 'test.py')
# 删除文件
os.remove('test.py')
# 列出所有python文件
[x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py']

io文件

方法 特性 性能
read() 读取全部内容 一般
readline() 每次读出一行内容 占用内存最少
readlines() 读取整个文件所有行,保存在一个列表(list)变量中,每行作为一个元素 最好(内存足)
write() 写文件
# 读

# 下面是read()方法的使用,“r”表示read
with open('testread.txt', 'r', encoding='utf-8') as f1:
    results = f1.read()    # 读取数据
    print(results)

# 下面是readline()方法的使用,“r”表示read
with open('testread.txt', 'r', encoding='utf-8') as f2:
    line = f2.readline()    # 读取第一行
    while line is not none and line != '':
        print(line)
        line = f2.readline()    # 读取下一行

# 下面是readlines()方法的使用,“r”表示read
with open('testread.txt', 'r', encoding='utf-8') as f3:
    lines = f3.readlines()    # 接收数据
    for line in lines:     # 遍历数据
        print(line)

# 写

with open('/user/test.txt', 'w') as f:
  f.write('hello')

6. 正则表达式及re模块的使用

主要参考资料为:

Python-语法模板大全(常用)

6.2. re模块的使用

内置的 re 模块来使用正则表达式,提供了很多内置函数:

  1. pattern = re.compile(pattern[, flag]):
  • 参数:
    • pattern: 字符串形式的正则
    • flag: 可选模式,表示匹配模式
  • 例子:
import re

pattern = re.compile(r'\d+')
  1. pattern的常用方法
import re

pattern = re.compile(r'\d+')

m0 = pattern.match('one12twothree34four')
m = pattern.match('one12twothree34four', 3, 10)

print("-" * 15 + "match methods" + "-" * 15)
print("found strings: ", m.group(0))
print("start index of found strings: ", m.start(0))
print("end index of found strings: ", m.end(0))
print("span length of found strigns: ", m.span(0))

s = pattern.search('one12twothree34four')

print("-" * 15 + "search methods" + "-" * 15)
print("found strings: ", s.group(0))
print("start index of found strings: ", s.start(0))
print("end index of found strings: ", s.end(0))
print("span length of found strigns: ", s.span(0))

f = pattern.findall('one1two2three3four4', 0, 10)

print("-" * 15 + "findall methods" + "-" * 15)
print("found strings: ", f)

f_i = pattern.finditer('one1two2three3four4', 0, 10)

print("-" * 15 + "finditer methods" + "-" * 15)
print("type of method: ", type(f_i))
for m1 in f_i:  # m1 是 match 对象
    print('matching string: {}, position: {}'.format(m1.group(), m1.span()))

p = re.compile(r'[\s\,\;]+')
print("-" * 15 + "split methods" + "-" * 15)
print("split a,b;c.d: ", p.split('a,b;; c   d'))

p1 = re.compile(r'(\w+) (\w+)')
s1 = 'hello 123, hello 456'


def func(m):
    return 'hi' + ' ' + m.group(2)


print("-" * 15 + "替换 methods" + "-" * 15)
print(p1.sub(r'hello world', s1))  # 使用 'hello world' 替换 'hello 123' 和 'hello 456'
print(p1.sub(r'\2 \1', s1))  # 引用分组
print(p1.sub(func, s1))
print(p1.sub(func, s1, 1))  # 最多替换一次

结果是:

---------------match methods---------------
found strings:  12
start index of found strings:  3
end index of found strings:  5
span length of found strigns:  (3, 5)
---------------search methods---------------
found strings:  12
start index of found strings:  3
end index of found strings:  5
span length of found strigns:  (3, 5)
---------------findall methods---------------
found strings:  ['1', '2']
---------------finditer methods---------------
type of method:  <class 'callable_iterator'>
matching string: 1, position: (3, 4)
matching string: 2, position: (7, 8)
---------------split methods---------------
split a,b;c.d:  ['a', 'b', 'c', 'd']
---------------替换 methods---------------
hello world, hello world
123 hello, 456 hello
hi 123, hi 456
hi 123, hello 456