专业编程基础技术教程

网站首页 > 基础教程 正文

Python内置函数详解(python 常用内置函数)

ccvgpt 2025-03-20 12:49:25 基础教程 3 ℃

Python内置函数是Python语言的重要组成部分,提供了大量常用的功能,可以帮助程序员简化编程工作,提高开发效率。内置函数涵盖了数据类型转换、数学运算、字符串处理、文件操作、日期时间处理等各个方面。

1. 数据类型转换函数

数据类型转换函数用于将一种数据类型转换为另一种数据类型。常用的数据类型转换函数包括:

Python内置函数详解(python 常用内置函数)

  • int():将值转换为整数
  • float():将值转换为浮点数
  • str():将值转换为字符串
  • bool():将值转换为布尔值
  • list():将值转换为列表
  • tuple():将值转换为元组
  • set():将值转换为集合
  • dict():将值转换为字典

例如:

num = 10.23
print(int(num))  # 输出:10
print(float(num))  # 输出:10.23
print(str(num))  # 输出:'10.23'
print(bool(num))  # 输出:True

2. 数学运算函数

数学运算函数用于执行基本的数学运算,包括加、减、乘、除、模、幂等。常用的数学运算函数包括:

  • abs():计算绝对值
  • pow():计算幂
  • round():四舍五入
  • floor():向下取整
  • ceil():向上取整
  • min():返回最小值
  • max():返回最大值
  • random():生成随机数

例如:

print(abs(-5))  # 输出:5
print(pow(2, 3))  # 输出:8
print(round(3.1415926, 2))  # 输出:3.14
print(floor(5.2))  # 输出:5
print(ceil(4.8))  # 输出:5
print(min(1, 2, 3))  # 输出:1
print(max(1, 2, 3))  # 输出:3
print(random.random())  # 生成一个0到1之间的随机浮点数

3. 字符串处理函数

字符串处理函数用于处理字符串,包括查找、替换、连接、拆分等。常用的字符串处理函数包括:

  • len():计算字符串长度
  • find():查找子字符串
  • replace():替换子字符串
  • split():拆分字符串
  • join():连接字符串
  • upper():转换为大写
  • lower():转换为小写
  • strip():去除字符串两端的空格

例如:

str1 = "Hello, World!"
print(len(str1))  # 输出:11
print(str1.find("World"))  # 输出:7
print(str1.replace("World", "Python"))  # 输出:'Hello, Python!'
print(str1.split(", "))  # 输出:['Hello', 'World!']
print(",".join(["Python", "is", "fun"]))  # 输出:Python,is,fun
print(str1.upper())  # 输出:HELLO, WORLD!
print(str1.lower())  # 输出:hello, world!
print(str1.strip())  # 输出:Hello, World!

4. 文件操作函数

文件操作函数用于操作文件,包括打开、读取、写入、关闭等。常用的文件操作函数包括:

  • open():打开文件
  • read():读取文件内容
  • write():写入文件内容
  • close():关闭文件
  • os.path.exists():检查文件是否存在
  • os.path.isdir():检查是否是目录
  • os.path.isfile():检查是否是文件

例如:

with open("test.txt", "r") as f:
  content = f.read()
  print(content)

with open("test.txt", "w") as f:
  f.write("Hello, World!")

5. 日期时间处理函数

日期时间处理函数用于处理日期和时间,包括格式化、转换等。常用的日期时间处理函数包括:

  • datetime.datetime.now():获取当前日期时间
  • datetime.datetime.strptime():将字符串转换为日期时间
  • datetime.datetime.strftime():将日期时间转换为字符串
  • time.time():获取当前时间戳

最近发表
标签列表