字符串方法
# 字符串方法:
string = "Hello, World!"
# upper():将字符串转换为大写。
print(string.upper()) # 输出: HELLO, WORLD!
# lower():将字符串转换为小写。
print(string.lower()) # 输出: hello, world!
# strip():去除字符串两端的空白字符。
print(string.strip()) # 输出: Hello, World!
# split():将字符串拆分为列表,可以指定分隔符。
print(string.split(",")) # 输出: ['Hello', ' World!']
# join():将列表中的字符串连接为一个字符串,可以指定连接符。
print("-".join(['Hello', 'World!'])) # 输出: Hello-World!
# replace():替换字符串中的子字符串。
print(string.replace("Hello", "Hi")) # 输出: Hi, World!
# startswith():检查字符串是否以指定的前缀开始。
print(string.startswith("Hello")) # 输出: True
# endswith():检查字符串是否以指定的后缀结束。
print(string.endswith("World!")) # 输出: True
列表方法
# 列表方法:
fruits = ["apple", "banana", "cherry"]
# append():向列表末尾添加元素。
fruits.append("orange")
print(fruits) # 输出: ['apple', 'banana', 'cherry', 'orange']
# extend():将另一个列表中的元素添加到当前列表。
fruits.extend(["grape", "kiwi"])
print(fruits) # 输出: ['apple', 'banana', 'cherry', 'orange', 'grape', 'kiwi']
# insert():在指定位置插入元素。
fruits.insert(1, "pear")
print(fruits) # 输出: ['apple', 'pear', 'banana', 'cherry', 'orange', 'grape', 'kiwi']
# remove():从列表中删除指定元素。
fruits.remove("banana")
print(fruits) # 输出: ['apple', 'pear', 'cherry', 'orange', 'grape', 'kiwi']
# pop():删除并返回列表中指定位置的元素。
popped = fruits.pop(2)
print(popped) # 输出: cherry
print(fruits) # 输出: ['apple', 'pear', 'orange', 'grape', 'kiwi']
# index():返回指定元素在列表中的索引。
index = fruits.index("orange")
print(index) # 输出: 2
# count():返回指定元素在列表中的出现次数。
count = fruits.count("kiwi")
print(count) # 输出: 1
# sort():对列表进行排序。
fruits.sort()
print(fruits) # 输出: ['apple', 'grape', 'kiwi', 'orange', 'pear']
# reverse():反转列表中的元素顺序。
fruits.reverse()
print(fruits) # 输出: ['pear', 'orange', 'kiwi', 'grape', 'apple']
字典方法
# 字典方法:
person = {"name": "John", "age": 30, "city": "New York"}
# keys():返回字典中所有的键。
keys = person.keys()
print(keys) # 输出: dict_keys(['name', 'age', 'city'])
# values():返回字典中所有的值。
values = person.values()
print(values) # 输出: dict_values(['John', 30, 'New York'])
# items():返回字典中所有的键值对(以元组形式)。
items = person.items()
print(items) # 输出: dict_items([('name', 'John'), ('age', 30), ('city', 'New York')])
# get():获取指定键的值,如果键不存在则返回默认值。
name = person.get("name")
print(name) # 输出: John
unknown = person.get("unknown", "N/A")
print(unknown) # 输出: N/A
# pop():删除并返回指定键的值。
age = person.pop("age")
print(age) # 输出: 30
print(person) # 输出: {'name': 'John', 'city': 'New York'}
# update():将一个字典中的键值对更新到当前字典中。
person.update({"country": "USA"})
print(person) # 输出: {'name': 'John', 'city': 'New York', 'country': 'USA'}
# clear():清空字典中的所有键值对。
person.clear()
print(person) # 输出: {}
集合方法
#集合方法
# add(element): 向集合中添加元素。
# remove(element): 从集合中移除指定元素。如果元素不存在,会引发 KeyError 异常。
# discard(element): 从集合中移除指定元素,如果元素不存在,不会引发异常。
# pop(): 随机移除并返回集合中的一个元素。如果集合为空,会引发 KeyError 异常。
# clear(): 清空集合中的所有元素。
# copy(): 返回集合的一个副本。
# union(other_set): 返回当前集合和另一个集合的并集,生成一个新的集合。
# intersection(other_set): 返回当前集合和另一个集合的交集,生成一个新的集合。
# difference(other_set): 返回当前集合相对于另一个集合的差集,生成一个新的集合。
# symmetric_difference(other_set): 返回当前集合和另一个集合的对称差集,生成一个新的集合。
# issubset(other_set): 判断当前集合是否是另一个集合的子集,返回布尔值。
# issuperset(other_set): 判断当前集合是否是另一个集合的超集,返回布尔值。
# intersection_update(other_set): 将当前集合更新为当前集合和另一个集合的交集。
# difference_update(other_set): 将当前集合更新为当前集合相对于另一个集合的差集。
# symmetric_difference_update(other_set): 将当前集合更新为当前集合和另一个集合的对称差集。
# 创建集合
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
# 添加元素
set1.add(5)
print(set1) # 输出: {1, 2, 3, 4, 5}
# 移除元素
set1.remove(2)
print(set1) # 输出: {1, 3, 4, 5}
# 并集
union_set = set1.union(set2)
print(union_set) # 输出: {1, 3, 4, 5, 6}
# 交集
intersection_set = set1.intersection(set2)
print(intersection_set) # 输出: {3, 4}
# 差集
difference_set = set1.difference(set2)
print(difference_set) # 输出: {1, 5}
# 对称差集
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set) # 输出: {1, 5, 6}
# 判断子集和超集
print(set1.issubset(set2)) # 输出: False
print(set1.issuperset(set2)) # 输出: False
# 更新集合
set1.intersection_update(set2)
print(set1) # 输出: {3, 4}
文件操作方法
# 文件操作方法:
#a为追加写 r为读取文件 w为写入文件 b能打开所有文件以16进制输出
# open():打开文件。
# read():读取文件内容。注意:读取的是字符
# write():将内容写入文件。
# close():关闭文件。
# decode():定义字符编码
# readlines(): 读取所有行并返回一个列表 去掉S:读取一行
# writelines():写入多行内容到文件 去掉S:写入一行
# seek(): 指针移动的位置 注意:移动的是字节 不能在t模式下使用
# 写入文件
file = open("example.txt", "w")
file.write("Hello, World!")
file.close()
# 读取文件
file = open("example.txt", "r")
content = file.read()
print(content) # 输出: Hello, World!
file.close()
# 1. 打开文件
file = open('filename.txt', 'r') # 以只读模式打开文件
# 2. 读取文件内容
content = file.read() # 读取整个文件内容
# 3. 逐行读取文件内容
for line in file:
print(line)
# 4. 写入文件
file = open('filename.txt', 'w') # 以写入模式打开文件
file.write('Hello, World!') # 写入内容到文件
file.close() # 关闭文件
# 5. 追加内容到文件
file = open('filename.txt', 'a') # 以追加模式打开文件
file.write('New line') # 追加内容到文件
file.close() # 关闭文件
# 6. 关闭文件
file.close() # 关闭文件
#用户注册小程序
name = input('请输入账号>>>')
word = input('请输入密码>>>')
with open('hahaha.txt',mode='a',encoding='utf-8')as f:
f.write(f'{name}---{word}\n')
#拷贝功能
jiuwenjian = input('请输入旧文件路径>>>').strip()
xinwenjian = input('请输入新文件路径>>>').strip()
with open(fr'{jiuwenjian}',mode='+rt',encoding='utf-8')as f1,\
open(fr'{xinwenjian}',mode='wt',encoding='utf-8')as f2:
res = f1.read()
f2.write(res)
#b模式下打开文件
with open('图片.jpg',mode='rb')as f:
res = f.read()
print(res)
print(type(res))
# 文件指针
file.seek(0) # 将文件指针移动到文件开头
position = file.tell() # 获取当前文件指针的位置
# 附加技能
filename = file.name # 获取文件名
mode = file.mode # 获取打开模式
closed = file.closed # 检查文件是否已关闭
# 文件异常处理
try:
file = open('filename.txt', 'r')
# 进行文件操作
except FileNotFoundError:
print('文件不存在')
except IOError:
print('读取文件时发生错误')
finally:
file.close() # 确保关闭文件
#文件监控 服务端
import time
with open('文件异常操作.log',mode='rb')as f:
f.seek(0,2)
while True:
res = f.readline()
if res:
print(res.decode('utf-8'),end='')
time.sleep(0.2)
# 监控文件客户端
neirong = input('你需要写入的内容>>>')
with open('文件处理异常.log',mode='at',encoding='utf-8')as f:
f.write(f'文件写入了>>>{neirong}\n')
# 文件修改(修改特定值:文件编辑器形式修改文件)
with open('hahaha.txt',mode='r+t',encoding='utf-8')as f:
res = f.read() #如果文件过大 会对内存造成过大的占用
l = list(res) #转成列表
l.insert(1,'不') #插入数据
new = ''.join(l) #将列表转成字符串
print(new)
# 修改全部
new = res.replace('我喜欢你','我不喜欢你')
with open('hahaha.txt',mode='wt',encoding='utf-8')as f1:
f1.write(new)
import os #导入功能模块
with open('hahaha.txt',mode='rt',encoding='utf-8')as f,\
open('修改过后的文件.txt',mode='wt',encoding='utf-8')as f1:
for line in f: #读取每一行都写进硬盘里 不会占用太大内存空间
res = line.replace('一天','一年') #将原文件的所有一天改为一年
f1.write(res) #将循环后的f写进f1
os.remove('hahaha.txt') #删除原文件
os.rename('修改过后的文件.txt','hahaha.txt') #修改过后的名称改为hahaha.txt
函数
# 函数
# 函数定义阶段不会执行子代码 只会检测代码
#有参函数
def func1(x,y):
print(x,y)
func1(800,90) #实参函数
def add(x,y):
res = x + y
print(res)
add(100,800)
#无参函数
def func2():
print('我是func2')
def func1():
print(func2) #在fucn1的子代码块中 访问func2的内存地址
print('我是func1')
func1()
# 定义一个简单的函数
def greet():
print("Hello!")
# 调用函数
greet()
# 定义带参数的函数
def greet_with_name(name):
print("Hello, " + name + "!")
# 传递参数调用函数
greet_with_name("Alice")
# 定义带有默认参数的函数
def greet_with_default(name="Anonymous"):
print("Hello, " + name + "!")
# 不传递参数,使用默认值
greet_with_default()
# 传递参数,覆盖默认值
greet_with_default("Bob")
# 定义可变参数的函数
def add_numbers(*args):
sum = 0
for num in args:
sum += num
return sum
# 调用可变参数的函数
result = add_numbers(1, 2, 3, 4)
print(result) # 输出:10
# 定义关键字参数的函数
def greet_with_age(name, age):
print("Hello, " + name + "! You are " + str(age) + " years old.")
# 使用关键字参数传递参数
greet_with_age(name="Alice", age=25)
# 定义带返回值的函数
def add_numbers(a, b):
return a + b
# 调用带返回值的函数
result = add_numbers(3, 4)
print(result) # 输出:7
# 使用Lambda函数定义匿名函数
add_numbers = lambda a, b: a + b
result = add_numbers(3, 4)
print(result) # 输出:7
# 函数作为参数传递
def apply_operation(operation, a, b):
return operation(a, b)
def add(a, b):
return a + b
# 调用函数作为参数的函数
result = apply_operation(add, 3, 4)
print(result) # 输出:7
# 函数内部定义函数
def outer_function():
def inner_function():
print("Inside inner function")
print("Inside outer function")
inner_function()
# 调用函数内部定义的函数
outer_function()
# 列表添加 不可变类型
def my_append (x,y,l=None):
if l is None: #如果l=None l=[]
l = []
l.append(x)
l.append(y)
print(l)
liebiao = [3,4,5]
my_append(1,2,l=liebiao)
#Python中有四种作用域:
# 局部作用域(Local:本地)
# 嵌套作用域(Enclosing:封闭)
# 全局作用域(Global:全局)
# 内置作用域(Built-in:内置)
#1. 局部作用域(Local Scope):
# 局部作用域是在函数内部定义的变量所在的作用域。
# 这些变量只能在函数内部使用,并且在函数外部是不可访问的。
# 例如:
def my_function():
x = 10 # 局部变量
print(x)
my_function() # 输出:10
# print(x) # 报错,x在全局作用域中不可见
# nonlocal:非本地
x = 10
def func1():
x = 20
def func2():
nonlocal x #将x设为非本地 就改为了20
x = 30
print('调用之前的x>>>',x) #打印为20
func2()
print('调用之后的x>>>',x) #打印为30
func1()
print('全局的x>>>',x) #打印为10
#2. 嵌套作用域(Enclosing Scope):
# 嵌套作用域是指在函数内部嵌套函数的情况下,
# 内部函数可以访问外部函数的变量。内部函数可以访问其外部函数的变量,
# 但对于外部函数来说,内部函数的变量不可见。
# 例如:
def outer_function():
x = 10 # 外部函数的变量
def inner_function():
print(x) # 可以访问外部函数的变量
inner_function()
outer_function() # 输出:10
# print(x) # 报错,x在全局作用域中不可见
#3. 全局作用域(Global Scope):
# 全局作用域是在模块层级定义的变量所在的作用域。
# 这些变量可以在模块的任何地方访问,包括函数内部和函数之间。
# 例如:
#局部想要修改全局的名字对应的不可变类型的值
x = 10
def func():
global x #将局部的20变为全局
x = 20
func()
print(x)
x = 10 # 全局变量
def my_function():
print(x) # 可以访问全局变量
my_function() # 输出:10
print(x) # 输出:10
#4. 内置作用域(Built-in Scope):
# 内置作用域是指Python解释器内置的函数和变量所在的作用域,
# 这些函数和变量可以在任何地方直接使用,无需导入任何模块。
# 例如:
print(len([1, 2, 3])) # 使用内置函数len()
max_value = max(4, 7) # 使用内置函数max()
# 位置参数传递:
# 这是最常见的参数传递方式。
# 当调用函数时,按照定义时的顺序,将实际参数传递给函数。
# 例如:
def greet(name, message):
print(f"Hello, {name}! {message}")
greet("Alice", "How are you?")
#在上面的例子中,"Alice"被传递给name参数,"How are you?"被传递给message参数。
def func():
print('我是func')
x = func #内存地址
#print(x,func) #x和func的内存地址
#x() #调用函数
def func2(x):
#print(x) #调用func的内存地址
#x() #调用func的函数
return x #返回x的内存地址
res = func2(func) #func2(func的内存地址)
print(res) #打印的func的内存地址
def func():
print('我是func')
# l = [func] #能定义成列表,也能定义成字典
# l[0]() #调用func函数 [0]的意思为访问列表0位置的[func]
d = {'k1':func} #定义字典k1:func
d['k1']() #先调用key拿到内存地址 再调用函数
# 关键字参数传递:
# 使用关键字参数可以根据参数的名称来传递参数,
# 而不必按照定义时的顺序。这样可以提高代码的可读性,
# 并且允许跳过某些可选参数。
# 例如:
def greet(name, message):
print(f"Hello, {name}! {message}")
greet(message="How are you?", name="Bob")
#在上面的例子中,message="How are you?"和name="Bob"使用了关键字参数传递。
# 默认参数值:
# 函数可以使用默认参数值,这样在调用函数时可以省略这些参数。
# 默认参数值在函数定义时指定,并在调用时生效。
# 例如:
def greet(name, message="Nice to meet you!"):
print(f"Hello, {name}! {message}")
greet("Alice")
#在上面的例子中,调用greet("Alice")时,没有传递message参数,因此将使用默认值"Nice to meet you!"。
# 可变数量的参数:
# 有时候函数需要接受可变数量的参数,Python提供了两种方式来实现这一点:
# 使用*args接受任意数量的位置参数,
# 或使用**kwargs接受任意数量的关键字参数。
# 例如:
def print_items(*args):
for item in args:
print(item)
print_items("apple", "banana", "cherry")
def print_dict(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_dict(name="Alice", age=25)
# 在上面的例子中,print_items函数接受任意数量的位置参数,并将它们逐个打印出来。
# print_dict函数接受任意数量的关键字参数,并将它们逐个打印出来。
#装饰器
# 装饰器的作用是在不改变函数调用方式的前提下,给函数添加额外的功能或者修改函数的行为。
# 它可以用于函数的日志记录、性能分析、输入验证、缓存等场景,使得代码更加灵活和可重用。
#装饰器基础模板
def outer(func):
def wrapper(*args,**kwargs):
res = func(*args,**kwargs) #返回原函数
return res #返回原函数的返回值,如没有则返回默认值(None)
return wrapper #返回wrapper使全局可访问
#装饰器实例:
from functools import wraps #导入wraps装饰器,把原函数的所有属性都赋值给
def decorator_function(original_function):
@wraps(original_function) #把原函数的所有属性都赋值给original_function
def wrapper_function(*args, **kwargs):
# 在原始函数调用之前执行的代码
print("装饰器:在函数调用之前执行")
# 调用原始函数
result = original_function(*args, **kwargs)
# 在原始函数调用之后执行的代码
print("装饰器:在函数调用之后执行")
# 返回原始函数的返回值
return result
# 返回装饰后的函数
return wrapper_function
# 使用装饰器语法将装饰器应用到函数上
@decorator_function #语法糖
def my_function():
print("原始函数:我是原始函数")
return print('返回值') #有返回值
# 调用经过装饰器修饰后的函数 (实体函数)
my_function()