一、基本用法

1、print功能

print(1)
1

1.1 print字符串

print("we're going to do something")
we're going to do something
print('we\'re going to do something')
we're going to do something

1.2 字符串叠加

print('apple'+'car')
applecar
print('apple'+'4')
apple4

1.3 简单运算

print(1+2)
3
print(int('1')+2)
3
print(float('1.2')+2)
3.2

2、基础数学运算

1+1
2
1-1
0
2*2
4
2**2
4

平方运算,不能是2^2

8%3
2

求余运算

9//4
2

取整运算

3、变量Variable

apple = 1
print(apple)
1
apple = 'iphone 7 plus'
print(apple)
iphone 7 plus
a,b,c = 11,12,13
print(a,b,c)
11 12 13

二、循环

1、while循环

执行循环,直到符合条件时结束。

while condition:expressions
condition = 0
while condition<10:print(condition)condition = condition+1#没有condition++这种写法,还可以写成condition += 1, ++condition
0
1
2
3
4
5
6
7
8
9

在使用 while 句法的时候一定要注意在循环内部一定要修改判断条件的值,否则程序的 while 部分 将永远执行下去。
while True:
print(“I’m True”)
如果这样做的话,程序将一直打印出 I’m True, 要停止程序,使用 ctrl + c 终止程序。

2、for循环

for item in sequence:expressions

item 是在for这里新定义的变量, sequence是之前定义好的数组/列表

example_list = [1,2,3,4,5,6,7,12,543,876,12,3,2,5]
for i in example_list:print(i)
1
2
3
4
5
6
7
12
543
876
12
3
2
5

python是一个使用缩进表示程序的结构,冒号后会自动缩进一个Tab

example_list = [1,2,3,4,5,6,7,12,543,876,12,3,2,5]
for i in example_list:print(i)print('inner of for')
print('outer of for')
1
inner of for
2
inner of for
3
inner of for
4
inner of for
5
inner of for
6
inner of for
7
inner of for
12
inner of for
543
inner of for
876
inner of for
12
inner of for
3
inner of for
2
inner of for
5
inner of for
outer of for

三、判断

1、if判断

if condition:expressions
x = 1
y = 2
z = 3
if x < y:print('x is less than y')
x is less than y
if x < y < z:print('x is less than y, and y is less than z')
x is less than y, and y is less than z

python特有的写法,意思是x < y and y < z,最好不要这么写。

注意:==是判断,=是赋值

2、if else判断

if condition:true_expressions
else:false_expressions
x = 1
y = 2
z = 3
if x > y:print('x is greater than y')
else:print('x is less or equal to y')
x is less or equal to y
  • python没有三目操作符(condition ? value1 : value2),可以用如下方式实现:
var= var1 if condition else var2
worked = True
result = 'done' if worked else 'not yet'
print(result)
done

3、if elif else判断

if condition1:true1_expressions
elif condition2:true2_expressions
elif condtion3:true3_expressions
elif ......
else:else_expressions
x = 4
y = 2
z = 3
if x > 1:print ('x > 1')
elif x < 1:print('x < 1')
else:print('x = 1')
print('finish')
x > 1
finish
  • 区别就是else if 写成了elif,注意每个结尾的:

四、函数

1、def函数

def function_name(parameters):expressions
def function():print('This is a function')a = 1+2print(a)
function()
This is a function
3

2、特定参数——需要传参

def function_name(parameters):expressions
def func(a, b):c = a+bprint('the c is ', c)
func(1, 2)
the c is  3

3、默认参数——需要指定值

def function_name(para_1,...,para_n=defau_n,..., para_m=defau_m):expressions
def sale_car(price, color='red', brand='carmy', is_second_hand=True):print('price', price,'color', color,'brand', brand,'is_second_hand', is_second_hand,)
sale_car(100)
price 100 color red brand carmy is_second_hand True

4、进阶

4.1 自调用

if __name__ == '__main__':#code_here

这里的code可以写入该函数的测试代码,当脚本被执行时,if判断为true,执行测试代码;当外部调用该脚本,if判断为false,不执行测试代码。

4.2 可变参数——*var

可变参数是指可迭代参数,避免了对于list的传参,写的时候放在特定参数和默认参数之后。

def report(name, *grades):total_grade = 0for grade in grades:total_grade += gradeprint(name, 'total grade is ', total_grade)report('Mike', 8, 9, 10)
Mike total grade is  27

4.3 关键字参数——**var

关键字参数可以传入0个或者任意个含参数名的参数,这些参数名在函数定义中并没有出现,这些参数在函数内部自动封装成一个字典(dict).写的时候放在所有参数最最后。

def portrait(name, **kw):print('name is', name)for k,v in kw.items():print(k, v)portrait('Mike', age=24, country='China', education='bachelor')
name is Mike
age 24
country China
education bachelor
  • 通过可变参数和关键字参数,任何函数都可以用 universal_func(*args, **kw) 表达

五、全局&局部变量

1、局部变量

def函数中定义的变量就是局部变量,只能在函数中使用

2、全局变量

那如何在外部也能调用一个在局部里修改了的全局变量呢. 首先我们在外部定义一个全局变量 a=None, 然后再 fun() 中声明 这个 a 是来自外部的 a. 声明方式就是 global a. 然后对这个外部的 a 修改后, 修改的效果会被施加到外部的 a 上.

APPLE = 100 # 全局变量
a = None
def fun():global a    # 使用之前在全局里定义的 aa = 20      # 现在的 a 是全局变量了return a+100print(APPLE)    # 100
print('a past:', a)  # None
b=fun()
print('a now:', a)   # 20
print(b)
100
a past: None
a now: 20
120

六、模块安装

外部模块就是在你 import 什么东西去python 脚本的时候会用到的.
安装语句:pip install 模块名
更新语句:pip install -u 模块名

七、读写文件

1、换行命令——\n

text='This is my first test.\nThis is the second line.\nThis the third line'
print(text)   # 输入换行命令\n,要注意斜杆的方向。注意换行的格式和c++一样
This is my first test.
This is the second line.
This the third line

2、open读文件方式——w的形式打开文件

open 的第一个参数为文件名和路径 ‘my file.txt’, 第二个参数为将要以什么方式打开它, 比如 w 为可写方式. 如果计算机没有找到 ‘my file.txt’ 这个文件, w 方式能够创建一个新的文件, 并命名为 my file.txt

my_file=open('my file.txt','w')   #用法: open('文件名','形式'), 其中形式有'w':write;'r':read.
my_file.write(text)               #该语句会写入先前定义好的 text
my_file.close()                   #关闭文件

3、tab对齐——\t

text='\tThis is my first test.\n\tThis is the second line.\n\tThis is the third line'
print(text)  #延伸 使用 \t 对齐
 This is my first test.This is the second line.This is the third line

4、给文件增加内容——a的形式打开文件

append_text='\nThis is appended file.'  # 为这行文字提前空行 "\n"
my_file=open('my file.txt','a')   # 'a'=append 以增加内容的形式打开
my_file.write(append_text)
my_file.close()

5、读取文件内容——r的形式打开文件

file= open('my file.txt','r')
content=file.read()
print(content)
This is my first test.
This is the second line.
This the third line
This is appended file.

5.1 按行读取

file= open('my file.txt','r')
content=file.readline()  # 读取第一行
print(content)
This is my first test.

5.2 读取所有行

file= open('my file.txt','r')
content=file.readlines() # python_list 形式
print(content)
['This is my first test.\n', 'This is the second line.\n', 'This the third line\n', 'This is appended file.']

八、class类

class后面可以定义属性、函数

  • class 定义的类名称建议首字母大写
class Calculator:       #首字母要大写,冒号不能缺name='Good Calculator'  #该行为class的属性price=18def add(self,x,y):print(self.name)result = x + yprint(result)def minus(self,x,y):result=x-yprint(result)def times(self,x,y):print(x*y)def divide(self,x,y):print(x/y)
cal=Calculator()
cal.name
'Good Calculator'
  • 注意,调用类要加()
cal.price
18
cal.add(10,20)
Good Calculator
30
cal.minus(10,20)
-10
cal.times(10,20)
200
cal.divide(10,20)
0.5

init功能

__init__可以理解成初始化class的变量,取自英文中initial 最初的意思.可以在运行时,给初始值附值:

class Calculator:name='good calculator'price=18def __init__(self,name,price,height,width,weight):   # 注意,这里的下划线是双下划线self.name=nameself.price=priceself.h=heightself.wi=widthself.we=weight
c=Calculator('bad calculator',18,17,16,15)
c.name
'bad calculator'
c.price
18
c.h
17
c.wi
16
c.we
15

设置属性的默认值, 直接在def里输入即可,如下:

class Calculator:name='good calculator'price=18def __init__(self,name,price,hight=10,width=14,weight=16): #后面三个属性设置默认值,查看运行self.name=nameself.price=priceself.h=hightself.wi=widthself.we=weight

九、input输入

variable=input() 表示运行后,可以在屏幕中输入一个数字,该数字会赋值给自变量。

a_input=input('please input a number:')
print('this number is:',a_input)
please input a number:1
this number is: 1
  • 当input的值需要if做判断时,注意定义input的类型。
a_input=int(input('please input a number:'))#注意这里要定义一个整数型
if a_input==1:print('This is a good one')
elif a_input==2:print('See you next time')
else:print('Good luck')
please input a number:2
See you next time
score=int(input('Please input your score: \n'))
if score>=90:print('Congradulation, you get an A')
elif score >=80:print('You get a B')
elif score >=70:print('You get a C')
elif score >=60:print('You get a D')
else:print('Sorry, You are failed ')
Please input your score:
99
Congradulation, you get an A

十、元组、列表、字典

1、Tuple

叫做 tuple,用小括号、或者无括号来表述,是一连串有顺序的数字。

a_tuple = (12, 3, 5, 15 , 6)
another_tuple = 12, 3, 5, 15 , 6

2、List

而list是以中括号来命名的:

a_list = [12, 3, 67, 7, 82]

两者对比

* 他们的元素可以一个一个地被迭代、输出、运用、定位取值:
for content in a_list:print(content)
12
3
67
7
82
for content_tuple in a_tuple:print(content_tuple)
12
3
5
15
6
for index in range(len(a_list)):print("index = ", index, ", number in list = ", a_list[index])
index =  0 , number in list =  12
index =  1 , number in list =  3
index =  2 , number in list =  67
index =  3 , number in list =  7
index =  4 , number in list =  82
for index in range(len(a_tuple)):print("index = ", index, ", number in tuple = ", a_tuple[index])
index =  0 , number in tuple =  12
index =  1 , number in tuple =  3
index =  2 , number in tuple =  5
index =  3 , number in tuple =  15
index =  4 , number in tuple =  6

2.1 List添加

a = [1,2,3,4,1,1,-1]
a.append(0)  # 在a的最后面追加一个0
print(a)
[1, 2, 3, 4, 1, 1, -1, 0]
a = [1,2,3,4,1,1,-1]
a.insert(1,0) # 在位置1处添加0
print(a)
[1, 0, 2, 3, 4, 1, 1, -1]

2.2 List移除

a = [1,2,3,4,1,1,-1]
a.remove(2) # 删除列表中第一个出现的值为2的项
print(a)
[1, 3, 4, 1, 1, -1]

2.3 List索引

a = [1,2,3,4,1,1,-1]
print(a[0])  # 显示列表a的第0位的值
# 1print(a[-1]) # 显示列表a的最末位的值
# -1print(a[0:3]) # 显示列表a的从第0位 到 第2位(第3位之前) 的所有项的值
# [1, 2, 3]print(a[5:])  # 显示列表a的第5位及以后的所有项的值
# [1, -1]print(a[-3:]) # 显示列表a的倒数第3位及以后的所有项的值
# [1, 1, -1]
1
-1
[1, 2, 3]
[1, -1]
[1, 1, -1]
  • tips:索引位数是从0开始的

打印例表中某个值的索引

a = [1,2,3,4,1,1,-1]
print(a.index(2)) # 显示列表a中第一次出现的值为2的项的索引
1

统计列表中某值出现的次数

a = [4,1,2,3,4,1,1,-1]
print(a.count(-1))
1

2.4 List排序——.sort()

a = [4,1,2,3,4,1,1,-1]
a.sort() # 默认从小到大排序
print(a)
# [-1, 1, 1, 1, 2, 3, 4, 4]a.sort(reverse=True) # 从大到小排序
print(a)
# [4, 4, 3, 2, 1, 1, 1, -1]
[-1, 1, 1, 1, 2, 3, 4, 4]
[4, 4, 3, 2, 1, 1, 1, -1]

3、多维列表

3.1 创建二维列表

a = [1,2,3,4,5] # 一行五列multi_dim_a = [[1,2,3],[2,3,4],[3,4,5]] # 三行三列

3.2 索引

print(a[1])
# 2print(multi_dim_a[0][1])
# 2
2
2

4、字典

  • 如果说List是有顺序地输出输入的话,那么字典的存档形式则是无需顺序的。

  • 在字典中,有key和 value两种元素,每一个key对应一个value, key是名字, value是内容。

  • 数字和字符串都可以当做key或者value, 在同一个字典中, 并不需要所有的key或value有相同的形式。

  • 这样说, List 可以说是一种key维有序数列的字典。

4.1 创建字典

a_list = [1,2,3,4,5,6,7,8]d1 = {'apple':1, 'pear':2, 'orange':3}
d2 = {1:'a', 2:'b', 3:'c'}
d3 = {1:'a', 'b':2, 'c':3}print(d1['apple'])  # 1
print(a_list[0])    # 1del d1['pear']  # 删除pear
print(d1)   # {'orange': 3, 'apple': 1}d1['b'] = 20  # 没有d1中没有b,就直接创建
print(d1)   # {'orange': 3, 'b': 20, 'apple': 1}   发现没?无序的!
1
1
{'apple': 1, 'orange': 3}
{'apple': 1, 'orange': 3, 'b': 20}

4.2 字典存储类型

以上的例子可以对列表中的元素进行增减。在打印出整个列表时,可以发现各个元素并没有按规律打印出来,进一步验证了字典是一个无序的容器。

def func():return 0d4 = {'apple':[1,2,3], 'pear':{1:3, 3:'a'}, 'orange':func}
print(d4['pear'][3])    # a
a

十一、模块

1、import载入模块

  • 方法一:import 模块名:python自带或自己安装的

  • 方法二:import 模块名 as 自定义名

  • from 模块名 import 模块名.功能名:只导入想要的功能

  • from 模块名 import * :导入该模块所有功能

2、自己的模块

  • 自建一个模块:模块写好后保存在一个文件夹,eg.balance.py
  • 调用自己的模块:eg.import balance

其他

1、continue & break

  • 跳出循环 - 执行完当前循环后结束循环
a=True
while a:b= input('type somesthing')if b=='1':a= Falseelse:passprint("still in while")
print ('finish run')
type somesthing1
still in while
finish run
  • break - 直接结束循环
while True:b= input('type somesthing:')if b=='1':breakelse:passprint('still in while')
print ('finish run')
type somesthing:1
finish run
  • continue - 跳过当前循环进入下一次
while True:b=input('input somesthing:')if b=='1':continueelse:passprint('still in while' )print ('finish run')
input somesthing:1
input somesthing:2
still in while
input somesthing:3
still in while

2、try错误处理

  • 输出错误
try:file=open('eeee.txt','r')  #会报错的代码
except Exception as e:  # 将报错存储在 e 中print(e)
  • 处理错误

会使用到循环语句。首先报错:没有这样的文件No such file or directory. 然后决定是否输入y, 输入y以后,系统就会新建一个文件(要用写入的类型),再次运行后,文件中就会写入ssss

try:file=open('eeee.txt','r+')
except Exception as e:print(e)response = input('do you want to create a new file:')if response=='y':file=open('eeee.txt','w')else:pass
else:file.write('ssss')file.close()

3、zip lambda map

  • zip - zip函数接受任意多个(包括0个和1个)序列作为参数,合并后返回一个tuple列表。
a=[1,2,3]
b=[4,5,6]
ab=zip(a,b)
print(list(ab))  #需要加list来可视化这个功能
for i,j in zip(a,b):print(i/2,j*2)
[(1, 4), (2, 5), (3, 6)]
0.5 8
1.0 10
1.5 12
  • lambda - ambda定义一个简单的函数,实现简化代码的功能,看代码会更好理解。

fun = lambda x,y : x+y, 冒号前的x,y为自变量,冒号后x+y为具体运算。

fun= lambda x,y:x+y
x=int(input('x='))    #这里要定义int整数,否则会默认为字符串
y=int(input('y='))
print(fun(x,y))
x=6
y=5
11
  • map - map是把函数和参数绑定在一起。
def fun(x,y):return (x+y)
list(map(fun,[1],[2]))
[3]
list(map(fun,[1,2],[3,4]))
[4, 6]

4、copy & deepcopy 浅复制 & 深复制

  • id - 一个对象的id值在CPython解释器里就代表它在内存中的`地址
import copy
a=[1,2,3]
b=a
id(a)
2216177872064
id(b)
2216177872064
b[0]=222222
print(a,b)  # ab的值会同时改变
[222222, 2, 3] [222222, 2, 3]
  • 浅拷贝 - 当使用浅拷贝时,python只是拷贝了最外围的对象本身,内部的元素都只是拷贝了一个引用而已。
import copy
a =[1,2,3]
c=copy.copy(a) #拷贝了a的外围对象本身
print(c)
[1, 2, 3]
id(c)
2216177618560
id(a)
2216177645568
c[0]=222222
print(a,c) #a的值不改变
[1, 2, 3] [222222, 2, 3]
  • 深拷贝 - deepcopy对外围和内部元素都进行了拷贝对象本身,而不是对象的引用。
a=[1,2,[3,4]]  #第三个值为列表[3,4],即内部元素
d=copy.copy(a) #浅拷贝a中的[3,4]内部元素的引用,非内部元素对象的本身
id(a)==id(d)
False
id(a[2])==id(d[2])
True
a[2][0]=3333  #改变a中内部原属列表中的第一个值
d             #这时d中的列表元素也会被改变
[1, 2, [3333, 4]]
e=copy.deepcopy(a) #e为深拷贝了a
a[2][0]=333 #改变a中内部元素列表第一个的值
e[#因为时深拷贝,这时e中内部元素[]列表的值不会因为a中的值改变而改变
[1, 2, [3333, 4]]

5、Threading多线程

多线程 Threading 是一种让程序拥有分身效果. 能同时处理多件事情. 一般的程序只能从上到下一行行执行代码, 不过 多线程 (Threading) 就能打破这种限制. 让你的程序鲜活起来.
“把一个工作分成5人,5个人同时做一份工作”

6、multiprocessing多进程

我们在多线程 (Threading) 里提到过, 它是有劣势的, GIL 让它没能更有效率的处理一些分摊的任务. 而现在的电脑大部分配备了多核处理器, 多进程 Multiprocessing 能让电脑更有效率的分配任务给每一个处理器, 这种做法解决了多线程的弊端. 也能很好的提升效率.

7、tkinter窗口

Tkinter 是使用 python 进行窗口视窗设计的模块. 简单的构造, 多平台, 多系统的兼容性, 能让它成为让你快速入门定制窗口文件的好助手. 它在 python 窗口视窗模块中是一款简单型的. 所以用来入门, 熟悉 窗口视窗的使用, 非常有必要.

8、pickle保存数据

pickle 是一个 python 中, 压缩/保存/提取 文件的模块. 最一般的使用方式非常简单. 比如下面就是压缩并保存一个字典的方式. 字典和列表都是能被保存的.

import picklea_dict = {'da': 111, 2: [23,1,4], '23': {1:2,'d':'sad'}}# pickle a variable to a file
file = open('pickle_example.pickle', 'wb')
pickle.dump(a_dict, file)
file.close()

9、set找不同

Set 最主要的功能就是寻找一个句子或者一个 list 当中不同的元素.

char_list = ['a', 'b', 'c', 'c', 'd', 'd', 'd']
sentence = 'Welcome Back to This Tutorial'
print(set(char_list))
{'b', 'd', 'c', 'a'}
print(set(sentence))
{'e', 'W', 'i', 'B', 'c', 'm', 't', 'o', 's', 'r', ' ', 'u', 'l', 'T', 'k', 'a', 'h'}
print(set(char_list+ list(sentence)))
{'r', 'e', 'i', 'B', 'm', 'b', 'k', 'c', 't', 's', ' ', 'u', 'l', 'T', 'W', 'o', 'd', 'a', 'h'}
unique_char = set(char_list)
print(unique_char.difference({'a', 'e', 'i'}))
{'b', 'd', 'c'}

10、正则表达式

正则表达式 (Regular Expression) 又称 RegEx, 是用来匹配字符的一种工具. 在一大串字符中寻找你需要的内容. 它常被用在很多方面, 比如网页爬虫, 文稿整理, 数据筛选等等.

  • 简单的匹配
# matching string
pattern1 = "cat"
pattern2 = "bird"
string = "dog runs to cat"
print(pattern1 in string)    # True
print(pattern2 in string)    # False
True
False
import re# regular expression
pattern1 = "cat"
pattern2 = "bird"
string = "dog runs to cat"
print(re.search(pattern1, string))  # 12-15是cat
print(re.search(pattern2, string))  # None
<re.Match object; span=(12, 15), match='cat'>
None
  • 灵活匹配
# multiple patterns ("run" or "ran")
ptn = r"r[au]n"       # start with "r" means raw string  [au]表示两种都可以
print(re.search(ptn, "dog runs to cat"))
<re.Match object; span=(4, 7), match='run'>
print(re.search(r"r[A-Z]n", "dog runs to cat"))     # None
print(re.search(r"r[a-z]n", "dog runs to cat"))     # <_sre.SRE_Match object; span=(4, 7), match='run'>
print(re.search(r"r[0-9]n", "dog r2ns to cat"))     # <_sre.SRE_Match object; span=(4, 7), match='r2n'>
print(re.search(r"r[0-9a-z]n", "dog runs to cat"))  # <_sre.SRE_Match object; span=(4, 7), match='run'>
None
<re.Match object; span=(4, 7), match='run'>
<re.Match object; span=(4, 7), match='r2n'>
<re.Match object; span=(4, 7), match='run'>
  • 按类型匹配

除了自己定义规则, 还有很多匹配的规则时提前就给你定义好了的. 下面有一些特殊的匹配类型给大家先总结一下, 然后再上一些例子.

\d : 任何数字
\D : 不是数字
\s : 任何 white space, 如 [\t\n\r\f\v]
\S : 不是 white space
\w : 任何大小写字母, 数字和 _ [a-zA-Z0-9_]
\W : 不是 \w
\b : 空白字符 (只在某个字的开头或结尾)
\B : 空白字符 (不在某个字的开头或结尾)
\\ : 匹配 \
. : 匹配任何字符 (除了 \n)
^ : 匹配开头
$ : 匹配结尾
? : 前面的字符可有可无
# \d : decimal digit
print(re.search(r"r\dn", "run r4n"))
# \D : any non-decimal digit
print(re.search(r"r\Dn", "run r4n"))
# \s : any white space [\t\n\r\f\v]
print(re.search(r"r\sn", "r\nn r4n"))
# \S : opposite to \s, any non-white space
print(re.search(r"r\Sn", "r\nn r4n"))
# \w : [a-zA-Z0-9_]
print(re.search(r"r\wn", "r\nn r4n"))
# \W : opposite to \w
print(re.search(r"r\Wn", "r\nn r4n"))
# \b : empty string (only at the start or end of the word)
print(re.search(r"\bruns\b", "dog runs to cat"))
# \B : empty string (but not at the start or end of a word)
print(re.search(r"\B runs \B", "dog   runs  to cat"))
# \\ : match \
print(re.search(r"runs\\", "runs\ to me"))
# . : match anything (except \n)
print(re.search(r"r.n", "r[ns to me"))
# ^ : match line beginning
print(re.search(r"^dog", "dog runs to cat"))
# $ : match line ending
print(re.search(r"cat$", "dog runs to cat"))
print(re.search(r"Mon(day)?", "Monday"))
print(re.search(r"Mon(day)?", "Mon"))
<re.Match object; span=(4, 7), match='r4n'>
<re.Match object; span=(0, 3), match='run'>
<re.Match object; span=(0, 3), match='r\nn'>
<re.Match object; span=(4, 7), match='r4n'>
<re.Match object; span=(4, 7), match='r4n'>
<re.Match object; span=(0, 3), match='r\nn'>
<re.Match object; span=(4, 8), match='runs'>
<re.Match object; span=(5, 11), match=' runs '>
<re.Match object; span=(0, 5), match='runs\\'>
<re.Match object; span=(0, 3), match='r[n'>
<re.Match object; span=(0, 3), match='dog'>
<re.Match object; span=(12, 15), match='cat'>
<re.Match object; span=(0, 6), match='Monday'>
<re.Match object; span=(0, 3), match='Mon'>

如果一个字符串有很多行, 我们想使用 ^ 形式来匹配行开头的字符, 如果用通常的形式是不成功的. 比如下面的 I 出现在第二行开头, 但是使用 r"^I" 却匹配不到第二行, 这时候, 我们要使用 另外一个参数, 让 re.search() 可以对每一行单独处理. 这个参数就是 flags=re.M, 或者这样写也行 flags=re.MULTILINE.

string = """
dog runs to cat.
I run to dog.
"""
print(re.search(r"^I", string))                 # None
print(re.search(r"^I", string, flags=re.M))     # <_sre.SRE_Match object; span=(18, 19), match='I'>
None
<re.Match object; span=(18, 19), match='I'>
  • 重复匹配

如果我们想让某个规律被重复使用, 在正则里面也是可以实现的, 而且实现的方式还有很多. 具体可以分为这三种:

*: 重复零次或多次
+: 重复一次或多次
{n, m} : 重复 n 至 m 次
{n} : 重复 n 次
# * : occur 0 or more times
print(re.search(r"ab*", "a"))             # <_sre.SRE_Match object; span=(0, 1), match='a'>
print(re.search(r"ab*", "abbbbb"))        # <_sre.SRE_Match object; span=(0, 6), match='abbbbb'># + : occur 1 or more times
print(re.search(r"ab+", "a"))             # None
print(re.search(r"ab+", "abbbbb"))        # <_sre.SRE_Match object; span=(0, 6), match='abbbbb'># {n, m} : occur n to m times
print(re.search(r"ab{2,10}", "a"))        # None
print(re.search(r"ab{2,10}", "abbbbb"))   # <_sre.SRE_Match object; span=(0, 6), match='abbbbb'>
<re.Match object; span=(0, 1), match='a'>
<re.Match object; span=(0, 6), match='abbbbb'>
None
<re.Match object; span=(0, 6), match='abbbbb'>
None
<re.Match object; span=(0, 6), match='abbbbb'>
  • 分组
match = re.search(r"(\d+), Date: (.+)", "ID: 021523, Date: Feb/12/2017")
#()表示组,\d表示找数字,+表示重复,然后找Date后面所有内容
print(match.group())                   # 021523, Date: Feb/12/2017
print(match.group(1))                  # 021523
print(match.group(2))                  # Date: Feb/12/2017
021523, Date: Feb/12/2017
021523
Feb/12/2017
match = re.search(r"(?P<id>\d+), Date: (?P<date>.+)", "ID: 021523, Date: Feb/12/2017")
# ?P<名字> 就给这个组定义了一个名字. 然后就能用这个名字找到这个组的内容.
print(match.group('id'))                # 021523
print(match.group('date'))              # Date: Feb/12/2017
021523
Feb/12/2017
  • findall

前面我们说的都是只找到了最开始匹配上的一项而已, 如果需要找到全部的匹配项, 我们可以使用 findall 功能. 然后返回一个列表.

# findall
print(re.findall(r"r[ua]n", "run ran ren"))    # ['run', 'ran']# | : or
print(re.findall(r"(run|ran)", "run ran ren")) # ['run', 'ran']  |是或
['run', 'ran']
['run', 'ran']
  • replace
print(re.sub(r"r[au]ns", "catches", "dog runs to cat"))     # dog catches to cat
dog catches to cat
  • split
print(re.split(r"[,;\.]", "a;b,c.d;e"))             # ['a', 'b', 'c', 'd', 'e']
['a', 'b', 'c', 'd', 'e']

比如想获取一句话中所有的单词. 比如 “a is b”.split(" "), 这样它就会产生一个列表来保存所有单词.

  • compile - 将正则定义一个变量,可以重复使用
compiled_re = re.compile(r"r[ua]n")
print(compiled_re.search("dog ran to cat"))  # <_sre.SRE_Match object; span=(4, 7), match='ran'>
<re.Match object; span=(4, 7), match='ran'>

mofan-python基础学习笔记相关推荐

  1. Python基础学习笔记三

    Python基础学习笔记三 print和import print可以用,分割变量来输出 import copy import copy as co from copy import deepcopy ...

  2. Python基础学习笔记之(二)

    Python基础学习笔记之(二) zouxy09@qq.com http://blog.csdn.net/zouxy09 六.包与模块 1.模块module Python中每一个.py脚本定义一个模块 ...

  3. Python基础学习笔记之(一)

    Python基础学习笔记之(一) zouxy09@qq.com http://blog.csdn.net/zouxy09 前段时间参加微软的windows Azure云计算的一个小培训,其中Pytho ...

  4. Python基础学习笔记(一)

    Python基础学习笔记(一) 基本数据类型   整型(int):1.2.10--   浮点型(float):1.2.2.4.10.00--   布尔型(bool):True.False   字符串( ...

  5. Python 基础学习笔记 03

    Python基础系列 Python 基础学习笔记 01 Python 基础学习笔记 02 Python 基础学习笔记 03 Python 基础学习笔记 04 Python 基础学习笔记 05 文章目录 ...

  6. 8.Python基础学习笔记day8-正则表达式、网络编程、进程与线程

    8.Python基础学习笔记day8-正则表达式.网络编程.进程与线程 一.正则表达式 ''' 1. [1,2,3,4]中任意取3个元素排列: A43 = 4x3x2 = 24itertools.pe ...

  7. python笔记基础-python基础学习笔记(一)

    安装与运行交互式解释器 在绝大多数linux和 UNIX系统安装中(包括Mac OS X),Python的解释器就已经存在了.我们可以在提示符下输入python命令进行验证(作者环境ubuntu) f ...

  8. python基础学习笔记(九)

    python异常 python用异常对象(exception object)来表示异常情况.遇到错误后,会引发异常.如果异常对象并未被处理或捕捉,程序就会用所谓的 回溯(Traceback, 一种错误 ...

  9. Python基础学习笔记:匿名函数

    匿名函数 匿名函数就是不需要显示式的指定函数名 首先看一行代码: def calc(x,y):return x*y print(calc(2,3))# 换成匿名函数calc = lambda x,y: ...

  10. Python基础学习笔记:异常处理与断言(assertions)的运用

    python 提供了两个重要的功能来处理 python 程序在运行中出现的异常和错误: 异常处理 断言(assertions) 1.异常处理 捕捉异常可以使用 try/except 语句. try/e ...

最新文章

  1. c#百度排名点击器编写 及webser 填表.
  2. Eclipse启动项目时,删除workspaces无用的工作区间
  3. mysql 实体关系表_实体关系图
  4. CDS view里case - when - else关键字的用法
  5. C++中事件机制的简洁实现
  6. envs\TensorFlow2.0\lib\site-packages\tensorflow\python\framework\dtypes.py:516: FutureWarning 解决方案
  7. CISCO ASA 5510 防火墙的配置实例
  8. 【shell编程基础0】bash shell编程的基本配置
  9. Atitit 号码规范 靓号指南 attilax总结 v4 r926.docx
  10. 我是一只IT小小鸟(转载)
  11. TeamViewer(TV)锁屏后黑屏无法远程的解决方法
  12. 一个下载网页视频的方法
  13. 命令改计算机用户名和密码,利用NET命令添加、修改用户账户信息
  14. linux下类everthing搜索工具
  15. 三种经典网页音乐播放器
  16. php微信商家转账到零钱 发起商家转账API
  17. Win11无线网络适配器有感叹号不能上网怎么解决
  18. 工程材料学习3——第二章 金属材料组织和性能的控制(2.1 纯金属的结晶 2.2 合金的结晶)
  19. “黑客帝国”只是另一个幻想,但我们痴迷于此
  20. python新闻爬虫系统的功能_基于Scrapy框架的Python新闻爬虫

热门文章

  1. 【宝信IPLAT4J.V6】表格Grid的标题行合并和列合并写法
  2. 黑马程序员——JAVA基础——集合
  3. Pheonix Service Software 2011.14.004.45945 Cracked Original
  4. 钓鱼工具gophish详细教程
  5. Java_百度人脸识别登录
  6. 让AI 作画更快一点
  7. fatal: unable to access ‘https://github.com/xxxx.git/‘: Failed to connect to github.com port 443: T
  8. vue修改浏览器标签名的办法
  9. onkeydown,onkeyup,onkeypress,onclick,ondblclick
  10. 关于使用MyBatis逆向工程生成器把其他数据库的同名表生成下来的问题(Table Configuration xxx matched more than one table (xxx,xxx))