第一章:字符串高级
# _*_ coding : utf-8 _*_
# @CreateTime : 2021/10/4 21:50
# @Author : guoshizhan
# @File : hello
# @Project : python—project
# 1、获取长度 ==> len len() 函数可以获取字符串的长度
str1 = 'china'
print(len(str1))
# 2、查找内容 ==> find 查找指定内容在字符串中是否存在,如果存在就返回该内容在字符串中第一次出现的开始位置索引值,如果不存在,则返回 -1
str2 = 'china'
print(str2.find('a'))
# 3、判断 ==> startswith, endswith 判断字符串是不是以谁谁谁开头/结尾
str3 = 'china'
print(str3.startswith('h'))
print(str3.endswith('n'))
# 4、计算出现次数 ==> count 返回指定字符串在 start 和 end 之间出现的次数
str4 = 'aaabb'
print(str4.count('b'))
# 5、替换内容 ==> replace 替换字符串中指定的内容,如果指定次数 count ,则替换不会超过 count 次
str5 = 'cccdd'
print(str5.replace('c', 'd'))
# 6、切割字符串 ==> split 通过参数的内容切割字符串
str6 = '1#2#3#4'
print(str6.split('#'))
# 7、修改大小写 ==> upper,lower 将字符串中的大小写互换
str7 = 'china'
print(str7.upper())
str7 = 'CHINA'
print(str7.lower())
# 8、空格处理 ==> strip 去除字符串中的空格
str8 = ' a '
print(len(str8))
print(len(str8.strip()))
# 字符串拼接 ==> join 字符串拼接
str9 = 'a'
print(str9.join('hello')) # 结果很奇葩:haealalao
第二章:列表的高级使用
一、列表的添加
# _*_ coding : utf-8 _*_
# @CreateTime : 2021/10/4 21:59
# @Author : guoshizhan
# @File : hello
# @Project : python—project
food_list = ['典韦', '亚瑟']
print(food_list)
# append 追加 在列表的最后来添加一个对象/数据
food_list.append('后羿')
print(food_list)
char_list = ['a', 'c', 'd']
print(char_list)
# insert 插入 ==> index 的值就是你想插入数据的那个下标
char_list.insert(1, 'b')
print(char_list)
# extend
num1_list = [1, 2, 3]
num2_list = [4, 5, 6]
num1_list.extend(num2_list)
print(num1_list)
二、列表的修改
# _*_ coding : utf-8 _*_
# @CreateTime : 2021/10/4 22:12
# @Author : guoshizhan
# @File : hello
# @Project : python—project
city_list = ['北京', '上海', '深圳', '武汉', '西安']
print(city_list)
# 将列表中的元素的值修改 ==> 可以通过下标来修改,注意列表中的下标是从 0 开始的
city_list[4] = '大连'
print(city_list)
三、列表的查询
# _*_ coding : utf-8 _*_
# @CreateTime : 2021/10/4 22:20
# @Author : guoshizhan
# @File : hello
# @Project : python—project
# in 是判断某一个元素是否在某一个列表中
hero_list = ['典韦', '亚瑟', '后羿']
# 判断一下在控制台输入的那个数据是否在列表中
food = input('请输入英雄:\n')
if food in hero_list:
print('该英雄已存在!')
else:
print('没有找到该英雄!')
ball_list = ['篮球', '台球']
# 在控制台上输入你喜欢的球类,然后判断是否不在这个列表中
ball = input('请输入您喜欢的球类:\n')
if ball not in ball_list:
print('没有找到您喜欢的球类!')
else:
print('您喜欢的球类已存在!')
四、列表的删除
# _*_ coding : utf-8 _*_
# @CreateTime : 2021/10/4 22:27
# @Author : guoshizhan
# @File : hello
# @Project : python—project
# 1、根据下标来删除列表中的元素
# 爬取的数据中,有个别的数据是我们不想要的,那么我们就可以通过下标的方式来删除
num1_list = [1, 2, 3, 4, 5]
print(num1_list)
del num1_list[2]
print(num1_list)
print('================')
# 2、删除列表的最后一个元素 ==> pop() 函数是删除列表中的最后一个元素
num2_list = [1, 2, 3, 4, 5]
print(num2_list)
num2_list.pop()
print(num2_list)
print('================')
# 3、根据元素来删除列表中的数据
num3_list = [1, 2, 3, 4, 5]
print(num3_list)
num3_list.remove(3) # 如果列表中没有该元素,会报 ValueError: list.remove(x): x not in list 这样的错
print(num3_list)
第三章:元组和字典高级
一、元组高级
# _*_ coding : utf-8 _*_
# @CreateTime : 2021/10/4 22:35
# @Author : guoshizhan
# @File : hello
# @Project : python—project
num1_tuple = (1, 2, 3, 4)
print(num1_tuple[0])
print(num1_tuple[1])
print('===========')
# 1、元组是不可以修改里面的内容的,以下两行代码会报错
# num1_tuple[3] = 5
# print(num1_tuple)
# 2、元组和列表的区别:列表中的元素是可以修改的,而元组中的元素是不可以被修改
# 3、当元组中只要一个元素的时候,那么它是整型数据
num2_tuple = (5)
print(type(num2_tuple))
print('===========')
# 4、定义只有一个元素的元组,需要在唯一的元素后写一个逗号
num3_tuple = (5,)
print(type(num3_tuple))
二、切片操作
# _*_ coding : utf-8 _*_
# @CreateTime : 2021/10/4 22:43
# @Author : guoshizhan
# @File : hello
# @Project : python—project
"""
1、切片是指对操作的对象截取其中一部分的操作。字符串、列表、元组都支持切片操作
2、切片的语法:[起始:结束:步长],也可以简化使用 [起始:结束]
注意:选取的区间从"起始"位开始,到"结束"位的前一位结束(不包含结束位本身),步长表示选取间隔
"""
sentence = 'This is my first program'
# 1、在切片中直接写一个下标
print(sentence[0])
# 2、左闭右开区间 ==> 包含坐标的数据,不包含右边的数据
print(sentence[0:4])
# 3、是从起始的值开始,一直到末尾
print(sentence[1:])
# 4、以下写法是下标为 0 的索引的元素开始,一直到第二参数为止【遵循左闭右开区间】
print(sentence[:4])
# 5、从下标为 0 的位置开始,到下标为 6 的位置结束,每次增长 2 个长度
print(sentence[0:6:2])
三、字典的查询
# _*_ coding : utf-8 _*_
# @CreateTime : 2021/10/4 22:52
# @Author : guoshizhan
# @File : hello
# @Project : python—project
# 定义一个字典
person = {'name': 'Jack', 'age': 23}
# 1、使用中括号的方式来访问 person 的 name 和 age
print(person['name'])
print(person['age'])
print('============')
# 注意:使用中括号[]的方式获取字典中不存在的 key 时,会发生异常 ==> KeyError: 'sex' 。代码如下:
# print(person['sex'])
# 2、不能使用.的方式来访问字典的数据
# print(person.name)
# 3、使用 .get() 的方式来获取字典中不存在的 key 时,结果会返回 None 值
print(person.get('name'))
print(person.get('age'))
print(person.get('sex'))
四、字典的修改
# _*_ coding : utf-8 _*_
# @CreateTime : 2021/10/4 22:59
# @Author : guoshizhan
# @File : hello
# @Project : python—project
# 定义一个字典
person = {'name': 'Jack', 'age': 23}
print(person) # 修改之前的字典
# 修改 name 的值为 Lisa
person['name'] = 'Lisa'
print(person) # 修改之后的字典
# 注意事项:以下代码是错误的写法,系统会直接报错的
# person.get('name') = 'Jane'
五、字典的添加
# _*_ coding : utf-8 _*_
# @CreateTime : 2021/10/4 23:03
# @Author : guoshizhan
# @File : hello
# @Project : python—project
# 定义一个字典
person = {'name': 'Jack', 'age': 23}
print(person) # 添加元素之前的字典
print('===========================================')
# 1、给字典添加一个新的 key value
# 如果使用变量名字['键'] = 数据时,这个键如果在字典中不存在,那么就会变成新增元素;若存在,则执行修改操作
person['sex'] = 'male'
print(person) # 添加元素之后的字典
print('===========================================')
# 2、如果这个键在字典中存在 那么就会变成这个元素
person['name'] = 'Lisa'
print(person)
六、字典的删除
# _*_ coding : utf-8 _*_
# @CreateTime : 2021/10/4 23:11
# @Author : guoshizhan
# @File : hello
# @Project : python—project
# 定义一个字典
person = {'name': 'Jack', 'age': 23, 'sex': 'male'}
print(person) # 删除元素之前的字典
print('===========================================')
# 1、使用 del() 函数,删除字典中指定的某一个元素
del person['age']
print(person) # 删除元素之后的字典
# 2、删除整个字典,执行这个操作之后,整个字典都删除掉了,所以在执行打印时就会报错 ==> NameError: name 'person' is not defined
# del person
# print(person)
print('===========================================')
# 3、使用 clear() 函数来清空字典,但是保留字典对象。清空指的是将字典中所有的数据都删除掉而保留字典的结构
person.clear()
print(person)
七、字典的遍历
# _*_ coding : utf-8 _*_
# @CreateTime : 2021/10/4 23:20
# @Author : guoshizhan
# @File : hello
# @Project : python—project
# 定义一个字典
person = {'name': 'Jack', 'age': 23, 'sex': 'male'}
print(person)
print('================= key 遍历 =================')
# 【遍历】就是对数据一个一个的输出
# 1、遍历字典的 key ==> 字典.keys() 方法即可获取的字典中所有的 key 值
for item in person.keys():
print(item) # 打印所有的 key
print('================ value 变量 ================')
# 2、遍历字典的 value ==> 字典.values() 方法即可获取字典中所有的 value 值
for item in person.values():
print(item)
print('========== (key, value)键值对遍历 ==========')
# 3、遍历字典的 key 和 value
for key, value in person.items():
print(key, value)
print('========== (key, value)键值对遍历 ==========')
# 4、遍历字典的项/元素
for item in person.items():
print(item)
第四章:函数相关
一、函数的定义和调用
# _*_ coding : utf-8 _*_
# @CreateTime : 2021/10/4 23:33
# @Author : guoshizhan
# @File : hello
# @Project : python—project
# print('Hello World')
# print('This is my first program')
# print('See you again')
#
# print('Hello World')
# print('This is my first program')
# print('See you again')
#
# print('Hello World')
# print('This is my first program')
# print('See you again')
#
# print('Hello World')
# print('This is my first program')
# print('See you again')
# 很多重复的业务逻辑重复出现的时候,我们可以使用函数【例如上面的代码】
# 1、定义函数,参数 count 表示打印的次数
def print_function(count):
for item in range(count):
print('Hello World')
print('This is my first program')
print('See you again')
# 2、调用函数,打印 5 次
print_function(5)
二、函数的参数
# _*_ coding : utf-8 _*_
# @CreateTime : 2021/10/4 23:39
# @Author : guoshizhan
# @File : hello
# @Project : python—project
"""
定义一个函数来计算两个数的和
参数相关概念介绍:
定义函数的时候 add_two_sum(a, b) ==> 我们称 a 和 b 为【形式参数】 ==> 简称【形参】
调用函数的时候 add_two_sum(1, 2) ==> 我们称 1 和 2 为【实际参数】 ==> 简称【实参】
"""
def add_two_sum(a, b):
c = a + b
print(c)
# 位置参数:按照位置一一对应的关系来传递参数
add_two_sum(1, 2)
add_two_sum(100, 200)
# 关键字传参,指定参数的值
add_two_sum(b=200, a=100)
三、函数的返回值
# _*_ coding : utf-8 _*_
# @CreateTime : 2021/10/4 23:46
# @Author : guoshizhan
# @File : hello
# @Project : python—project
"""
返回值的关键字是 return ,存在函数中
"""
def add_two_sum(a, b):
c = a + b
return c
def buy_ice_cream():
return '冰激凌'
# 使用一个变量来接受函数的返回值
food = buy_ice_cream()
print(food)
# 案例练习 ==> 定义一个函数,然后让函数计算两个数值的和,并且返回这个计算之后的结果
result = add_two_sum(123, 456)
print(result)
四、函数的局部变量和全部变量
# _*_ coding : utf-8 _*_
# @CreateTime : 2021/10/4 23:53
# @Author : guoshizhan
# @File : hello
# @Project : python—project
"""
局部变量:在【函数的内部】定义的变量称之为局部变量 ==> 特点:其作用域范围是函数内部,而函数的外部是不可以使用
全局变量: 在【函数的外部】定义的变量称之为全局变量 ==> 特点:可以在函数的外部使用,也可以在函数的内部使用
"""
def function1():
num1 = 1 # 定义局部变量,num 定义在函数的内部,所以是局部变量
print(num1)
function1()
# print(num) # 此时就不能打印 num 了,因为 num 的作用范围局限于函数之内,无法在全局使用
# 定义全局变量 num2
num2 = 1
print(num2)
def function2():
print(num2)
function2()
# 注意事项:在满足条件的情况,要使用作用域最小的那个变量范围
第五章:文件操作和异常
一、文件的打开和关闭
# _*_ coding : utf-8 _*_
# @CreateTime : 2021/10/5 08:32
# @Author : guoshizhan
# @File : hello
# @Project : python—project
# 1、创建一个 Python.txt 文件 ==> open(文件的路径, 访问模式模式)
# 访问模式: w ==> 可写; r ==> 可读
# 更多访问模式请参考 ==> http://47.113.85.135:8888/documents/python/Python%E5%9F%BA%E7%A1%80.pdf
open('Python.txt', 'w')
# # 2、打开 Python.txt 文件
fp1 = open('Python.txt', 'w')
fp1.write('Hello World')
fp1.close()
# 3、文件夹是不可以创建的,暂时需要手动创建 demo 文件夹
fp2 = open('demo/Python.txt', 'w')
fp2.write('Hello World')
fp2.close()
# 4、文件的关闭:打开文件之后一定要记得关闭文件,这非常重要
fp3 = open('Python.txt', 'w')
fp3.write('I will close the file ...')
fp3.close()
二、文件的读写
# _*_ coding : utf-8 _*_
# @CreateTime : 2021/10/5 08:45
# @Author : guoshizhan
# @File : hello
# @Project : python—project
# 1、写数据 ==> 使用 write() 函数
fp1 = open('Python.txt', 'w')
fp1.write('I am writing now ...\n' * 3)
fp1.close()
"""
如果再次来运行上述代码,那么 Python.txt 文件中打印了 6 次还是打印了 3 次呢?
如果执行上述代码,若文件存在,会先清空原来的数据,然后再写入数据
那如果我想在每一次执行之后都要追加数据,那就需要把访问模式变为 a ,这样才能执行追加的操作
"""
# 2、读数据 ==> 使用 read() 函数
# 如果文件存在,则读取数据;若文件不存在,则报错 ==> FileNotFoundError: [Errno 2] No such file or directory: 'Python.txt'
fp2 = open('Python.txt', 'r')
# 默认情况下,read() 函数是一字节一字节的读 ==> 效率比较低
content2 = fp2.read()
print(content2)
# 3、读数据 ==> 使用 readline() 函数进行一行一行的读取,但是只能读取一行
fp3 = open('Python.txt', 'r')
content3 = fp3.readline()
print(content3)
# 4、读数据 ==> 使用 readlines() 函数
# 可以按照行来读取,能够将所有的数据都读取到并以一个列表的形式返回【列表的元素就是一行一行的数据】
fp4 = open('Python.txt', 'r')
content4 = fp4.readlines()
print(content4)
三、文件的序列化和反序列化
# _*_ coding : utf-8 _*_
# @CreateTime : 2021/10/5 08:57
# @Author : guoshizhan
# @File : hello
# @Project : python—project
"""
验证只能将字符串写入到文件,而不能把对象写入到文件
"""
# 1、字符串可写入到文件
fp1 = open('Python.txt', 'w')
# 默认情况下,我们只能将字符串写入到文件中
fp1.write('Hello World')
fp1.close()
# 2、对象不可写入到文件
fp2 = open('Python.txt', 'w')
# 默认情况下,对象是无法写入到文件中。如果想写入到文件,那么必须使用序列化操作
name_list = ['Jack', 'Lisa']
fp2.write(name_list) # 这里会报错 ==> TypeError: write() argument must be str, not list
# _*_ coding : utf-8 _*_
# @CreateTime : 2021/10/5 09:03
# @Author : guoshizhan
# @File : hello
# @Project : python—project
"""
序列化的 2 种方式:dumps() 和 dump()
"""
# 1、使用 dumps() 函数进行序列化
fp1 = open('Python.txt', 'w') # 创建一个文件
name_list = ['Jack', 'Lisa', 'Tom'] # 定义一个列表
import json # 导入 json 模块到该文件中
# 进行序列化操作,将 python 对象变成 json 字符串
names = json.dumps(name_list)
print(type(names))
fp1.write(names) # 将 names 写入到文件中
fp1.close()
# 2、使用 dump() 函数进行序列化
# 在将对象转换为字符串的同时,指定一个文件的对象,然后把转换后的字符串写入到这个文件里
fp2 = open('Python.txt', 'a')
# json.dump(name_list, fp2) 相当于 names = json.dumps(name_list) 和 fp.write(names)
json.dump(name_list, fp2)
fp2.close()
# _*_ coding : utf-8 _*_
# @CreateTime : 2021/10/5 09:10
# @Author : guoshizhan
# @File : hello
# @Project : python—project
"""
反序列化的 2 种方式:loads() 和 load()
"""
fp1 = open('Python.txt', 'r')
content = fp1.read()
# 读取之后,content 是字符串类型的
print(content)
print(type(content))
print('========================')
fp1.close()
# 1、使用 loads() 函数进行序列化
import json
result = json.loads(content) # 将 json 字符串变成 python 对象
print(result)
print(type(result))
print('========================')
# 2、使用 load() 函数进行序列化
fp2 = open('Python.txt', 'r')
result = json.load(fp2)
print(result)
print(type(result))
fp2.close()
四、Python 中的异常
# _*_ coding : utf-8 _*_
# @CreateTime : 2021/10/5 09:18
# @Author : guoshizhan
# @File : hello
# @Project : python—project
"""
Python 中的异常处理。异常的代码格式如下:
try:
可能出现异常的代码
except 异常的类型
友好的提示
"""
# 打开一个不存在的文件,这个时候会报错 ==> FileNotFoundError: [Errno 2] No such file or directory: 'Java.txt'
# fp1 = open('Java.txt', 'r')
# fp1.read()
# fp1.close()
# 所以需要对上述的情况进行异常处理
try:
fp2 = open('Java.txt', 'r')
fp2.read()
except FileNotFoundError:
print('系统正在升级,请稍后再试……')