处理日期和时间的标准库。
from datetime import datetime, date, time, timedelta
# 获取当前日期时间
now = datetime.now()
print(now) # 2024-01-18 15:30:45.123456
# 获取当前日期
today = date.today()
print(today) # 2024-01-18
# 创建特定日期时间
dt = datetime(2024, 1, 18, 15, 30, 0)
print(dt)
# 格式化日期时间
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted) # 2024-01-18 15:30:45
# 解析字符串为日期时间
date_str = "2024-01-18"
dt = datetime.strptime(date_str, "%Y-%m-%d")
# 时间运算
tomorrow = today + timedelta(days=1)
next_week = today + timedelta(weeks=1)
print(f"明天: {tomorrow}")
print(f"下周: {next_week}")
# 计算时间差
dt1 = datetime(2024, 1, 1)
dt2 = datetime(2024, 12, 31)
diff = dt2 - dt1
print(f"相差{diff.days}天")
生成随机数和进行随机选择。
import random
# 随机整数
num = random.randint(1, 10) # 1到10之间的随机整数
print(num)
# 随机浮点数
float_num = random.random() # 0到1之间的随机浮点数
print(float_num)
# 指定范围的随机浮点数
uniform_num = random.uniform(1.0, 10.0)
print(uniform_num)
# 从序列中随机选择
colors = ["红", "绿", "蓝", "黄"]
color = random.choice(colors)
print(color)
# 随机选择多个元素
sample = random.sample(colors, 2)
print(sample)
# 打乱列表
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(numbers)
# 设置随机种子(用于可重复的随机结果)
random.seed(42)
print(random.randint(1, 100))
用于字符串模式匹配和搜索。
import re
# 搜索模式
text = "我的电话是13800138000,邮箱是example@email.com"
# 查找第一个匹配
match = re.search(r'\d{11}', text)
if match:
print(f"找到电话: {match.group()}")
# 查找所有匹配
phones = re.findall(r'\d{11}', text)
print(phones)
# 匹配邮箱
email = re.search(r'[\w\.-]+@[\w\.-]+\.\w+', text)
if email:
print(f"找到邮箱: {email.group()}")
# 替换
new_text = re.sub(r'\d{11}', '***********', text)
print(new_text)
# 分割字符串
text = "apple,banana;orange:grape"
fruits = re.split(r'[,;:]', text)
print(fruits)
# 编译正则表达式(提高性能)
pattern = re.compile(r'\d{11}')
matches = pattern.findall(text)
# 常用模式
# \d - 数字
# \w - 字母数字下划线
# \s - 空白字符
# . - 任意字符
# * - 0次或多次
# + - 1次或多次
# ? - 0次或1次
# {n} - 恰好n次
# {n,m} - n到m次
提供额外的数据结构。
from collections import Counter, defaultdict, deque, namedtuple
# Counter - 计数器
words = ["apple", "banana", "apple", "orange", "banana", "apple"]
counter = Counter(words)
print(counter) # Counter({'apple': 3, 'banana': 2, 'orange': 1})
print(counter.most_common(2)) # [('apple', 3), ('banana', 2)]
# defaultdict - 带默认值的字典
dd = defaultdict(int)
dd['a'] += 1
dd['b'] += 2
print(dd) # defaultdict(, {'a': 1, 'b': 2})
# deque - 双端队列
dq = deque([1, 2, 3])
dq.append(4) # 右端添加
dq.appendleft(0) # 左端添加
dq.pop() # 右端删除
dq.popleft() # 左端删除
print(dq)
# namedtuple - 命名元组
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(p.x, p.y) # 10 20
from itertools import count, cycle, repeat, chain, combinations, permutations
# count - 无限计数
for i in count(10, 2):
if i > 20:
break
print(i) # 10, 12, 14, 16, 18, 20
# cycle - 循环迭代
colors = cycle(['红', '绿', '蓝'])
for i, color in enumerate(colors):
if i >= 6:
break
print(color)
# chain - 连接多个迭代器
list1 = [1, 2, 3]
list2 = [4, 5, 6]
for item in chain(list1, list2):
print(item)
# combinations - 组合
items = ['A', 'B', 'C']
for combo in combinations(items, 2):
print(combo) # ('A', 'B'), ('A', 'C'), ('B', 'C')
# permutations - 排列
for perm in permutations(items, 2):
print(perm) # ('A', 'B'), ('A', 'C'), ('B', 'A'), ...
import sys
# 命令行参数
print(sys.argv) # 脚本名和参数列表
# Python版本
print(sys.version)
# 平台信息
print(sys.platform) # 'win32', 'linux', 'darwin'
# 退出程序
# sys.exit(0)
# 标准输入输出
sys.stdout.write("Hello\n")
line = sys.stdin.readline()
# 模块搜索路径
print(sys.path)
import math
# 常量
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
# 基本运算
print(math.sqrt(16)) # 4.0 平方根
print(math.pow(2, 3)) # 8.0 幂运算
print(math.ceil(4.3)) # 5 向上取整
print(math.floor(4.7)) # 4 向下取整
print(math.fabs(-5)) # 5.0 绝对值
# 三角函数
print(math.sin(math.pi/2)) # 1.0
print(math.cos(0)) # 1.0
print(math.tan(math.pi/4)) # 1.0
# 对数
print(math.log(10)) # 自然对数
print(math.log10(100)) # 2.0 以10为底
print(math.log2(8)) # 3.0 以2为底
from urllib import request, parse
# 发送HTTP请求
url = "https://api.example.com/data"
response = request.urlopen(url)
data = response.read().decode('utf-8')
print(data)
# URL编码
params = {'name': '张三', 'age': 25}
encoded = parse.urlencode(params)
print(encoded) # name=%E5%BC%A0%E4%B8%89&age=25
# URL解析
parsed = parse.urlparse('https://example.com/path?key=value')
print(parsed.scheme) # https
print(parsed.netloc) # example.com
print(parsed.path) # /path
import argparse
# 创建解析器
parser = argparse.ArgumentParser(description='程序描述')
# 添加参数
parser.add_argument('filename', help='文件名')
parser.add_argument('-v', '--verbose', action='store_true', help='详细输出')
parser.add_argument('-n', '--number', type=int, default=10, help='数字参数')
# 解析参数
args = parser.parse_args()
print(f"文件名: {args.filename}")
print(f"详细模式: {args.verbose}")
print(f"数字: {args.number}")
# 使用示例:
# python script.py data.txt -v -n 20
# 练习1:计算年龄
from datetime import datetime, date
birthday = date(2000, 1, 1)
today = date.today()
age_days = (today - birthday).days
print(f"你已经活了{age_days}天")
# 练习2:彩票号码
import random
lottery = random.sample(range(1, 50), 6)
lottery.sort()
print(f"彩票号码: {lottery}")
# 练习3:邮箱验证
import re
def validate_email(email):
pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
return re.match(pattern, email) is not None
print(validate_email("test@example.com")) # True
print(validate_email("invalid.email")) # False
# 练习4:字符统计
from collections import Counter
text = "hello world"
char_count = Counter(text)
print(char_count)
print(f"最常见的3个字符: {char_count.most_common(3)}")