跳到主要内容

Python内置函数

Python 内置函数是 Python 解释器内置的函数,可以直接使用,无需导入。内置函数的功能非常丰富,涵盖了数据类型、数学运算、字符串处理、文件操作、异常处理等多个方面。

以下是 Python 内置函数的部分列表:

  • 数据类型
    • bool():将值转换为布尔值
    • int():将值转换为整数
    • float():将值转换为浮点数
    • str():将值转换为字符串
    • list():将值转换为列表
    • tuple():将值转换为元组
    • dict():将值转换为字典
  • 数学运算
    • abs():返回数的绝对值
    • round():将数四舍五入
    • pow():计算幂
    • sqrt():计算平方根
    • max():返回最大值
    • min():返回最小值
  • 字符串处理
    • len():返回字符串长度
    • upper():将字符串转换为大写
    • lower():将字符串转换为小写
    • replace():替换字符串中的子字符串
    • split():将字符串分割为列表
    • join():将列表连接为字符串
  • 文件操作
    • open():打开文件
    • read():读取文件内容
    • write():写入文件内容
    • close():关闭文件
  • 异常处理
    • try...except:异常处理
    • raise:抛出异常

以下是一些内置函数的使用示例:

# 数据类型

>>> bool(1)
True
>>> int("123")
123
>>> float("12.3")
12.3
>>> str(123)
"123"
>>> list([1, 2, 3])
[1, 2, 3]
>>> tuple([1, 2, 3])
(1, 2, 3)
>>> dict({"a": 1, "b": 2})
{"a": 1, "b": 2}

# 数学运算

>>> abs(-10)
10
>>> round(12.3456, 2)
12.35
>>> pow(2, 3)
8
>>> sqrt(9)
3.0
>>> max([1, 2, 3, 4])
4
>>> min([1, 2, 3, 4])
1

# 字符串处理

>>> len("Hello, world!")
13
>>> "Hello, world!".upper()
"HELLO, WORLD!"
>>> "Hello, world!".lower()
"hello, world!"
>>> "Hello, world!".replace("world", "Python")
"Hello, Python!"
>>> "Hello, world!".split(",")
["Hello", "world!"]
>>> ", ".join(["Hello", "world!"])
"Hello, world!"

# 文件操作

>>> f = open("test.txt", "w")
>>> f.write("This is a test file.")
>>> f.close()
>>> f = open("test.txt", "r")
>>> f.read()
"This is a test file."
>>> f.close()

# 异常处理

>>> try:
... 1 / 0
... except ZeroDivisionError:
... print("Cannot divide by zero.")
...
Cannot divide by zero.

Python 内置函数非常强大,可以帮助我们快速完成各种任务。在学习 Python 时,有必要熟悉这些内置函数的使用方法。