Python

输出(打印)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
print(520)
print(114514)
print('helloworld')

# 将数据输出文件中
fp = open('D:/text.txt', 'a+')
print('hello world', file=fp)
fp.close()


name = '玛利亚'
print(name)
print('标识',id(name))
print('类型',type(name))
print('值',name)

n1=10086
n2=114514
n3=123
print(n1,type(n1))
print(n2,type(n2))
print(n3,type(n3))

转义字符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#   \是转义字符首字母
print('hello\nworld') # \n是newline的首字母,表示换行
print('hello\tworld') # \t是tab,空出4个字符位置,每四个字符为一组,不足4位补全4位
print('hellooo\tworld')
print('hello\rworld') # \r是replace,将光标定位到本行开头(当后面接内容后, 本行之前的内容会被清除掉)
print('hello\bworld') # \b是退一个格,将o退没了

print('http:\\\\www.baidu.com') # 4个\\\\表示第一个\转义第二个\,第三个\转义第四个\
print('老师说:\'大家好\'')

#原字符,不希望字符串中的转义字符起作用,就是用原字符,就是在字符串之前加上r或者R
print(r'hello\nworld')

#注意事项,最后一个字符不能是反斜杠
#例如print(r'hello\nworld\')

类型转换

1
2
3
4
name = '张三'
age = 20
#print('我叫'+name+'今年'+age+'岁')
print('我叫'+name+'今年'+str(age)+'岁')#int类型和str类型无法直接连接,需要类型转换

input函数

1
2
3
4
5
#   input函数作用:接收来自用户的输入
# 返回值类型为str
# 值的存储:用户输入什么就存什么
present = input('小志想要什么礼物呢')
print(present,type(present))

input的进一步应用

1
2
3
4
5
#   从键盘上录入两个整数,计算两个整数的和
a = int(input('请输入一个加数'))
# 因为input使用str来存,而加法需要采用int或float,这里采用int()来强转
b = int(input('请输入另一个加数'))
print(a+b)

算数运算符

1
2
3
4
5
6
7
8
9
10
11
12
13
print(1+1)  #加法
print(1-1) #减法
print(2*4) #乘法
print(1/2) #除法

print(11//2)#整除运算,取整数部分,向下取整
print(9//-4)#-3,向下取整
print(-9//4)#-3,向下取整

print(11%2) #取余运算,取余数部分
print(9%-4) #-3,公式: 余数 = 被除数 - 除数 * 商 9-(-4)*(-3)=-3
print(-9%4) #3 -9-4*(-3)=3
print(2**3) #表示的是2的3次方

比较运算符

1
2
3
4
5
6
7
8
#   比较运算符,比较运算符的结果是bool类型
a,b=10,20
print('a>b吗',a>b)# False
print('a<b吗',a<b)# True
print('a<=b吗',a<=b)#True
print('a>=b吗',a>=b)#False
print('a==b吗',a==b)#False
print('a!=b吗',a!=b)#True

多分支结构

1
2
3
4
5
6
7
8
9
10
11
12
score = int(input('请输入一个成绩:'))
# 判断
if 90<=score<=100:
print('A级')
elif 80<=score<=89:
print('B级')
elif 70<=score<=79:
print('C级')
elif 0<=score<=69:
print('芜湖!给我狠狠的挂科!')
else:
print('好死!')

range函数的使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
r = range(10)#  [0,1,2,3,4,5,6,7,8,9],默认从0开始,步长为1
print(r)# range(0,10)
print(list(r))# 用于查看range对象的整数列

r = range(1,10)# 定义了起始值,从1开始,到10结束(不包含10),可以看作[1,10),步长为1
print(r)# range(1,10)
print(list(r))# 用于查看range对象的整数列

r = range(1,10,2)# 定义了起始值,从1开始,到10结束(不包含10),可以看作[1,10),步长为2
print(r)# range(1, 10, 2)
print(list(r))# 用于查看range对象的整数列,[1, 3, 5, 7, 9]

# 判断指定的整数在序列中是否存在,in , not in
print(10 in r)# False,10不在当前r的序列中
print(9 in r)# True,9在当前r的序列中

for _ in循环

1
2
3
4
5
6
7
8
9
10
11
for item in ('python'):
print(item)# 第一次取出来的是p,将p赋值给item,将item的值输出
# 依次输出python

# range()产生一个整数序列,也是一个可迭代对象
for i in range(10):
print(i)# 依次输出0123456789

# 如果在循环体中不需要用到循环变量,可以将自定义变量写为_
for _ in range(5):
print('这技术爱谁学谁学吧,老子不干了,开摆!')# 把这句话输出5遍

else语句

if … else 是if条件表达式不成立时执行else

while …else 和for …else是没有碰到break时执行

列表

列表是可变序列,可以向列表中添加元素,而列表的内存地址不变

1.创建列表的第一种方式,使用 [ ]

1
2
3
4
5
6
#   创建列表的第一种方式,使用[]
lst=['好想摆烂','怎么一直在睡觉','为什么一定要去打暑假工','是嫌弃以后的打工时间不够长?']
print(lst)# 输出列表
print(lst[0])# 列表索引从左到右为从0开始,0,1,2,3
print(lst[-1])# 当然也可以从右到左从-1开始,-1,-2,-3,-4
print(lst[0],lst[2])

2.创建列表的第二种方式,使用内置函数 list()

1
2
3
4
5
6
7
8
9
#   创建列表的第二种方式,使用内置函数list()
lst2=list(['好想摆烂','怎么一直在睡觉','为什么一定要去打暑假工','是嫌弃以后的打工时间不够长?'])
print(lst)# 输出列表
print(lst[0])# 列表索引从左到右为从0开始,0,1,2,3
print(lst[-1])# 当然也可以从右到左从-1开始,-1,-2,-3,-4
print(lst[0],lst[2])

print(lst.index('好想摆烂'))# 如果列表中有相同元素只返回列表中的相同元素的第一个元素的索引
print(lst.index('为什么一定要去打暑假工',0,4))# [0,4),在列表的这个范围内找'为什么一定要去打暑假工'的具体位置

获取列表中的多个元素,切片操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
lst=[10,20,30,40,50,60,70,80]
# 这里先打印原列表方便对照
print('原列表',lst)

# 然后截取片段
# start=1,stop=6,step=1,相当于[1,6),步长为1
lst2=lst[1:6:1]
print('截取的片段,步长为1',lst2)# 截取的片段,步长为1 [20, 30, 40, 50, 60]

# start=1,stop=6,step=2,相当于[1,6),步长为2
lst3=lst[1:6:2]
print('截取的片段,步长为2',lst3)# 截取的片段,步长为2 [20, 40, 60]

# 省略step,默认step=1,步长为1
lst4=lst[1:6:]
print('截取的片段,没写step,默认为1',lst4)# 截取的片段,没写step,默认为1 [20, 30, 40, 50, 60]

# 省略start,默认start为0,从0开始,stop=6,step=2,相当于[0,6),步长为2
lst5=lst[:6:2]
print('截取的片段,没写start,默认为0',lst5)# 截取的片段,没写start,默认为0 [10, 30, 50]

# 省略stop,默认stop为
lst6=lst[1::2]
print('截取的片段,没写stop,默认为最大',lst6)# 截取的片段,没写stop,默认为最大 [20, 40, 60, 80]

print('------------------------step为负数的情况----------------------------')

# 这里先打印原列表方便对照
print('原列表',lst)# 原列表 [10, 20, 30, 40, 50, 60, 70, 80]
print('step=-1',lst[::-1])# step=-1 [80, 70, 60, 50, 40, 30, 20, 10]
print(lst[6:0:-2])# 从左到右0123456,也就说是第7位,往左边跑,步数为2
# [70, 50, 30]

列表元素的判断以及遍历

1
2
3
4
5
6
7
8
#判断列表中的元素是否存在
lst=[10,20,30,40,50,60,70,80]
print(10 in lst)# True
print(10086 in lst)# False

# 遍历列表中的元素
for item in lst:
print(item)

列表元素的增删改查

append
1
2
3
4
5
6
7
lst=[10,20,30]
# append()在列表的末尾添加一个元素
lst.append(10086)
print('append 添加元素后',lst)
lst2=['hello','world']
lst.append(lst2)# 把列表当成是一个元素添加到列表末尾
print('append 把列表当成是一个元素',lst)

添加元素前 [10, 20, 30]
append 添加元素后 [10, 20, 30, 10086]
append 把列表当成是一个元素 [10, 20, 30, 10086, [‘hello’, ‘world’]]

extend
1
2
3
4
#   extend在列表的末尾至少添加一个元素
lst=[10,20,30]
lst.extend(lst2)
print('extend 向末尾添加多位元素',lst)

extend 向末尾添加多位元素 [10, 20, 30, ‘hello’, ‘world’]

insert
1
2
3
#   insert在任意地方添加一个元素
lst=[10,20,30]
lst.insert(1,114514)# 在列表索引为1的地方,添加一个元素为114514

insert 在任意地方添加一个元素 [10, 114514, 20, 30]

切片
1
2
3
4
5
6
#   切片在任意的位置上添加n多个元素
# 切片更像是把任意位置的元素替换掉
lst=[10,20,30]
lst3=['true','false']
lst[1:]=lst3# 从索引为1的地方开始,:后没写代表后面全部都要进行操作
print('切片 在任意的位置上添加n多个元素',lst)

切片 在任意的位置上添加n多个元素 [10, ‘true’, ‘false’]

remove
1
2
3
4
5
6
lst=[10,20,30,40,50,60,30]
print('原列表',lst)

# remove删除元素时,从列表中删除一个元素,如果有重复元素只删除第一个
lst.remove(30)
print('使用remove删除30',lst)

原列表 [10, 20, 30, 40, 50, 60, 30]
使用remove删除30 [10, 20, 40, 50, 60, 30]

pop
1
2
3
4
5
6
7
8
9
10
11
12
lst=[10,20,30,40,50,60,30]
print('原列表',lst)

# pop()根据索引移除元素
lst.pop(1)
print('使用pop删除索引位置为1的数',lst)

lst=[10,20,30,40,50,60,30]
print('原列表',lst)

lst.pop()# 如果不指定pop的参数(索引),将删除列表中的最后一个元素
print('没有指定pop的参数(索引)',lst)

原列表 [10, 20, 30, 40, 50, 60, 30]
使用pop删除索引位置为1的数 [10, 30, 40, 50, 60, 30]

原列表 [10, 20, 30, 40, 50, 60, 30]
没有指定pop的参数(索引) [10, 20, 30, 40, 50, 60]

切片
1
2
3
4
5
6
7
8
9
10
#   切片操作删除至少一个参数,将产生一个新的列表对象
lst2=lst[1:3]
print('采用切片操作',lst2)

lst=[10,20,30,40,50,60,30]
print('原列表',lst)

# 不产生新的列表对象,而是删除原列表中的内容
lst[1:3]=[]
print('切片操作的第二种',lst)

采用切片操作 [20, 30]
原列表 [10, 20, 30, 40, 50, 60, 30]
切片操作的第二种 [10, 40, 50, 60, 30]

clear
1
2
3
#   clear清空列表中的所有元素
lst.clear()
print(lst)

[ ]

del
1
2
3
#   del语句将列表对象删除
del lst
print(lst)

NameError: name ‘lst’ is not defined.

1
2
3
4
#   一次修改一个值
lst=[10,20,30,40]
lst[1:3]=[300,400,500]# 20,30被300,400,500替换
print(lst)

1
2
3
4
5
6
7
8
#判断列表中的元素是否存在
lst=[10,20,30,40,50,60,70,80]
print(10 in lst)# True
print(10086 in lst)# False

# 遍历列表中的元素
for item in lst:
print(item)

列表元素的排序操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#   开始排序,调用列表对象的sort方法,升序排序
lst=[20,40,66,33,78,96]
print('排序前的列表',lst)# 排序前的列表 [20, 40, 66, 33, 78, 96]
lst.sort()
print('排序后的列表',lst)# 排序后的列表 [20, 33, 40, 66, 78, 96]

# 通过指定关键字参数,将列表中的元素进行降序排序
lst.sort(reverse=True)# reverse=True表示降序排序,reverse=False就是升序排序
print('降序排序',lst)# 降序排序 [96, 78, 66, 40, 33, 20]
lst.sort(reverse=False)
print('升序排序',lst)# 升序排序 [20, 33, 40, 66, 78, 96]

print('---------------使用内置函数sort()对列表进行排序将产生一个新的列表对象--------------')
lst=[3,1,2,9,5,8,4,6,7]
new_list=sorted(lst)
print('原列表',lst)# 原列表 [3, 1, 2, 9, 5, 8, 4, 6, 7]
print('新列表',new_list)# 新列表 [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 指定关键字参数,实现列表元素的降序排序
desc_list=sorted(lst,reverse=True)
print('降序排序',desc_list)# 降序排序 [9, 8, 7, 6, 5, 4, 3, 2, 1]

列表生成式

1
2
3
4
5
6
#   列表生成式
lst=[i for i in range(1,10)]
print(lst)# [1, 2, 3, 4, 5, 6, 7, 8, 9]

lst=[i*i for i in range(1,10)]
print(lst)# [1, 4, 9, 16, 25, 36, 49, 64, 81]

字典

字典的创建方式

1.使用{ }来创建字典

1
2
3
#   使用{}来创建字典
scores={'张三':100,'李四':98,'王五':45}
print(scores)# {'张三': 100, '李四': 98, '王五': 45}

2.第二种创建dict

1
2
3
#   第二种创建dict
student=dict(name='jack',age=20)
print(student)# {'name': 'jack', 'age': 20}

获取字典的元素

1
2
3
4
5
6
7
8
9
#   获取字典的元素
scores={'张三':100,'李四':98,'王五':45}
print(scores['张三'])# 100

# 第二种方法,使用get()方法
print(scores.get('张三'))# 100
print(scores.get('桑你忒他'))# None
print(scores.get('模拟穹',99))# 99是在查找‘模拟穹’所对的value不存在时,提供的一个默认值

字典元素的增删改操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#   key的判断
scores={'张三':100,'李四':98,'王五':45}
print('张三' in scores)# True
print('张三' not in scores)# False

# 删除指定的key-value对
del scores['张三']
scores.clear()# 清空字典元素
print(scores)# {}

# 添加字典元素
scores['雷军']=98
print(scores)# {'李四': 98, '王五': 45, '雷军': 98},这里的结果是已经把上面的清空代码注释掉了

# 修改
scores['雷军']=10086
print(scores)# {'李四': 98, '王五': 45, '雷军': 10086}

获取字典的视图

keys() 获取所有的key

1
2
3
4
scores={'张三':100,'李四':98,'王五':45}
keys=scores.keys()
print(keys)# dict_keys(['张三', '李四', '王五'])
print(list(keys))# 将所有的key组成的视图转成列表 ['张三', '李四', '王五']

values() 获取所有的values

1
2
3
#   获取所有的value
values=scores.values()
print(values)# dict_values([100, 98, 45])

items() 获取所有的key-value对

1
2
3
#   获取所有的key-value对
items=scores.items()
print(items)# dict_items([('张三', 100), ('李四', 98), ('王五', 45)])

字典元素的遍历

1
2
3
4
5
#   字典元素的遍历
for items in scores:
print(items,scores[items],scores.get(items))
# scores[items],items是键,根据键获取值,此方法会抛异常。(当遍历的键不存在时,但很明显这不可能)
# scores.get(items)是使用get方法获取键,根据键获取值,这个不会抛异常,没有找到键顶多是None

字典的特点

1
2
3
4
5
6
7
8
9
#   字典的特点

# key不准重复
d={'name':'张三','name':'李四'}
print(d)# {'name': '李四'}

# values是可以重复的
d={'name':'张三','nikname':'张三'}
print(d)# {'name': '张三', 'nikname': '张三'}

字典生成式

内置函数zip()

用于将可迭代的对象作为参数,将对象中对应的元素打包成一个元祖,然后返回这些 元组 组成的 列表

1
2
3
4
5
6
7
8
9
10
11
12
13
items=['fruits','books','others']
prices=[96,78,85]# 列表[]

# 字典{}
d={single_item:single_price for single_item,single_price in zip(items,prices)}
# zip(items,prices)中的 items,prices 是被‘压缩’的对象
# for single_item,single_price in中的 single_item,single_price 是我们自己取的变量名
# single_item:single_price for for中的 single_item 是由for遍历出来的键 single_price是由for遍历来的值
print(d)# {'fruits': 96, 'books': 78, 'others': 85}

d={single_item.upper():single_price for single_item,single_price in zip(items,prices)}
# upper() 全部大写
print(d)# {'FRUITS': 96, 'BOOKS': 78, 'OTHERS': 85}

元组

Python内置的数据结构之一,是一个不可变序列,不允许修改元素

不可变序列和可变序列

不可变序列:字符串,元组 没有 增删改 操作

可变序列:列表,字典 可以对序列执行 增删改 操作,对象地址不发生改变

元组的创建方式

1.第一种创建方式,使用()

1
2
3
4
5
6
7
8
9
#   第一种创建方式,使用()
t=('python','hello',10086)
print(t)# ('python', 'hello', 10086)
print(type(t))# <class 'tuple'>元组

# 第一种创建方式也可以不写()
t1='python','hello',10086
print(t1)# ('python', 'hello', 10086)
print(type(t1))# <class 'tuple'>元组

2.第二种创建方式,使用内置函数tuple()

1
2
3
4
#   第二种创建方式,使用内置函数tuple()
t2=tuple(('python','hello',10086))
print(t2)# ('python', 'hello', 10086)
print(type(t2))# <class 'tuple'>元组

元组的核心判定:逗号

1
2
3
4
5
6
7
8
9
#   只包含一个元组的元素需要使用括号和逗号,逗号必须写,括号可以省略
t3='python',
print(t3)# ('python',)
print(type(t3))# <class 'tuple'>元组

# 没写逗号,判定为 str 类型
t4='python'
print(t4)# python
print(type(t4))# <class 'str'>

元组的遍历

1
2
3
4
5
6
7
#   元组的遍历
t=('python','hello',10086)
for item in t:
print(item)
'''python
hello
10086'''

集合

1.第一种创建方式使用{ }

1
2
3
#   第一种创建方式使用{}
s={1,2,2,7,4,4,7}
print(s)# {1, 2, 4, 7},集合当中的元素不允许重复

2.第二种创建方式使用set()

1
2
3
#   第二种创建方式使用set()
s1=set(range(6))
print(s1,type(s1))# {0, 1, 2, 3, 4, 5} <class 'set'>

集合当中的元素不允许重复

1
2
3
#   将列表当中的元素转成了集合
s2=set([1,2,2,7,4,4,7])
print(s2,type(s2))# {1, 2, 4, 7} <class 'set'>

集合中的元素是无序的

1
2
3
4
5
6
#   将元组类型的元素转化为集合类型的元素
s3=set((1,2,4,4,5,65,10086))# 集合中的元素是无序的
print(s3,type(s3))# {65, 1, 2, 4, 5, 10086} <class 'set'>

s4=set('python')
print(s4,type(s4))# 每次输出都是不同的顺序,证明集合中的元素是无序的

定义空集合

1
2
3
4
5
6
7
#   定义一个空集合
s5=set()
print(s5,type(s5))# set() <class 'set'>

# 定义空集合的错误做法
s6={}
print(s6,type(s6))# {} <class 'dict'>

集合元素的判断操作

1
2
3
4
5
#   集合元素的判断操作
s={1,10,123,10086}
print(1 in s)# True
print(1919810 in s)# False
print(114514 in s)# False

集合元素的新增操作

add

1
2
3
4
5
#   元素集合的新增操作
# 添加一个用add
s={1,10,123,10086}
s.add(80)
print(s)# {1, 10086, 10, 80, 123}

update

1
2
3
4
5
6
#   添加多个用update,一次至少添加一个元素
s.update({200,300,400})
print(s)
s.update([369,589,99])
s.update((147,56,76))
print(s)# {1, 99, 10086, 200, 10, 300, 589, 76, 80, 400, 369, 147, 56, 123}

集合元素的删除操作

remove

调用remove(),一次删除一个指定元素,如果指定的元素不存在就抛出异常KeyError

1
2
3
4
5
#	{1, 99, 10086, 200, 10, 300, 589, 76, 80, 400, 369, 147, 56, 123}
# 集合元素的删除操作
# 调用remove(),一次删除一个指定元素,如果指定的元素不存在就抛出异常KeyError
s.remove(200)# 如果集合里没有200这个元素,那么会抛出一个错误KeyError:200
print(s)# {1, 99, 10086, 10, 300, 589, 76, 80, 400, 369, 147, 56, 123}

discard

调用discard(),一次删除一个指定元素,如果指定的元素不存在也不抛异常

1
2
3
4
5
6
#   调用discard(),一次删除一个指定元素,如果指定的元素不存在也不抛异常
s.discard(10086)
print(s)# {1, 99, 10, 300, 589, 76, 80, 400, 369, 147, 56, 123}

s.discard(10087)# discard就不会有这种问题,有就删,没有也不报错
print(s)# {1, 99, 10, 300, 589, 76, 80, 400, 369, 147, 56, 123}

pop

调用pop(),一次只删除一个元素,删除最左边的元素,pop不能指定参数

1
2
3
4
5
6
7
#   调用pop(),一次只删除一个元素,删除最左边的元素
# {1, 99, 10, 300, 589, 76, 80, 400, 369, 147, 56, 123}
s.pop()
print(s)# {99, 10, 300, 589, 76, 80, 400, 369, 147, 56, 123}
s.pop()
print(s)# {10, 300, 589, 76, 80, 400, 369, 147, 56, 123}
# pop不能指定参数

clear

clear()清空所有的元素

1
2
3
#   clear()清空所有的元素
s.clear()
print(s)# set()

集合间的关系

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#   集合当中的元素是无序的,只要内容相同就相等
# 两个集合是否相等(元素相同就相等)
s1={1,2,3,4}
s2={4,3,2,1}
print(s1==s2)# True
print(s1!=s2)# False

# 一个集合是否是另一个集合的子集
s1={1,2,3,4,5,6}
s2={4,3,2,1}
s3={1,2,9}
print(s2.issubset(s1))# True
print(s3.issubset(s1))# False

# 一个集合是否是另一个集合的超集
# 超集,就是子集的反义词
print(s1.issuperset(s2))# True
print(s1.issuperset(s3))# False

# 两个集合是否有交集
print(s2.isdisjoint(s3))# False
s4={100,200,300}

print(s2.isdisjoint(s4))# True

集合的数据操作

交集

1
2
3
#   交集
print(s1.intersection(s2))
print(s1 & s2)

并集

1
2
3
#   并集
print(s1.union(s2))
print(s1|s2)

差集

1
2
3
#   差集(s1减去两者共有的部分)
print(s1.difference(s2))
print(s1-s2)

对称差集

1
2
3
#   对称差集(去掉中间相同的部分,s1和s2剩下的就是对称差集)
print(s1.symmetric_difference(s2))
print(s1^s2)

集合生成式

1
2
3
#   集合生成式
s={i*i for i in range(10)}
print(s)# {0, 1, 64, 4, 36, 9, 16, 49, 81, 25}

列表,元组,字典,集合总结

字符串

字符串的查询操作的方法

1
2
3
4
5
s='hello,hello'
print(s.index('lo'))# 3
print(s.find('lo'))# 3
print(s.rindex('lo'))# 9
print(s.rfind('lo'))# 9

字符串的大小写转换操作的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
s='hello,python'
a=s.upper()# 转写成功后,会产生一个新的字符串对象
print(a,id(a))# HELLO,PYTHON 1635209859120
print(s,id(s))# hello,python 1635209858416
b=s.lower()
print(b,id(b))# hello,python 1635209858352
print(s,id(s))# hello,python 1635209858416
print(b==s)# True
print(b is s)# False

s2='hello,python'
print(s2.swapcase())# HELLO,PYTHON
print(s2.title())# Hello,Python

字符串内容对齐操作的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
s='hello,python'

print('居中对齐')
print(s.center(20,'*'))# ****hello,python****

print('左对齐')
print(s.ljust(20,'*'))# hello,python********
print(s.ljust(10))# hello,python
print(s.ljust(20))# hello,python

print('右对齐')
print(s.rjust(20,'*'))# ********hello,python
print(s.rjust(10))# hello,python
print(s.rjust(20))# hello,python

字符串劈分操作的方法

1
2
3
4
5
6
7
8
9
10
11
12
s='hello world python'
lst=s.split()
print(lst)
s1='hello|world|python'
print(s1.split(sep='|'))# 以'|'来划分
print(s1.split(sep='|',maxsplit=1))

print('rsplit从右侧开始劈分')

print(s.rsplit())
print(s1.rsplit('|'))
print(s1.rsplit(sep='|',maxsplit=1))

判断字符串操作的方法

1
2
3
4
5
6
7
s='hello,python'
print('1.',s.isidentifier())# 1. False,合法的标识符是字母数字下划线
print('2.','hello'.isidentifier())# 2. True
print('3.','张三_'.isidentifier())# 3. True
print('4.','张三_123'.isidentifier())# 4. True

print('5.','\t'.isspace())# 5. True

字符串操作的其他方法

1
2
3
4
5
6
7
8
9
10
11
12
s='hello,python'
print(s.replace('python','嗨嗨嗨'))# 用 嗨嗨嗨 替换前面的 python
s1='hello,python,python,python'
print(s1.replace('python','嗨嗨嗨',2))# 用 嗨嗨嗨 替换前面的 python ,替换两次

lst=['hello','嗨嗨嗨','python']
print('|'.join(lst))# hello|嗨嗨嗨|python
print(''.join(lst))# hello嗨嗨嗨python

t=('hello','嗨嗨嗨','python')
print(''.join(t))# hello嗨嗨嗨python
print('*'.join('python'))# p*y*t*h*o*n

字符串的比较操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
print('apple'>'app')#   True
print('apple'>'banana')# False
print(ord('a'),ord('b'))# 97 98
print(chr(97),chr(98))# a b
# chr()和ord()是互补的
# ord()返回ASCII码

# ==和is的区别
# ==比较的是value
# is比较的是id是否相等
a=b='python'
c='python'
print(a==b)# True
print(b==c)# True
print(a is b)# True
print(b is c)# True
# 因为字符串的驻留机制,'python'只保留一份,a,b,c全是指向'python'同一块内存空间

字符串的切片操作

1
2
3
4
5
6
7
8
9
10
11
12
13
s='hello,python'
s1=s[:5]# 由于没有指定起始位置,所以从0开始切
s2=s[6:]# 由于没有指定结束位置,所以切到字符串的最后一个元素
s3='!'
newstr=s1+s3+s2

print(s1)
print(s2)
print(newstr)

print('完整写法')
print('-------------切片[start:end:step]--------------')
print(s[1:5:1])# 从1开始截到(不包含5),步长为1

格式化字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#   格式化字符串
# 1. % 占位符
name='张三'
age=20
print('我叫%s,今年%d岁'%(name,age))

# 2. {}
print('我叫{0},今年{1}岁'.format(name,age))

# f-string
print(f'我叫{name},今年{age}岁')

print('%10d'%99)# 10表示的是宽度
print('%f'%3.1415926)# 3.141593
print('%.3f'%3.1415926)# 3.142,保留三位小数,.3表示小数点后三位

# 同时表示宽度和精度
print('%10.3f'%3.1415926)

print('hellohello')

print('{0}'.format(3.1415926))# .3表示的是一共3位数

print('{:.3f}'.format(3.1415926))# .3f表示是3位小数

print('{:10.3f}'.format(3.1415926))# 同时设置宽度和精度,一共是10位,3位是小数

'''
我叫张三,今年20岁
我叫张三,今年20岁
我叫张三,今年20岁
99
3.141593
3.142
3.142
hellohello
3.1415926
3.142
3.142

进程已结束,退出代码0
'''

字符串的编码和解码

1
2
3
4
5
6
7
8
9
10
11
12
s='天涯共此时'
# 编码
print(s.encode(encoding='GBK'))
print(s.encode(encoding='UTF-8'))

# 解码
# byte代表就是一个二进制数据(字节类型的数据)
bytes=s.encode(encoding='GBK')# 编码
print(bytes.decode(encoding='GBK'))# 解码

bytes=s.encode(encoding='UTF-8')# 编码
print(bytes.decode(encoding='UTF-8'))# 解码

函数

函数的创建

1
2
3
4
5
6
def calc(a,b):
c=a+b
return c

result=calc(10,20)
print(result)# 30

函数的参数传递

1
2
3
4
5
6
7
8
9
def calc(a,b):# a,b称为形式参数,简称形参,形参的位置是在函数的定义处
c=a+b
return c

result=calc(10,20)# 10,20称为实际参数的值,简称实参,实参的位置是函数的调用处
print(result)# 30

res=calc(b=10,a=20)# = 左侧的变量的名称称为 关键字参数
print(res)

函数的返回值

函数的参数定义

默认值参数

个数可变的位置参数_个数可变的关键字形参

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def fun(*arg):
print(arg)
fun(10)
fun(10,20)
fun(10,20,30)

def fun1(**arg):
print(arg)
fun1(a=10)
fun1(a=10,b=20)
fun1(a=10,b=20,c=30)


def fun2(*arg,**a):
pass
'''
def fun2(*arg,*a):
pass
以上代码,程序会报错,个数可变的位置参数只能是1个
def fun3(**arg,**a):
pass
以上代码,程序会报错,个数可变的关键字参数只能是1个
def fun4(**arg,**a):
pass
在一个函数的定义过程中,既有个数可变的关键字形参,也有个数可变的位置形参,
要求,个数可变的位置形参,放在个数可变的关键字形参之前
'''

函数的参数总结

1
2
3
4
5
6
7
8
9
10
11
12
def fun(a,b,c):
print('a=',a)
print('b=',b)
print('c=',c)

# 函数的调用
fun(10,20,30)# 函数调用时的参数传递,称为位置传参
lst=[11,22,33]
fun(*lst)# 在函数调用时,将列表中的每个元素都转换为位置实参传入

fun(a=100,c=300,b=200)# 函数的调用,所以是关键字实参
fun(**dic)# 在函数调用时,将字典的键值对都转换为关键字实参输入

变量的作用域

递归函数

斐波那契数列

Python的异常处理机制

多个except结构

try…except…else结构

try…except…else…finally结构

python常见的异常类型

traceback模块

类的创建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Student:# Student为类的名称(类名)由一个或多个单词组成,每个单词的首字母大写,其余小写
native_pace='浙江'# 直接写在类里面的变量,称为类属性
def __init__(self, name, age):
self.name=name# self.name称为实体属性,进行了一个赋值操作,将局部变量的name的值赋给实体属性
self.age=age

# 实例方法
def eat(self):
print('学生在吃饭...')

# 静态方法
@staticmethod
def method():
print('我使用了staticmethod,进行修试,所以我是静态方法')

@classmethod
def cm(cls):
print('我是类方法,因为我使用了classmethod进行修饰')

# 在类之外定义的称为函数,在类之内定义的称为方法
def drink():
print('喝水')

类属性,类方法,静态方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Student:# Student为类的名称(类名)由一个或多个单词组成,每个单词的首字母大写,其余小写
native_pace='浙江'# 直接写在类里面的变量,称为类属性
def __init__(self, name, age):
self.name=name# self.name称为实体属性,进行了一个赋值操作,将局部变量的name的值赋给实体属性
self.age=age

# 实例方法
def eat(self):
print('学生在吃饭...')

# 静态方法
@staticmethod
def method():
print('我使用了staticmethod,进行修饰,所以我是静态方法')

@classmethod
def cm(cls):
print('我是类方法,因为我使用了classmethod进行修饰')

# 在类之外定义的称为函数,在类之内定义的称为方法
def drink():
print('喝水')


stu1=Student('张三',20)
stu1.eat()# 对象名.方法名
print(id(stu1))
print(type(stu1))
print(stu1)# 输出student对象的内存地址是由一个16进制的数

print('----------------------------')
Student.eat(stu1)# 该行代码和26行代码功能相同,都是调用Student中的eat方法
# 类名.方法名(类的对象)————>实际上就是方法定义处的self

# 类属性的使用方式

stu1=Student('张三',20)
stu2=Student('李四',30)
print(stu1.native_pace)
print(stu2.native_pace)
Student.native_pace='北京'
print(stu1.native_pace)
print(stu2.native_pace)
print('--------类方法的使用方式-----------')
Student.cm()
print('--------静态方法的使用方式-----------')
Student.method()

动态绑定属性和方法

面向对象的三大特征:封装,继承,多态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Car:
def __init__(self,brand):
self.brand=brand
def start(self):
print('汽车已启动')

car=Car('宝马X5')
car.start()
print(car.brand)
'''
在构造函数内部,我们使用 self.brand = brand 将传入的 brand 参数赋值给对象的 brand 属性。
这样,在创建 Car 对象时,可以通过传入品牌名称来初始化 brand 属性。
然后,我们使用 car = Car('宝马X5') 创建了一个 Car 对象,并将品牌名称传入构造函数中进行初始化。
接下来,我们调用了 car.start() 方法来启动汽车,并使用 print(car.brand) 打印了汽车的品牌名称。
'''

封装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Student:
def __init__(self,name,age):
self.name=name
self.__age=age# 年龄不希望在类的外部去使用,所以加了两个_
def show(self):
print(self.name,self.__age)

stu=Student('张三',20)
stu.show()

# 在类的外面使用name和age
print(stu.name)
# print(stu.__age) # AttributeError: 'Student' object has no attribute '__age'
print(stu._Student__age)# 在类的外部可以通过_Student__age来访问

继承

super()

在 Python 中,super() 是一个内置函数,用于调用父类(超类)的方法。它可以在子类中调用父类的方法,以便在子类中扩展或修改父类的行为。

使用 super() 函数时,通常是在子类的方法中调用父类的同名方法。这样可以实现子类继承父类的行为,并且可以在子类中添加额外的逻辑。

下面是一个简单的示例,说明了 super() 的用法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Parent:
def __init__(self, name):
self.name = name

def greet(self):
print(f"Hello, {self.name}!")

class Child(Parent):
def __init__(self, name, age):
super().__init__(name) # 调用父类的构造函数
self.age = age

def greet(self):
super().greet() # 调用父类的 greet 方法
print(f"I am {self.age} years old.")

child = Child("Tom", 10)
child.greet()

在上述代码中,我们定义了一个父类 Parent 和一个子类 Child。子类 Child 继承了父类 Parent 的属性和方法。

在子类的构造函数 __init__ 中,我们首先使用 super().__init__(name) 调用父类的构造函数,以便初始化继承的属性。然后,在子类的 greet 方法中,我们使用 super().greet() 调用父类的 greet 方法,以便在子类中扩展父类的行为。

输出结果为:

1
2
Hello, Tom!
I am 10 years old.

可以看到,在子类的 greet 方法中,先输出了父类的问候语,然后再输出子类自己的信息。这就是使用 super() 函数来调用父类方法的基本用法。

方法重写

在 Python 中,方法重写(Method Overriding)是指在子类中定义父类中已经存在的方法。这样,子类将使用自己的实现来替代父类中的方法。

当子类重新定义一个与父类中同名的方法时,子类的方法将覆盖(重写)父类的方法。当我们调用该方法时,将执行子类中的实现。

方法重写允许我们在子类中修改、扩展或定制父类的行为,从而实现多态性。通过重写父类的方法,我们可以根据子类的特定需求来提供不同的实现。

下面是一个简单的示例,说明了方法重写的概念:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Parent:
def greet(self):
print("Hello, I am the parent.")

class Child(Parent):
def greet(self):
print("Hello, I am the child.")

parent = Parent()
parent.greet() # 输出: Hello, I am the parent.

child = Child()
child.greet() # 输出: Hello, I am the child.

在上述代码中,我们定义了一个父类 Parent 和一个子类 Child。父类中有一个 greet 方法,输出一条父类特定的问候语。子类中也有一个同名的 greet 方法,但它输出一个子类特定的问候语。

当我们分别创建父类对象和子类对象,并调用它们的 greet 方法时,会根据对象的类型执行相应的方法。父类对象调用的是父类的方法,子类对象调用的是子类的方法。这就是方法重写的效果。

需要注意的是,子类重写父类的方法时,方法名、参数和返回值类型必须与父类中的方法保持一致。否则,将会导致方法重载(Method Overloading),而不是方法重写。

object类

1
2
3
4
5
6
7
8
9
10
11
class Student:
def __init__(self,name,age):
self.name=name
self.age=age
def __str__(self):
return '我的名字是{0},今年{1}岁'.format(self.name,self.age)

stu=Student('张三',20)
print(dir(stu))
print(stu)# 默认会调用__str__()这样的方法
print(type(stu))

多态

静态语言和动态语言关于多态的区别

特殊方法和特殊属性

1
2
3
4
5
6
7
8
9
10
11
class Student:
def __init__(self,name):
self.name=name
def __add__(self, other):
return self.name+other.name

stu1=Student('张三')
stu2=Student('李四')

s=stu1+stu2# 实现了两个对象的加法预算(因为在Student类中 编写__add__()特殊的方法)
print(s)

类的浅拷贝与深拷贝

模块

模块中包含函数,类,语句,类当中包含类属性,类方法,静态方法,实例属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def fun():
pass
def fun2():
pass

class Student:
native_place='浙江'# 类属性
def eat(self,name,age):# 实例方法
self.name=name# 实例属性
self.age=age
@classmethod
def cm(cls):# 类方法
pass
@staticmethod
def sm():# 静态方法
pass

模块的导入

1
2
from calc import add#	导入calc的add函数
print(add(10,20))
1
2
3
4
#   在demo5中导入calc自定义模块使用
import calc
print(calc.add(10,20))
print(calc.div(20,10))

以主程序形式运行

1
2
3
4
5
def add(a,b):
return a+b

if __name__ == '__main__':
print(add(10,20))# 只有当点击运行calc2时,才会执行运算符

python中的包

1
2
#	这是package包下的module_A
a=10
1
2
#	这是package包下的module_B
b=100
1
2
3
#   在demo8的模块中导入package包
import package.module_A as ma# ma是package.module_A这个模块的别名
print(package.module_A.a)
1
2
3
4
#   在使用import方式进行导入时,只能跟或模块名称
# 使用from可以导入包,模块名,函数名和变量名
from package import module_A
from package.module_A import a

Python中常用的内置模块

1
2
3
4
5
6
7
8
9
10
11
12
import sys
import time
import urllib.request# request发送请求

print(sys.getsizeof(24))
print(sys.getsizeof(45))
print(sys.getsizeof(True))
print(sys.getsizeof(False))
print(time.time())# 输出的second 秒
print(time.localtime(time.time()))# 将输出的second 秒转换成具体的时间

print(urllib.request.urlopen('https://www.baidu.com/index.htm').read())

模块与包 知识点总结

编码格式

文件的读写操作

1
2
中国
美丽

上面的文件名字叫a.txt

1
2
3
file=open('a.txt','r')
print(file.readlines())
file.close()# ['中国\n', '美丽\n']

常用的文件打开方式

1
2
3
file=open('b.txt','w')
print('helloworld')
file.close()

1
2
3
4
5
6
7
8
9
10
#file=open('a.txt','r')
#print(file.read(2))
#print(file.readline())
#print(file.readlines())

file=open('c.txt','a')
#file.write('hello')
lst=['java','go','python']
file.writelines(lst)
file.close()# 释放系统资源

with语句(上下文管理器)

目录操作

os模块操作目录相关函数

1
2
3
4
5
6
7
8
9
10
import  os
print(os.getcwd())# 告诉你当前路径

lst=os.listdir('../practice')
print(lst)# /一般是根目录,叫从根目录找,叫绝对路径,./ 是当前目录, ../是上一级,是相对于此文件的路径,叫相对路径。

#os.mkdir('newdir2')
#os.makedirs('A/B/C')
#os.rmdir('newdir2')
os.removedirs('A/B/C')