🔧 21. 内置函数大全
Python 常用内置函数速查表,方便快速查阅。
预计学习时间:30 分钟(浏览)
21.1 数学运算
| 函数 | 说明 | 示例 |
|---|
abs(x) | 绝对值 | abs(-5) → 5 |
round(x, n) | 四舍五入 | round(3.14159, 2) → 3.14 |
pow(x, y) | x的y次方 | pow(2, 3) → 8 |
divmod(a, b) | 商和余数 | divmod(10, 3) → (3, 1) |
max(iterable) | 最大值 | max([1, 5, 3]) → 5 |
min(iterable) | 最小值 | min([1, 5, 3]) → 1 |
sum(iterable) | 求和 | sum([1, 2, 3]) → 6 |
len(s) | 长度 | len("hello") → 5 |
print(abs(-10)) # 10
print(round(3.7)) # 4
print(pow(2, 10)) # 1024
print(divmod(17, 5)) # (3, 2)
print(max(3, 7, 2)) # 7
print(min(3, 7, 2)) # 2
print(sum([1, 2, 3, 4, 5])) # 15
print(len("Python")) # 6
21.2 类型转换
| 函数 | 说明 | 示例 |
|---|
int(x) | 转整数 | int("123") → 123 |
float(x) | 转浮点数 | float("3.14") → 3.14 |
str(x) | 转字符串 | str(123) → "123" |
bool(x) | 转布尔值 | bool(0) → False |
list(x) | 转列表 | list("abc") → ['a','b','c'] |
tuple(x) | 转元组 | tuple([1,2,3]) → (1,2,3) |
set(x) | 转集合 | set([1,2,2,3]) → {1,2,3} |
dict(x) | 转字典 | dict([('a',1)]) → {'a':1} |
chr(x) | 数字转字符 | chr(65) → 'A' |
ord(x) | 字符转数字 | ord('A') → 65 |
hex(x) | 转十六进制 | hex(255) → '0xff' |
oct(x) | 转八进制 | oct(8) → '0o10' |
bin(x) | 转二进制 | bin(3) → '0b11' |
print(int("42")) # 42
print(float("3.14")) # 3.14
print(str(100)) # '100'
print(bool([])) # False
print(list("hello")) # ['h', 'e', 'l', 'l', 'o']
print(tuple([1, 2, 3])) # (1, 2, 3)
print(set([1, 2, 2, 3])) # {1, 2, 3}
print(chr(65)) # 'A'
print(ord('A')) # 65
print(hex(255)) # '0xff'
print(bin(10)) # '0b1010'
21.3 序列操作
| 函数 | 说明 | 示例 |
|---|
sorted(iterable) | 排序 | sorted([3,1,2]) → [1,2,3] |
reversed(seq) | 反转 | list(reversed([1,2,3])) → [3,2,1] |
enumerate(seq) | 带索引枚举 | list(enumerate(['a','b'])) → [(0,'a'),(1,'b')] |
zip(*iterables) | 打包 | list(zip([1,2],['a','b'])) → [(1,'a'),(2,'b')] |
range(start, stop, step) | 生成范围 | list(range(5)) → [0,1,2,3,4] |
map(func, iterable) | 映射 | list(map(str, [1,2,3])) → ['1','2','3'] |
filter(func, iterable) | 过滤 | list(filter(bool, [0,1,2])) → [1,2] |
reduce(func, iterable) | 累积 | reduce(lambda a,b:a+b, [1,2,3]) → 6 |
any(iterable) | 任一为真 | any([False, True, False]) → True |
all(iterable) | 全部为真 | all([True, True, False]) → False |
# sorted 排序
print(sorted([3, 1, 4, 1, 5, 9])) # [1, 1, 3, 4, 5, 9]
print(sorted([3, 1, 4], reverse=True)) # [4, 3, 1]
print(sorted(["apple", "banana", "cherry"], key=len)) # 按长度排序
# enumerate 枚举
for i, fruit in enumerate(["苹果", "香蕉", "橙子"]):
print(i, fruit)
# zip 打包
names = ["张三", "李四", "王五"]
ages = [18, 19, 20]
for name, age in zip(names, ages):
print(name, age)
# range 范围
for i in range(10):
print(i)
# any / all
print(any([0, "", None, 1])) # True(有一个真值)
print(all([1, "hello", True])) # True(全是真值)
21.4 对象操作
| 函数 | 说明 | 示例 |
|---|
type(obj) | 查看类型 | type(123) → <class 'int'> |
isinstance(obj, class) | 判断类型 | isinstance(1, int) → True |
id(obj) | 内存地址 | id(x) → 内存地址 |
dir(obj) | 查看属性方法 | dir(str) → 方法列表 |
hasattr(obj, name) | 是否有属性 | hasattr(s, 'upper') → True |
getattr(obj, name) | 获取属性 | getattr(s, 'upper') → 方法 |
setattr(obj, name, value) | 设置属性 | setattr(obj, 'x', 10) |
delattr(obj, name) | 删除属性 | delattr(obj, 'x') |
callable(obj) | 是否可调用 | callable(print) → True |
help(obj) | 查看帮助 | help(str) |
# type 和 isinstance
print(type(123)) # <class 'int'>
print(isinstance(123, int)) # True
print(isinstance(123, (int, float))) # True(是其中一种就行)
# dir 查看属性和方法
print(dir("hello")) # 列出字符串的所有方法
# hasattr / getattr / setattr
s = "hello"
print(hasattr(s, "upper")) # True
func = getattr(s, "upper")
print(func()) # HELLO
# help 帮助
help(str.split) # 查看split方法的帮助
21.5 输入输出
| 函数 | 说明 | 示例 |
|---|
print(*objects) | 打印输出 | print("hello") |
input(prompt) | 输入 | name = input("请输入姓名:") |
open(file, mode) | 打开文件 | f = open("a.txt", "r") |
# print
print("Hello", "World", sep="-", end="!\n") # Hello-World!
# input
name = input("请输入你的名字:")
print(f"你好,{name}")
# open
with open("test.txt", "w", encoding="utf-8") as f:
f.write("Hello World")
21.6 其他常用
| 函数 | 说明 | 示例 |
|---|
eval(expr) | 执行表达式 | eval("1 + 2 * 3") → 7 |
exec(code) | 执行代码 | exec("print('hello')") |
compile(source, filename, mode) | 编译代码 | |
globals() | 全局变量字典 | globals() |
locals() | 局部变量字典 | locals() |
vars(obj) | 对象的属性字典 | vars(obj) |
hash(obj) | 哈希值 | hash("hello") |
id(obj) | 内存地址 | id(x) |
repr(obj) | 官方字符串表示 | repr(x) |
format(value, spec) | 格式化 | format(3.14, '.2f') → '3.14' |
iter(obj) | 获取迭代器 | iter([1,2,3]) |
next(iterator) | 下一个值 | next(it) |
slice(start, stop, step) | 切片对象 | slice(1, 5, 2) |
super() | 父类对象 | super().method() |
__import__(name) | 导入模块 | __import__('math') |
# eval 执行表达式
result = eval("2 + 3 * 4")
print(result) # 14
# format 格式化
print(format(3.14159, '.2f')) # 3.14
print(format(100, ',')) # 100
print(format(100, 'b')) # 1100100(二进制)
# hash 哈希
print(hash("hello"))
print(hash(123))
- 不要执行不可信的代码,有安全风险
- 用户输入的内容不要直接传给 eval
21.7 常用函数分类速记
必记(最常用)
# 输出
print()
# 类型
int(), float(), str(), bool(), list(), dict(), set(), tuple()
# 序列
len(), max(), min(), sum(), sorted(), range(), enumerate(), zip()
# 判断
type(), isinstance()
# 输入输出
input(), open()
进阶(常用)
# 高阶函数
map(), filter(), any(), all()
# 对象操作
dir(), help(), getattr(), hasattr()
# 数学
abs(), round(), pow(), divmod()
# 转换
chr(), ord(), hex(), bin(), oct()
了解(偶尔用)
eval(), exec(), compile(), globals(), locals(), vars(),
hash(), id(), repr(), format(), iter(), next(), slice(),
super(), __import__(), callable(), reversed()
🔗 相关章节
📝 我的笔记
在这里记录你常用的函数和使用技巧
# 你的练习代码
✅ 本章检查清单