Python标准库
[Python标准库](https://docs.python.org/zh-cn/3.10/library/index.html)非常庞大,所提供的组件涉及范围十分广泛,正如以下内容目录所显示的。这个库包含了多个内置模块 (以 C 编写),Python 程序员必须依靠它们来实现系统级功能,例如文件 I/O,此外还有大量以 Python 编写的模块,提供了日常编程中许多问题的标准解决方案。其中有些模块经过专门设计,通过将特定平台功能抽象化为平台中立的 API 来鼓励和加强 Python 程序的可移植性。
字符串
循环打印字符串中的字符
temp = "1234567" h = 0 for i in temp: print(i) h+=int(i) print(h)
string之常见字符串操作
import random import string # string之间常见的字符串操作 # 1 获取大小写字母 print(string.ascii_letters) # 2 获取大写字母 print(string.ascii_uppercase) # 3 获取小写字母 print(string.ascii_lowercase) # 获取字符串 0123456789 十进制 print(string.digits) # 获取字符串 0123456789abcdefABCDEF 十六进制 print(string.hexdigits) # 获取字符串 01234567 八进制 print(string.octdigits)
随机获取位数的验证码
temp = string.ascii_letters yzm = "" for i in range(4): id = random.randint(0,len(temp)-1) yzm+= temp[id] print("验证码",yzm)
str之文本序列类型
[官网](https://docs.python.org/zh-cn/3.10/library/stdtypes.html#textseq)
在 Python 中处理文本数据是使用 [`str`](https://docs.python.org/zh-cn/3.10/library/stdtypes.html#str) 对象,也称为 *字符串*。 字符串是由 Unicode 码位构成的不可变序列。 字符串字面值有多种不同的写法:
- 单引号: `允许包含有 "双" 引号`
- 双引号: `允许嵌入 '单' 引号`
- 三重引号: `'''三重单引号'''`, `"""三重双引号"""`
使用三重引号的字符串可以跨越多行 —— 其中所有的空白字符都将包含在该字符串字面值中。
# 1) index:类似于java中的indexOf,如果没有找到则报错
try:
print("hello python".index('h',2))
except ValueError:
print("报错了")
# 2) find:与index类似
print("hello python".find('py'))
# 3) split
nums="1a2a3"
print(nums.split('a'))
# 4) strip:类似于java中的trim()方法
text = " a s "
print(text.strip(' '))
# 5) capitalize
text = 'hello python'
print(text.capitalize())
# 6) join
print(','.join('12345'))
# 7) endswith
print("123.png".endswith(".png"))
# 8) startwith: 如果字符串以指定的 prefix 开始则返回 True,否则返回 False。
print("123.png".startswith("123"))
# 9) 大写、小写及首字母大写转换处理
print("HELLO".lower())
print("hello".upper())
print("hello".capitalize())
案例:检查一个字符串中某个字符出现的次数
# 方式一:
temp = '123uiaudoa8uo1u3ouaosud9lkmlm2l34ml12asf'
index = temp.find('a')
count = 0
while index != -1:
count += 1
index = temp.find('a', index+1)
print("出现次数:", count)
# 方式二:
print("出现次数:", len(temp) - len(temp.replace('a', ''))) # 只适用于单个字母查询
# 方式三: count:返回子字符串 sub 在 [start, end] 范围内非重叠出现的次数
text = 'hello python'
print("出现次数:", str.count(text, 'h')) # Java中不成立
日期操作
from datetime import datetime # 日期格式化处理 '''d = datetime(2024,5,13) print(d)''' #获取当前系统日期 d = datetime.now() print(d) # 获取日期中的年,月,日,时,分,秒,毫秒 print(d.year) print(d.month) print(d.day) print(d.hour) print(d.minute) print(d.second) print(d.microsecond)
文件操作
pathlib --- 面向对象的文件系统路径。该模块提供表示文件系统路径的类,其语义适用于不同的操作系统。路径类被分为提供纯计算操作而没有 I/O 的纯路径,以及从纯路径继承而来但提供 I/O 操作的具体路径。
[`shutil`](https://docs.python.org/zh-cn/3.9/library/shutil.html#module-shutil) --- 高阶文件操作。该模块提供了一系列对文件和文件集合的高阶操作。特别是提供了一些支持文件拷贝和删除的函数。
[`os`](https://docs.python.org/zh-cn/3.9/library/os.html#module-os) --- 多种操作系统接口。本模块提供了一种使用与操作系统相关的功能的便捷式途径。 如果你只是想读写一个文件,请参阅 [`open()`](https://docs.python.org/zh-cn/3.9/library/functions.html#open),如果你想操作文件路径,请参阅 [`os.path`](https://docs.python.org/zh-cn/3.9/library/os.path.html#module-os.path) 模块,如果你想读取通过命令行给出的所有文件中的所有行,请参阅 [`fileinput`](https://docs.python.org/zh-cn/3.9/library/fileinput.html#module-fileinput) 模块。 为了创建临时文件和目录,请参阅 [`tempfile`](https://docs.python.org/zh-cn/3.9/library/tempfile.html#module-tempfile) 模块
# 操作目录 import pathlib from pathlib import Path # 获取当前文件所在路径 print(Path.cwd()) # 获取当前用户目录 print(Path.home()) # 获取当前文件路径 print(Path(__file__)) # 操作目录 p = Path("D:\S2项目\汽车素材图片\跑车\图片") # 是否是目录 print(p.is_dir()) # 是否是文件 print(p.is_file()) # 获取上一级目录 print(p.parent) # 是否是绝对路径 print(p.is_absolute()) # 创建目录 p.mkdir() # 删除目录 p.rmdir() # 操作文件 p = Path("E:\\images\\1.png") # 获取目录名称或者文件名称 print(p.name) # 获取文件名或者目录名 print(p.stem) # 获取文件后缀 print(str(p.resolve()).endswith(".png")) print(p.suffix) # 获取父级目录 print(p.parent) print(p.parents) for i in p.parents: print(i) # 获取第二级 print(p.parents[1]) # 获取最后一级 print(list(p.parents)[-1]) # 获取锚,目录前面的部分 C:\ 或者 / print(p.anchor) # 新建文件 p = Path("E:\\images\\readme.txt") p.touch() 获取当前目录下的所有目录和文件: def each(dir): p = Path(dir) for i in p.iterdir(): if i.is_file(): print(i) else: each(i) each("E:\\images") 获取目录下的指定文件: # 获取目录下的指定文件 p = Path("E:\\images") print(list(p.glob("*.png"))) # 递归获取所有子目录下的文件 print(list(p.rglob("*.png")))
移动文件:
p = Path("E:\\images\\readme.txt")
# 新建文件
p.touch()
# 通过replace返回一个新的指向目标路径的Path实例
p.replace("E:\\images\\xx.txt")
重命名文件:
p = Path("E:\\images\\xx.txt")
# 返回一个带有修改后stem的新路径,只修改了对象名称,并没有影响本地存储文件的名称
filename=p.with_stem("read")
# 通过replace返回一个新的指向目标路径的Path实例
p.replace(str(filename.absolute()))