11、Python常用函数示例和用法说明

一、timedelta类使用指南

timedelta 对象表示两个日期或时间之间的差异。它可以包含天数(days)、秒数(seconds)和微秒数(microseconds)。你可以使用这些属性来创建时间间隔,并将它们应用到日期和时间对象

通过指定天数、秒数、分钟数、小时数等参数来创建一个 timedelta 对象

一旦创建了 timedelta 对象,你可以将其添加到或从 datetime 对象中减去,以执行日期和时间的计算。

from datetime import timedelta

# 创建一个表示7天的时间间隔

one_week = timedelta(days=7)

# 创建一个表示1小时30分钟的时间间隔

one_hour_thirty_minutes = timedelta(hours=1, minutes=30)

# 创建一个表示2天5小时30秒的时间间隔

two_days_five_hours_thirty_seconds = timedelta(days=2, hours=5, seconds=30)

二、常用函数注意事项;

  • 字符串是不可变的,所有字符串操作都会返回新的字符串
  • 列表操作中,有些方法会改变原列表(如 append),有些会返回新列表(如 sorted)
  • 文件操作记得及时关闭文件(使用 with 语句最安全)
  • 日期时间操作要注意时区问题

三、强化记忆,哪些修改了原表,哪些不修改原表

1、会改变原列表的操作(修改型操作):

特点:这些都是列表的方法,用.调用,通常返回none

主要包括:

增:append insert

删:pop remove clear

改:sort reverse

2、不会改变原列表的操作(返回新列表)

特点:这些函数或运算符操作,返回新的列表

主要包括:

函数:sorted(),list(),reversed()

运算:切片[:]  加法+ 乘法*

查询:len() max() min() sum()

3.快速判断方法

        1.看调用方式:

  • 用点号调用的方法(如 list.append())通常会改变原列表

        2.看返回值:

  • 如果方法返回 None,通常会改变原列表
  • 如果返回新的列表,通常不会改变原列表

        3.看操作类型:

  • 涉及修改的操作(增删改)通常会改变原列表
  • 涉及查询的操作通常不会改变原列表

4.常见示例对比:

  1. 排序操作对比:
  • numbers.sort() - 改变原列表
  • sorted(numbers) - 不改变原列表,返回新列表
  1. 反转操作对比:
  • numbers.reverse() - 改变原列表
  • numbers[::-1] - 不改变原列表,返回新列表
  1. 添加元素对比:
  • numbers.append(x) - 改变原列表
  • numbers + [x] - 不改变原列表,返回新列表

tips:数据函数round采用的是“向偶数舍入”的规则,意思就是向上入的必须是偶数,示例如下:

round(2.5) 结果是 2(而不是 3),因为 2 是偶数。

round(3.5) 结果是 4,因为 4 是偶数。

round(5.5) 结果是 6,因为 6 是偶数。

三、字符串函数大全

字符串常用函数:
print("*" * 50)
text = "hello world"
print(f"标题化: {text.title()}")
print(f"大写: {text.upper()}")
print(f"小写: {text.lower()}")
print(f"分割: {text.split()}")
print(f"替换: {text.replace('world','python')}")
print(f"查找: {text.find('world')}")
print(f"o出现的次数: {text.count('o')}")
print(f"是否以h开头: {text.startswith('h')}")
print(f"是否以d结尾: {text.endswith('d')}")
print(f"是否全是字母: {text.isalpha()}")
print(f"是否全是数字: {text.isdigit()}")
print(f"是否全是数字或字母: {text.isalnum()}")
print(f"是否全是空白字符: {text.isspace()}")
print(f"是否全是小写字母: {text.islower()}")
print(f"是否全是大写字母: {text.isupper()}")
print("*" * 50)

结果
**************************************************
标题化: Hello World
大写: HELLO WORLD
小写: hello world
分割: ['hello', 'world']
替换: hello python
查找: 6
o出现的次数: 2
是否以h开头: True
是否以d结尾: True
是否全是字母: False
是否全是数字: False
是否全是数字或字母: False
是否全是空白字符: False
是否全是小写字母: True
是否全是大写字母: False
**************************************************

四、字符串、字典、列表、日期函数、数学函数、集合 使用方法大全

"""
Python常用函数示例和用法说明
作用:展示Python中最常用的内置函数和操作方法
"""


#######################
# 1. 字符串操作函数演示 #
#######################
def string_operations_demo():
    print("1. 字符串操作示例:")
    print("-" * 50)

    # 基本字符串
    text = "Hello Python Programming"

    # 长度计算
    print(f"字符串长度: {len(text)}")  # len()计算字符串长度

    # 大小写转换
    print(f"转大写: {text.upper()}")  # 将所有字符转为大写
    print(f"转小写: {text.lower()}")  # 将所有字符转为小写
    print(f"首字母大写: {text.title()}")  # 每个单词首字母大写

    # 字符串分割与合并
    words = text.split(" ")  # 按空格分割字符串为列表
    print(f"分割结果: {words}")
    print(f"合并结果: {'|'.join(words)}")  # 用'|'连接列表中的元素

    # 去除空白字符
    text_with_spaces = "   Python   "
    print(f"去除两端空格: '{text_with_spaces.strip()}'")  # 去除两端空格
    print(f"去除左侧空格: '{text_with_spaces.lstrip()}'")  # 去除左侧空格
    print(f"去除右侧空格: '{text_with_spaces.rstrip()}'")  # 去除右侧空格


#######################
# 2. 列表操作函数演示   #
#######################
def list_operations_demo():
    print("\n2. 列表操作示例:")
    print("-" * 50)
    print("【会改变原列表的操作】与【不会改变原列表的操作】对比:")
    print("-" * 50)

    # 创建原始列表
    numbers = [1, 5, 2, 8, 3, 9, 7]
    print(f"原始列表: {numbers}")
    print("\n1. 会改变原列表的操作(修改型操作):")
    print("-" * 30)

    # 1.1 append - 在末尾添加元素
    numbers_copy = numbers.copy()
    numbers_copy.append(10)
    print(f"append后: {numbers_copy}")

    # 1.2 insert - 在指定位置插入
    numbers_copy.insert(0, 0)
    print(f"insert后: {numbers_copy}")

    # 1.3 remove - 删除指定元素
    numbers_copy.remove(5)
    print(f"remove后: {numbers_copy}")

    # 1.4 pop - 弹出元素
    popped = numbers_copy.pop()
    print(f"pop后: {numbers_copy}, 弹出: {popped}")

    # 1.5 sort - 排序
    numbers_copy.sort()
    print(f"sort后: {numbers_copy}")

    # 1.6 reverse - 反转
    numbers_copy.reverse()
    print(f"reverse后: {numbers_copy}")

    # 1.7 clear - 清空列表
    numbers_copy.clear()
    print(f"clear后: {numbers_copy}")

    print("\n2. 不会改变原列表的操作(返回新列表):")
    print("-" * 30)

    # 2.1 切片操作
    print(f"原列表: {numbers}")
    print(f"切片[1:4]: {numbers[1:4]}")
    print(f"切片后原列表: {numbers}")

    # 2.2 sorted函数
    print(f"sorted排序结果: {sorted(numbers)}")
    print(f"sorted后原列表: {numbers}")

    # 2.3 列表拼接
    print(f"列表拼接结果: {numbers + [10, 11]}")
    print(f"拼接后原列表: {numbers}")

    # 2.4 列表乘法
    print(f"列表乘2结果: {numbers * 2}")
    print(f"乘法后原列表: {numbers}")

    print("\n记忆规律总结:")
    print("-" * 30)
    print("1. 会改变原列表的操作(方法):")
    print("   - 所有直接对列表操作的方法(返回None)")
    print("   - append(), insert(), remove(), pop()")
    print("   - sort(), reverse(), clear(), extend()")
    print("\n2. 不会改变原列表的操作(函数/运算):")
    print("   - 所有返回新列表的函数:sorted(), +, *, 切片[:]")
    print("   - 所有查询操作:len(), max(), min(), sum(), count(), index()")


#######################
# 3. 字典操作函数演示   #
#######################
def dict_operations_demo():
    print("\n3. 字典操作示例:")
    print("-" * 50)
    print("【会改变原字典的操作】与【不会改变原字典的操作】对比:")
    print("-" * 50)

    # 创建原始字典
    person = {"name": "张三", "age": 25, "skills": ["Python", "Java"]}
    print(f"原始字典: {person}")

    print("\n1. 会改变原字典的操作(修改型操作):")
    print("-" * 30)

    # 1.1 更新或添加元素
    person_copy = person.copy()  # 创建副本进行演示
    person_copy["city"] = "北京"  # 使用索引添加新键值对
    print(f"索引添加后: {person_copy}")

    # 1.2 update方法 - 批量更新
    person_copy.update({"age": 26, "salary": 10000})
    print(f"update后: {person_copy}")

    # 1.3 pop方法 - 删除并返回值
    removed_age = person_copy.pop("age")
    print(f"pop('age')后: {person_copy}, 删除的值: {removed_age}")

    # 1.4 popitem方法 - 删除并返回最后的键值对
    last_item = person_copy.popitem()
    print(f"popitem后: {person_copy}, 删除的键值对: {last_item}")

    # 1.5 clear方法 - 清空字典
    person_copy.clear()
    print(f"clear后: {person_copy}")

    print("\n2. 不会改变原字典的操作(返回新数据):")
    print("-" * 30)
    print(f"原字典: {person}")  # 显示原字典保持不变

    # 2.1 get方法 - 安全访问
    print(f"get('name'): {person.get('name')}")
    print(f"get不存在的键: {person.get('height', '不存在')}")

    # 2.2 keys, values, items方法
    print(f"获取所有键: {person.keys()}")
    print(f"获取所有值: {person.values()}")
    print(f"获取所有键值对: {person.items()}")

    # 2.3 copy方法 - 浅拷贝
    person_copy = person.copy()
    print(f"copy后的新字典: {person_copy}")

    # 2.4 字典推导式 - 创建新字典
    upper_dict = {k.upper(): v for k, v in person.items() if isinstance(k, str)}
    print(f"字典推导式结果: {upper_dict}")

    print("\n记忆规律总结:")
    print("-" * 30)
    print("1. 会改变原字典的操作(修改型操作):")
    print("   - 直接索引赋值:dict[key] = value")
    print("   - 更新方法:update()")
    print("   - 删除方法:pop(), popitem(), clear()")
    print("   - setdefault(), del dict[key]")

    print("\n2. 不会改变原字典的操作(返回新数据):")
    print("   - 所有查询方法:get(), keys(), values(), items()")
    print("   - 复制方法:copy(), dict()")
    print("   - 运算符:in, not in")
    print("   - len(), max(), min(), sum()")

    print("\n3. 特别注意:")
    print("   - 字典是可变类型,默认浅拷贝")
    print("   - 如果需要完全独立的副本,使用deepcopy")


#######################
# 4. 数学函数演示      #
#######################
def math_operations_demo():
    import math

    print("\n4. 数学函数示例:")
    print("-" * 50)

    # 基本数学运算
    print(f"绝对值: {abs(-5)}")
    print(f"向上取整: {math.ceil(4.1)}")
    print(f"向下取整: {math.floor(4.9)}")
    print(f"四舍五入: {round(4.5)}")
    print(f"取整: {math.trunc(4.5)}")

    # 高级数学运算
    print(f"平方根: {math.sqrt(16)}")
    print(f"幂运算: {math.pow(2, 3)}")
    print(f"π值: {math.pi}")
    print(f"e值: {math.e}")


#######################
# 5. 日期时间函数演示   #
#######################
def datetime_operations_demo():
    from datetime import datetime, timedelta

    print("\n5. 日期时间操作示例:")
    print("-" * 50)

    # 获取当前时间
    now = datetime.now()
    print(f"当前时间: {now}")

    # 时间格式化
    formatted = now.strftime("%Y年%m月%d日 %H:%M:%S")
    print(f"格式化时间: {formatted}")

    # 时间计算
    tomorrow = now + timedelta(days=1)
    print(f"明天: {tomorrow}")

    next_week = now + timedelta(weeks=1)
    print(f"下周: {next_week}")


#######################
# 6. 集合操作函数演示   #
#######################
def set_operations_demo():
    print("\n6. 集合操作示例:")
    print("-" * 50)

    # 创建集合
    set1 = {1, 2, 3, 4, 5}
    set2 = {4, 5, 6, 7, 8}

    # 集合运算
    print(f"并集: {set1.union(set2)}")  # 或使用 set1 | set2
    print(f"交集: {set1.intersection(set2)}")  # 或使用 set1 & set2
    print(f"差集: {set1.difference(set2)}")  # 或使用 set1 - set2
    print(f"对称差集: {set1.symmetric_difference(set2)}")  # 或使用 set1 ^ set2


# 运行所有示例
if __name__ == "__main__":
    string_operations_demo()
    list_operations_demo()
    dict_operations_demo()
    math_operations_demo()
    datetime_operations_demo()
    set_operations_demo()


结果:
1. 字符串操作示例:
--------------------------------------------------
字符串长度: 24
转大写: HELLO PYTHON PROGRAMMING
转小写: hello python programming
首字母大写: Hello Python Programming
分割结果: ['Hello', 'Python', 'Programming']
合并结果: Hello|Python|Programming
去除两端空格: 'Python'
去除左侧空格: 'Python   '
去除右侧空格: '   Python'

2. 列表操作示例:
--------------------------------------------------
【会改变原列表的操作】与【不会改变原列表的操作】对比:
--------------------------------------------------
原始列表: [1, 5, 2, 8, 3, 9, 7]

1. 会改变原列表的操作(修改型操作):
------------------------------
append后: [1, 5, 2, 8, 3, 9, 7, 10]
insert后: [0, 1, 5, 2, 8, 3, 9, 7, 10]
remove后: [0, 1, 2, 8, 3, 9, 7, 10]
pop后: [0, 1, 2, 8, 3, 9, 7], 弹出: 10
sort后: [0, 1, 2, 3, 7, 8, 9]
reverse后: [9, 8, 7, 3, 2, 1, 0]
clear后: []

2. 不会改变原列表的操作(返回新列表):
------------------------------
原列表: [1, 5, 2, 8, 3, 9, 7]
切片[1:4]: [5, 2, 8]
切片后原列表: [1, 5, 2, 8, 3, 9, 7]
sorted排序结果: [1, 2, 3, 5, 7, 8, 9]
sorted后原列表: [1, 5, 2, 8, 3, 9, 7]
列表拼接结果: [1, 5, 2, 8, 3, 9, 7, 10, 11]
拼接后原列表: [1, 5, 2, 8, 3, 9, 7]
列表乘2结果: [1, 5, 2, 8, 3, 9, 7, 1, 5, 2, 8, 3, 9, 7]
乘法后原列表: [1, 5, 2, 8, 3, 9, 7]

记忆规律总结:
------------------------------
1. 会改变原列表的操作(方法):
   - 所有直接对列表操作的方法(返回None)
   - append(), insert(), remove(), pop()
   - sort(), reverse(), clear(), extend()

2. 不会改变原列表的操作(函数/运算):
   - 所有返回新列表的函数:sorted(), +, *, 切片[:]
   - 所有查询操作:len(), max(), min(), sum(), count(), index()

3. 字典操作示例:
--------------------------------------------------
【会改变原字典的操作】与【不会改变原字典的操作】对比:
--------------------------------------------------
原始字典: {'name': '张三', 'age': 25, 'skills': ['Python', 'Java']}

1. 会改变原字典的操作(修改型操作):
------------------------------
索引添加后: {'name': '张三', 'age': 25, 'skills': ['Python', 'Java'], 'city': '北京'}
update后: {'name': '张三', 'age': 26, 'skills': ['Python', 'Java'], 'city': '北京', 'salary': 10000}
pop('age')后: {'name': '张三', 'skills': ['Python', 'Java'], 'city': '北京', 'salary': 10000}, 删除的值: 26
popitem后: {'name': '张三', 'skills': ['Python', 'Java'], 'city': '北京'}, 删除的键值对: ('salary', 10000)
clear后: {}

2. 不会改变原字典的操作(返回新数据):
------------------------------
原字典: {'name': '张三', 'age': 25, 'skills': ['Python', 'Java']}
get('name'): 张三
get不存在的键: 不存在
获取所有键: dict_keys(['name', 'age', 'skills'])
获取所有值: dict_values(['张三', 25, ['Python', 'Java']])
获取所有键值对: dict_items([('name', '张三'), ('age', 25), ('skills', ['Python', 'Java'])])
copy后的新字典: {'name': '张三', 'age': 25, 'skills': ['Python', 'Java']}
字典推导式结果: {'NAME': '张三', 'AGE': 25, 'SKILLS': ['Python', 'Java']}

记忆规律总结:
------------------------------
1. 会改变原字典的操作(修改型操作):
   - 直接索引赋值:dict[key] = value
   - 更新方法:update()
   - 删除方法:pop(), popitem(), clear()
   - setdefault(), del dict[key]

2. 不会改变原字典的操作(返回新数据):
   - 所有查询方法:get(), keys(), values(), items()
   - 复制方法:copy(), dict()
   - 运算符:in, not in
   - len(), max(), min(), sum()

3. 特别注意:
   - 字典是可变类型,默认浅拷贝
   - 如果需要完全独立的副本,使用deepcopy

4. 数学函数示例:
--------------------------------------------------
绝对值: 5
向上取整: 5
向下取整: 4
四舍五入: 4
取整: 4
平方根: 4.0
幂运算: 8.0
π值: 3.141592653589793
e值: 2.718281828459045

5. 日期时间操作示例:
--------------------------------------------------
当前时间: 2025-03-10 19:43:52.885496
格式化时间: 2025年03月10日 19:43:52
明天: 2025-03-11 19:43:52.885496
下周: 2025-03-17 19:43:52.885496

6. 集合操作示例:
--------------------------------------------------
并集: {1, 2, 3, 4, 5, 6, 7, 8}
交集: {4, 5}
差集: {1, 2, 3}
对称差集: {1, 2, 3, 6, 7, 8}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值