Python常见代码

Published on
Published on
/14 mins read/---

基础操作

字符串操作

# 字符串拼接
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2  # "Hello World"
 
# 字符串格式化 (f-string, 推荐)
name = "张三"
age = 25
print(f"我叫{name},今年{age}岁。") # 我叫张三,今年25岁。
 
# 字符串格式化 (format 方法)
print("我叫{},今年{}岁。".format(name, age)) # 我叫张三,今年25岁。
 
# 字符串切片
s = "Python编程"
print(s[0:6])    # "Python" (从索引0到5)
print(s[7:])     # "编程" (从索引7到末尾)
print(s[:6])     # "Python" (从开头到索引5)
print(s[::-1])   # "程编nohtyP" (反转字符串)
 
# 常用字符串方法
text = "  Hello, Python!  "
print(text.strip())          # "Hello, Python!" (去除首尾空格)
print(text.lstrip())         # "Hello, Python!  " (去除左边空格)
print(text.rstrip())         # "  Hello, Python!" (去除右边空格)
print(text.lower())          # "  hello, python!  " (转为小写)
print(text.upper())          # "  HELLO, PYTHON!  " (转为大写)
print(text.replace("Python", "World")) # "  Hello, World!  " (替换子串)
print("python,java,c++".split(',')) # ['python', 'java', 'c++'] (分割字符串)
print("-".join(['a', 'b', 'c']))    # "a-b-c" (连接字符串列表)
print("hello".capitalize())      # "Hello" (首字母大写)
print("hello world".title())     # "Hello World" (每个单词首字母大写)
print("python".startswith("py")) # True
print("python".endswith("on"))   # True
print("python".find("th"))       # 2 (查找子串位置,找不到返回-1)
print("python".index("th"))      # 2 (查找子串位置,找不到抛出ValueError)
print("123".isdigit())           # True (是否只包含数字)
print("abc".isalpha())           # True (是否只包含字母)
print("Python3".isalnum())       # True (是否只包含字母和数字)

列表操作

# 创建列表
my_list = [1, 2, 3, "apple", True]
 
# 访问元素
print(my_list[0])    # 1
print(my_list[-1])   # True (最后一个元素)
 
# 修改元素
my_list[3] = "banana" # [1, 2, 3, "banana", True]
 
# 添加元素
my_list.append("orange")    # 在末尾添加: [1, 2, 3, "banana", True, "orange"]
my_list.insert(1, "grape")  # 在指定索引处插入: [1, "grape", 2, 3, "banana", True, "orange"]
 
# 删除元素
my_list.remove("banana") # 删除第一个匹配的元素: [1, "grape", 2, 3, True, "orange"]
popped_item = my_list.pop() # 删除并返回最后一个元素: "orange"
del my_list[0]           # 删除指定索引的元素: ["grape", 2, 3, True]
 
# 列表切片
numbers = [0, 1, 2, 3, 4, 5]
print(numbers[1:4])  # [1, 2, 3]
print(numbers[:3])   # [0, 1, 2]
print(numbers[3:])   # [3, 4, 5]
print(numbers[::2])  # [0, 2, 4] (步长为2)
 
# 列表推导式
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
even_numbers = [x for x in numbers if x % 2 == 0] # [0, 2, 4]
 
# 列表排序
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort()            # 原地升序排序: [1, 1, 2, 3, 4, 5, 6, 9]
numbers.sort(reverse=True) # 原地降序排序: [9, 6, 5, 4, 3, 2, 1, 1]
sorted_numbers = sorted([3, 1, 4]) # 返回新的排序列表: [1, 3, 4]
 
# 其他常用方法
print(len(numbers))      # 8 (列表长度)
print(min(numbers))      # 1
print(max(numbers))      # 9
print(sum(numbers))      # 31
print(numbers.count(1))  # 2 (元素出现次数)
print(numbers.index(4))  # 3 (元素首次出现位置)

字典操作

# 创建字典
person = {"name": "张三", "age": 30, "city": "北京"}
empty_dict = {}
another_dict = dict(name="李四", age=25)
 
# 访问元素
print(person["name"])          # "张三"
print(person.get("age"))       # 30
print(person.get("job", "无业")) # "无业" (键不存在时返回默认值)
 
# 修改和添加元素
person["age"] = 31
person["job"] = "工程师"
# person: {'name': '张三', 'age': 31, 'city': '北京', 'job': '工程师'}
 
# 删除元素
del person["city"]
popped_job = person.pop("job") # 删除并返回键对应的值: "工程师"
# person: {'name': '张三', 'age': 31}
 
# 遍历字典
for key in person:
    print(key, person[key])
 
for key, value in person.items():
    print(f"{key}: {value}")
 
for value in person.values():
    print(value)
 
# 字典推导式
squares = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
 
# 其他常用方法
print(len(person))        # 2 (键值对数量)
print("name" in person)   # True (检查键是否存在)
person_copy = person.copy()
person.clear()          # 清空字典

集合操作

# 创建集合 (无序,不重复)
set1 = {1, 2, 3, 3, 4} # {1, 2, 3, 4}
set2 = set([3, 4, 5, 6]) # {3, 4, 5, 6}
empty_set = set()
 
# 添加和删除元素
set1.add(5)        # {1, 2, 3, 4, 5}
set1.remove(1)     # {2, 3, 4, 5} (元素不存在会报错)
set1.discard(10)   # (元素不存在不会报错)
popped_element = set1.pop() # 随机删除一个元素并返回
 
# 集合运算
s1 = {1, 2, 3}
s2 = {3, 4, 5}
print(s1.union(s2))          # 并集: {1, 2, 3, 4, 5}  (s1 | s2)
print(s1.intersection(s2))   # 交集: {3} (s1 & s2)
print(s1.difference(s2))     # 差集 (s1中有,s2中没有): {1, 2} (s1 - s2)
print(s2.difference(s1))     # 差集 (s2中有,s1中没有): {4, 5} (s2 - s1)
print(s1.symmetric_difference(s2)) # 对称差集 (并集 - 交集): {1, 2, 4, 5} (s1 ^ s2)
 
# 其他常用方法
print(len(set1))       # 集合大小
print(2 in set1)       # True (检查元素是否存在)
s1.issubset(s2)      # s1是否是s2的子集
s2.issuperset(s1)    # s2是否是s1的超集

函数和装饰器

函数定义与参数

# 基本函数
def greet(name):
    return f"Hello, {name}!"
 
# 带默认参数的函数
def greet_default(name, greeting="Hi"):
    return f"{greeting}, {name}!"
 
# 可变参数 (*args)
def sum_all(*numbers):
    total = 0
    for num in numbers:
        total += num
    return total
print(sum_all(1, 2, 3)) # 6
 
# 关键字参数 (**kwargs)
def print_info(**info):
    for key, value in info.items():
        print(f"{key}: {value}")
print_info(name="Alice", age=25, city="New York")
 
# Lambda 匿名函数
multiply = lambda x, y: x * y
print(multiply(3, 4)) # 12
 
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers)) # [1, 4, 9, 16, 25]

装饰器

import time
 
def timer_decorator(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"函数 {func.__name__} 执行耗时: {end_time - start_time:.4f} 秒")
        return result
    return wrapper
 
@timer_decorator
def my_function(delay):
    time.sleep(delay)
    print("函数执行完毕!")
 
my_function(1)

文件操作

读写文件

# 写文件 (如果文件不存在则创建,存在则覆盖)
with open("example.txt", "w", encoding="utf-8") as f:
    f.write("你好,世界!\n")
    f.write("这是第二行。\n")
 
# 追加内容到文件
with open("example.txt", "a", encoding="utf-8") as f:
    f.write("这是追加的内容。\n")
 
# 读文件
with open("example.txt", "r", encoding="utf-8") as f:
    content = f.read() # 读取全部内容
    print("--- 全部内容 ---")
    print(content)
 
with open("example.txt", "r", encoding="utf-8") as f:
    print("--- 按行读取 ---")
    for line in f: # 逐行读取 (推荐,内存友好)
        print(line.strip()) # strip() 去除换行符
 
with open("example.txt", "r", encoding="utf-8") as f:
    lines = f.readlines() # 读取所有行到一个列表
    print("--- 读取所有行为列表 ---")
    print(lines)

CSV文件操作

import csv
 
# 写入 CSV 文件
data_to_write = [
    ["姓名", "年龄", "城市"],
    ["张三", 30, "北京"],
    ["李四", 25, "上海"]
]
with open("data.csv", "w", newline="", encoding="utf-8") as csvfile:
    writer = csv.writer(csvfile)
    writer.writerows(data_to_write)
 
# 读取 CSV 文件
with open("data.csv", "r", encoding="utf-8") as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        print(row)

异常处理

try:
    num = int(input("请输入一个数字: "))
    result = 10 / num
    print(f"10 / {num} = {result}")
except ValueError:
    print("输入无效,请输入一个整数。")
except ZeroDivisionError:
    print("错误:除数不能为零。")
except Exception as e: # 捕获所有其他类型的异常
    print(f"发生了一个未知错误: {e}")
else: # 如果 try 块没有发生异常,则执行
    print("计算成功,没有发生异常。")
finally: # 无论是否发生异常,总会执行
    print("异常处理结束。")
 
# 自定义异常
class MyCustomError(Exception):
    def __init__(self, message):
        self.message = message
        super().__init__(self.message)
 
# raise MyCustomError("这是一个自定义错误!")

常用模块

datetime - 日期和时间

from datetime import datetime, timedelta, date
 
# 获取当前日期和时间
now = datetime.now()
print(f"当前时间: {now}")
 
# 获取当前日期
today = date.today()
print(f"今天日期: {today}")
 
# 创建特定日期时间
dt = datetime(2024, 7, 20, 10, 30, 0)
print(f"指定时间: {dt}")
 
# 格式化日期时间为字符串
formatted_dt = now.strftime("%Y-%m-%d %H:%M:%S") # 年-月-日 时:分:秒
print(f"格式化后: {formatted_dt}")
 
# 从字符串解析日期时间
date_str = "2023-01-15 14:45:00"
parsed_dt = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print(f"解析后: {parsed_dt}")
 
# 时间差计算
one_day = timedelta(days=1)
yesterday = now - one_day
tomorrow = now + one_day
print(f"昨天: {yesterday.strftime('%Y-%m-%d')}")
print(f"明天: {tomorrow.strftime('%Y-%m-%d')}")
 
diff = tomorrow - yesterday
print(f"时间差: {diff.days} 天, {diff.total_seconds()} 秒")

json - JSON 数据处理

import json
 
# Python 字典
data_dict = {
    "name": "Alice",
    "age": 30,
    "isStudent": False,
    "courses": [
        {"title": "Math", "credits": 3},
        {"title": "History", "credits": 2}
    ]
}
 
# 将 Python 字典转换为 JSON 字符串
json_string = json.dumps(data_dict, indent=4, ensure_ascii=False) # indent美化输出, ensure_ascii处理中文
print("--- JSON 字符串 ---")
print(json_string)
 
# 将 JSON 字符串转换为 Python 字典
parsed_data = json.loads(json_string)
print("--- 解析后的 Python 字典 ---")
print(parsed_data["name"])
print(parsed_data["courses"][0]["title"])

re - 正则表达式

import re
 
text = "我的电话号码是 13812345678, 另一个是 15987654321。"
pattern = r"\b1[3-9]\d{9}\b" # 匹配中国大陆手机号
 
# 查找所有匹配项
phone_numbers = re.findall(pattern, text)
print(f"找到的手机号: {phone_numbers}") # ['13812345678', '15987654321']
 
# 查找第一个匹配项
match = re.search(pattern, text)
if match:
    print(f"第一个匹配的手机号: {match.group(0)}") # 13812345678
 
# 替换匹配项
new_text = re.sub(pattern, "[已隐藏]", text)
print(f"替换后的文本: {new_text}")
 
# 分割字符串
s = "apple,banana;orange grape"
parts = re.split(r"[,;\s]+", s) # 按逗号、分号或空格分割
print(f"分割结果: {parts}") # ['apple', 'banana', 'orange', 'grape']

random - 生成随机数

import random
 
# 生成一个 0.0 <= x < 1.0 之间的随机浮点数
print(random.random())
 
# 生成一个 a <= x <= b 之间的随机整数
print(random.randint(1, 10))
 
# 生成一个 a <= x < b 之间的随机整数
print(random.randrange(1, 10)) # 1 到 9
 
# 从序列中随机选择一个元素
my_list = ["apple", "banana", "cherry", "date"]
print(random.choice(my_list))
 
# 从序列中随机选择 k 个不重复的元素
print(random.sample(my_list, 2))
 
# 打乱序列中的元素 (原地操作)
random.shuffle(my_list)
print(f"打乱后: {my_list}")

os 和 os.path - 操作系统交互和路径操作

import os
import shutil # 用于高级文件操作,如复制、移动
 
# 获取当前工作目录
current_dir = os.getcwd()
print(f"当前目录: {current_dir}")
 
# 列出目录内容
print(f"当前目录内容: {os.listdir('.')}") # '.' 表示当前目录
 
# 创建目录
if not os.path.exists("my_new_folder"):
    os.makedirs("my_new_folder/subfolder") # makedirs可以创建多级目录
    print("目录已创建")
 
# 路径拼接 (推荐,跨平台)
file_path = os.path.join(current_dir, "my_new_folder", "test.txt")
print(f"拼接路径: {file_path}")
 
# 检查路径是否存在
print(f"路径 {file_path} 是否存在: {os.path.exists(file_path)}")
print(f"路径 {file_path} 是否是文件: {os.path.isfile(file_path)}")
print(f"路径 my_new_folder 是否是目录: {os.path.isdir('my_new_folder')}")
 
# 获取文件名和目录名
print(f"目录名: {os.path.dirname(file_path)}")
print(f"文件名: {os.path.basename(file_path)}")
print(f"分割路径和文件名: {os.path.split(file_path)}")
print(f"获取文件扩展名: {os.path.splitext(file_path)[1]}") # (root, ext)
 
# 示例:删除创建的目录和文件 (小心使用!)
# if os.path.exists("my_new_folder"):
#     shutil.rmtree("my_new_folder") # rmtree可以删除非空目录
#     print("目录已删除")

高级特性

生成器 (Generators)

# 生成器函数
def count_up_to(max_val):
    count = 1
    while count <= max_val:
        yield count # yield 使函数成为生成器
        count += 1
 
# 使用生成器
counter = count_up_to(5)
for num in counter:
    print(num) # 1 2 3 4 5
 
# 生成器表达式 (类似列表推导式,但使用圆括号)
squares_gen = (x*x for x in range(5))
for sq in squares_gen:
    print(sq) # 0 1 4 9 16

上下文管理器 (Context Managers) 和 with 语句

# 文件操作是内置的上下文管理器
# with open("example.txt", "r") as f:
#     content = f.read()
# 自动处理文件的打开和关闭,即使发生错误
 
# 自定义上下文管理器
class MyResource:
    def __init__(self, name):
        self.name = name
        print(f"资源 '{self.name}' 初始化...")
 
    def __enter__(self):
        print(f"进入资源 '{self.name}' 的上下文...")
        return self # 返回的对象可以在 as 子句中使用
 
    def __exit__(self, exc_type, exc_val, exc_tb):
        # exc_type, exc_val, exc_tb 用于异常处理
        print(f"退出资源 '{self.name}' 的上下文...")
        if exc_type:
            print(f"发生异常: {exc_type}, {exc_val}")
        return False # 如果返回 True,则异常被抑制
 
with MyResource("DBConnection") as resource:
    print(f"使用资源 '{resource.name}'...")
    # raise ValueError("模拟错误") # 取消注释以测试异常处理
print("在 with 语句之后。")