Python入门手册:常用的Python标准库
Python标准库是Python语言的核心组成部分,它提供了一系列内置的模块和函数,使得Python能够处理各种常见的编程任务。这些标准库模块覆盖了从文件操作、网络编程到数据处理等多个方面。今天,就让我们一起深入了解Python标准库中一些常用的模块。
一、os
模块:操作系统接口
os
模块提供了与操作系统交互的功能,包括文件和目录操作、环境变量访问等。
1. 文件和目录操作
示例:获取当前工作目录
import os# 获取当前工作目录
current_dir = os.getcwd()
print(f"Current working directory: {current_dir}")
示例:列出目录内容
# 列出指定目录的内容
directory = os.listdir(current_dir)
print(f"Contents of {current_dir}: {directory}")
示例:创建和删除目录
# 创建目录
os.mkdir("new_directory")
print("Directory 'new_directory' created.")# 删除目录
os.rmdir("new_directory")
print("Directory 'new_directory' removed.")
2. 环境变量访问
示例:获取环境变量
# 获取环境变量
path = os.getenv("PATH")
print(f"PATH environment variable: {path}")
二、datetime
模块:时间和日期处理
datetime
模块提供了处理日期和时间的类,包括date
、time
、datetime
和timedelta
。
1. 获取当前日期和时间
示例:获取当前日期和时间
from datetime import datetime# 获取当前日期和时间
now = datetime.now()
print(f"Current date and time: {now}")
2. 日期和时间格式化
示例:格式化日期和时间
# 格式化日期和时间
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted date and time: {formatted_date}")
3. 日期和时间计算
示例:计算日期差
from datetime import datetime, timedelta# 计算日期差
date1 = datetime(2023, 1, 1)
date2 = datetime(2023, 1, 15)
delta = date2 - date1
print(f"Days between dates: {delta.days}")
三、math
模块:数学计算
math
模块提供了许多数学函数和常量,如sin
、cos
、sqrt
、pi
等。
1. 常用数学函数
示例:计算平方根
import math# 计算平方根
sqrt_value = math.sqrt(16)
print(f"Square root of 16: {sqrt_value}")
示例:计算三角函数
# 计算三角函数
sin_value = math.sin(math.pi / 2)
print(f"Sin of π/2: {sin_value}")
四、random
模块:随机数生成
random
模块提供了生成随机数的函数,适用于模拟、游戏开发等场景。
1. 生成随机数
示例:生成随机整数
import random# 生成随机整数
random_int = random.randint(1, 10)
print(f"Random integer between 1 and 10: {random_int}")
示例:生成随机浮点数
# 生成随机浮点数
random_float = random.random()
print(f"Random float between 0 and 1: {random_float}")
2. 随机选择
示例:从列表中随机选择元素
# 从列表中随机选择元素
my_list = [1, 2, 3, 4, 5]
random_choice = random.choice(my_list)
print(f"Random choice from list: {random_choice}")
五、json
模块:JSON数据处理
json
模块提供了处理JSON数据的功能,包括将Python对象编码为JSON字符串,以及将JSON字符串解码为Python对象。
1. JSON编码和解码
示例:将Python对象编码为JSON字符串
import json# 将Python对象编码为JSON字符串
data = {"name": "Alice","age": 25,"city": "Wonderland"
}
json_string = json.dumps(data)
print(f"JSON string: {json_string}")
示例:将JSON字符串解码为Python对象
# 将JSON字符串解码为Python对象
json_string = '{"name": "Alice", "age": 25, "city": "Wonderland"}'
data = json.loads(json_string)
print(f"Python object: {data}")
六、re
模块:正则表达式
re
模块提供了正则表达式的支持,用于字符串匹配、搜索和替换等操作。
1. 常用正则表达式操作
示例:匹配字符串
import re# 匹配字符串
pattern = r"^\d{3}-\d{2}-\d{4}$"
text = "123-45-6789"
if re.match(pattern, text):print("Match found!")
else:print("No match.")
示例:搜索字符串
# 搜索字符串
pattern = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b"
text = "Contact me at alice@example.com"
match = re.search(pattern, text)
if match:print(f"Email found: {match.group()}")
else:print("No email found.")
七、sys
模块:系统参数和函数
sys
模块提供了访问与Python解释器强相关的变量和函数,如命令行参数、标准输入输出等。
1. 命令行参数
示例:获取命令行参数
import sys# 获取命令行参数
print(f"Command line arguments: {sys.argv}")
2. 标准输入输出
示例:从标准输入读取数据
# 从标准输入读取数据
print("Enter your name:")
name = sys.stdin.readline().strip()
print(f"Hello, {name}!")
总结
Python标准库提供了丰富的模块和函数,使得Python能够处理各种常见的编程任务。通过本文的介绍,你已经了解了os
、datetime
、math
、random
、json
、re
和sys
等常用模块的基本用法。这些模块在实际开发中非常实用,能够帮助你高效地完成各种任务。希望这些知识能帮助你在Python编程中更加得心应手。