Python-语法模板大全(常用)
1.怎么存数据
插入Python数据类型.png
变量:
age =10
字符串: 不可变对象
name = "python"
a = "pythonpythonpython"
# 索引和切片
a[0] # index
a[-1]
a[0:3] # slice
a[0:6:2]
a[-1:-7:-1]
a[::-1] # slice reverse
字符串方法详见:https://www.cnblogs.com/haochen273/p/10244032.html#字符串
列表:
[1,2,3,"python"]
a = [1,2,3,"python"]
len(a)
a[0]
[i*2 for i in a]
a.append(50)
a.insert(2,15)
a.extend([5,8,10])
a[0]="java"
"python" in a
a.index("python")
a.count(1)
a.pop(index)
元组:
(1,2,3)(不可以更改.与list类似)
字典:
{"a":100, "b":"666"}
d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
d['Michael']
d['Adam'] = 67
'Thomas' in d
d.get('Thomas')
d.pop('Bob')
三大容器的遍历方法
a = [1,2,3]
for i in a:
print(i)
b = (1,2,3)
for i in b:
print(b)
c = {"a":10, "b":20, "c":30}
for key,value in dict.items():
print("key = %s, value = %d"%(key,value))
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
- for循环
for i in [1,2,3]:
print(i)
- break和continue的使用
# break:打断全部循环
for i in [1,2,3,4,5]:
print("----")
if i==4:
break
print(i)
# continue: 打断一次循环
for i in [1,2,3,4,5]:
print("----")
if i==4:
continue
print(i)
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. Python核心编程
4.1. 列表生成器
[x * x for x in range(1, 11) if x % 2 == 0]
5. 类和对象
5.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
5.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
5.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
6. 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')
7. 正则表达式及re模块的使用
主要参考资料为:
6.1. 正则表达式语法
7.2. re模块的使用
内置的 re 模块来使用正则表达式,提供了很多内置函数:
- pattern = re.compile(pattern[, flag]):
- 参数:
- pattern: 字符串形式的正则
- flag: 可选模式,表示匹配模式
- 例子:
import re
pattern = re.compile(r'\d+')
- 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
Python-语法模板大全(常用)的更多相关文章
- python MVC、MTV 框架介绍 Django 模板系统常用语法
Django 框架简介一.MVC框架和MTV框架1.MVC 全名Model View Controller,是软件工程中的一种软件架构模式,把软件系统分为三个基本部分.优势: 耦合性低 重用性高 生命 ...
- python库包大全(转)
python 库资源大全 转自: Python 资源大全中文版 环境管理 管理 Python 版本和环境的工具 p:非常简单的交互式 python 版本管理工具.官网 pyenv:简单的 Python ...
- Python库资源大全
转载地址:https://zhuanlan.zhihu.com/p/27350980 本文是一个精心设计的Python框架.库.软件和资源列表,是一个Awesome XXX系列的资源整理,由BigQu ...
- (数据分析)第02章 Python语法基础,IPython和Jupyter Notebooks.md
第2章 Python语法基础,IPython和Jupyter Notebooks 当我在2011年和2012年写作本书的第一版时,可用的学习Python数据分析的资源很少.这部分上是一个鸡和蛋的问题: ...
- Python库资源大全【收藏】
本文是一个精心设计的Python框架.库.软件和资源列表,是一个Awesome XXX系列的资源整理,由BigQuant整理加工而成,欢迎扩散.欢迎补充! 对机器学习.深度学习在量化投资中应用感兴趣的 ...
- python爬虫:一些常用的爬虫技巧
python爬虫:一些常用的爬虫技巧 1.基本抓取网页 get方法: post方法: 2.使用代理IP 在开发爬虫过程中经常会遇到IP被封掉的情况,这时就需要用到代理IP; 在urllib2包中有Pr ...
- python语法快速入门(1)
http://www.runoob.com/python/python-tutorial.html Python 是一种解释型语言: 这意味着开发过程中没有了编译这个环节.类似于PHP和Perl语言 ...
- Python之路,Day21 - 常用算法学习
Python之路,Day21 - 常用算法学习 本节内容 算法定义 时间复杂度 空间复杂度 常用算法实例 1.算法定义 算法(Algorithm)是指解题方案的准确而完整的描述,是一系列解决问题的 ...
- 第六章:Python基础の反射与常用模块解密
本课主题 反射 Mapping 介绍和操作实战 模块介绍和操作实战 random 模块 time 和 datetime 模块 logging 模块 sys 模块 os 模块 hashlib 模块 re ...
随机推荐
- Intellij idea 离线安装activiti工作流插件
想在Intellij idea上安装一个activiti插件玩玩,由于网络环境原因,不能使用网上已有的在线搜索acti bpm并安装的方式.也在网上找了好久没找到离线安装的方式.自己摸索了一下装好了, ...
- 携程实时计算平台架构与实践丨DataPipeline
文 | 潘国庆 携程大数据平台实时计算平台负责人 本文主要从携程大数据平台概况.架构设计及实现.在实现当中踩坑及填坑的过程.实时计算领域详细的应用场景,以及未来规划五个方面阐述携程实时计算平台架构与实 ...
- 【死磕Java并发】----- 死磕 Java 并发精品合集
[死磕 Java 并发]系列是 LZ 在 2017 年写的第一个死磕系列,一直没有做一个合集,这篇博客则是将整个系列做一个概览. 先来一个总览图: [高清图,请关注"Java技术驿站&quo ...
- 福利:1H1G2M云服务器限时15元/月,买2送1,一年加6个月只要180元
平时看文章做测试只能用虚拟机的有福了,现在腾迅做活动,1H1G2M的服务器一个月只需要15元,买2送1,最多可以送6个月. 这个比之前1H1G1M10元一月的要好一些 购买地址
- 关于:未能加载文件或程序集“ICSharpCode.SharpZipLib”或它的某一个依赖项异常的解决方案
问题: 今天项目迁移忽然又个ICSharpCode.SharpZipLib.dll 程序包丢失了,于是我在网上下载一个这样的包,结果程序运行就提示:未能加载文件或程序集“ICSharpCode.Sha ...
- Sublime Text2支持Vue语法高亮显示
1.下载vue语法高亮插件vue-syntax-highlight 下载地址:https://github.com/vuejs/vue-syntax-highlight 2.将vue-syntax-h ...
- 使用 Moq 测试.NET Core 应用 -- Mock 属性
第一篇文章, 关于Mock的概念介绍: https://www.cnblogs.com/cgzl/p/9294431.html 第二篇文章, 关于方法Mock的介绍: https://www.cnbl ...
- 【python3基础】相对路径,‘/’,‘./’,‘../’
python3相对路径 “/” 前有没有 “.” ,有几个“.”,意思完全不一样. “/”:表示根目录,在windows系统下表示某个盘的根目录,如“E:\”: “./”:表示当前目录:(表示当前目录 ...
- java~IDEA引用包时分组所有java包
对于java系统包,我们的IDEA里开发项目时,如果你使用了java系统包,如import java.util,那么,你可以把它和其它第三方的包分开,这样更清晰,我们可以在设置里,代码风格,java ...
- SpringBoot技术栈搭建个人博客【后台开发】
前言:在之前,我们已经完成了项目的基本准备,那么就可以开始后台开发了,突然又想到一个问题,就是准备的时候只是设计了前台的RESTful APIs,但是后台管理我们同样也是需要API的,那么就在这一篇里 ...