Python
基础语法
01概念
02安装
03变量
04字符串
05数
06常量与注释
07列表
08元组
09if语句
10字典
11集合
12复合数据类型对比
13推导式
14用户输入
15while循环
16函数
17类
18面向对象编程
19文件操作
20异常处理
21日期和时间
22魔术方法
23内置函数
24线程
25并发&并行
26正则表达式
27迭代器
28装饰器
29生成器
30上下文管理器
31函数式编程
32闭包
33解包
34工具库
35连接关系型数据库
36虚拟环境
37异步编程
网络爬虫
01urllib库[了解]
02requests库
03数据交换格式
04解析库
05lxml
06Beautiful Soup
07Xpath语法
08动态网页的处理
-
+
首页
23内置函数
Python 的内置函数(Built-in Functions)是解释器自带的函数,无需导入任何模块即可直接使用,涵盖了数据处理、类型转换、输入输出等多种基础功能。掌握常用内置函数能极大提高编程效率。以下按功能分类详解最常用的内置函数: ## 基础输入输出函数 **1. print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)** **功能**:将对象输出到控制台(或指定文件)。 **参数**: - *objects:要输出的一个或多个对象(可多个,用逗号分隔)。 - sep:多个对象之间的分隔符,默认是空格。 - end:输出结束时的字符,默认是换行符 \n。 - file:输出目标(默认是控制台,可指定文件对象)。 ```python print("Hello", "Python", sep="--", end="!") #Hello--Python! ``` **2. input([prompt])** **功能**:从控制台获取用户输入,返回值是字符串(需手动转换类型)。 **参数**:prompt 是输入前显示的提示文字(可选)。 ```python name = input("请输入姓名:") # 用户输入"Alice",name 为 "Alice" age = int(input("请输入年龄:")) # 转换为整数 ``` ## 数据类型与转换函数 **1.类型判断** - type(object):返回对象的类型 ```python print(type(123)) # <class 'int'> print(type("abc")) # <class 'str'> ``` - isinstance(object, classinfo):判断对象是否是指定类型(或其子类)的实例,返回布尔值(比 type 更推荐,支持继承判断)。 ```python print(isinstance(123, int)) # True print(isinstance("123", (int, str))) # True(判断是否是int或str) ``` **2. 类型转换** - int(x, base=10):将对象转换为整数(base 指定进制,默认 10 进制)。 ```python print(int("123")) # 123 print(int("1010", base=2)) # 10(二进制转十进制) ``` - float(x):转换为浮点数。 ```python print(float("3.14")) # 3.14 print(float(123)) # 123.0 ``` - str(object):转换为字符串。 ```python print(str(123)) # "123" print(str([1,2,3])) # "[1, 2, 3]" ``` - list(iterable):转换为列表(iterable 是可迭代对象,如元组、字符串等)。 ```python print(list((1,2,3))) # [1, 2, 3] print(list("abc")) # ['a', 'b', 'c'] ``` - tuple(iterable):转换为元组。 ```python print(tuple([1,2,3])) # (1, 2, 3) ``` - dict(** kwargs) 或 dict(iterable):创建字典。 ```python print(dict(name="Alice", age=18)) # {'name': 'Alice', 'age': 18} print(dict([("name", "Bob"), ("age", 20)])) # {'name': 'Bob', 'age': 20} ``` - bool(x):转换为布尔值(0、None、空容器等转换为 False,其他为 True)。 ```python print(bool(0)) # False print(bool("")) # False print(bool([1])) # True ``` ## 序列 / 容器操作函数 **1. 长度与计数** - len(s):返回容器(字符串、列表、元组等)的元素个数。 ```python print(len("abc")) # 3 print(len([1,2,3,4])) # 4 ``` - count(sub[, start[, end]])(字符串 / 列表等方法):但内置函数中无直接计数,需结合容器方法。 ```python >>> [1,2,2,3].count(2) 2 >>> [1,2,2,3].count(1) 1 >>> [1,2,2,3].count(3) 1 ``` **2. 最值与求和** - max(iterable, *[, key, default]):返回可迭代对象中的最大值(key 是自定义比较函数)。 ```python print(max([3,1,4,2])) # 4 print(max(["apple", "banana", "cherry"], key=len)) # "banana"(按长度取最长) ``` - min(iterable, *[, key, default]):返回最小值(用法同 max)。 ```python >>> print(min([3,1,4,2])) 1 >>> print(min(["apple", "banana", "cherry"], key=len)) apple ``` - sum(iterable, start=0):对可迭代对象的元素求和(start 是初始值,默认 0)。 ```python print(sum([1,2,3])) # 6 print(sum([1,2,3], start=10)) # 16(10+1+2+3) ``` **3. 切片与排序** - slice(start, stop[, step]):创建切片对象(用于截取序列)。 ```python >>> s = slice(1, 4) # 等价于 [1:4] >>> print([0,1,2,3,4][s]) [1, 2, 3] ``` - sorted(iterable, *[, key, reverse]):对可迭代对象排序,返回新列表(不修改原对象)。 ```python print(sorted([3,1,4,2])) # [1, 2, 3, 4] print(sorted(["c", "a", "b"], reverse=True)) # ['c', 'b', 'a'](倒序) ``` **4. 迭代相关** - enumerate(iterable, start=0):将可迭代对象转换为枚举对象(包含索引和值),常用于循环。 ```python for i, v in enumerate(["a", "b", "c"]): print(i, v) # 0 a;1 b;2 c ``` 输出结果: ```python 0 a 1 b 2 c ``` - zip(*iterables):将多个可迭代对象的元素按位置打包成元组,返回迭代器。 ```python names = ["Alice", "Bob"] ages = [18, 20] for name, age in zip(names, ages): print(name, age) # Alice 18;Bob 20 ``` 输出结果: ```python Alice 18 Bob 20 ``` - map(function, *iterables):对可迭代对象的每个元素应用函数,返回迭代器。 ```python # 计算列表中每个元素的平方 result = map(lambda x: x**2, [1,2,3]) print(list(result)) # [1, 4, 9] ``` - ilter(function, iterable):筛选可迭代对象中使函数返回 True 的元素,返回迭代器。 ```python # 筛选偶数 result = filter(lambda x: x%2 == 0, [1,2,3,4]) print(list(result)) # [2, 4] ``` ## 数学运算函数 - abs(x):返回绝对值。 ```python print(abs(-5)) # 5 print(abs(3.14)) # 3.14 ``` - round(number, ndigits=None):四舍五入(ndigits 是保留的小数位数,默认取整)。 ```python print(round(3.1415)) # 3 print(round(3.1415, 2)) # 3.14 ``` - pow(base, exp, mod=None):计算幂运算(base**exp,可选对 mod 取余)。 ```python print(pow(2, 3)) # 8(2^3) print(pow(2, 3, 5)) # 3(8 % 5) ``` ## 对象操作函数 - id(object):返回对象的唯一标识符(内存地址的整数表示)。 ```python a = 10 b = a print(id(a) == id(b)) # True(a和b指向同一对象) ``` - hash(object):返回对象的哈希值(可哈希对象如整数、字符串等,用于字典的键)。 ```python print(hash("abc")) # 一个整数(不同环境可能不同) #返回结果为:3235652744882373962 ``` - help([object]):查看对象的帮助文档(交互式环境中常用)。 ```python help(str) # 查看字符串类型的帮助文档 ``` 输出结果: ```python >>> help(str) Help on class str in module builtins: class str(object) | str(object='') -> str | str(bytes_or_buffer[, encoding[, errors]]) -> str | | Create a new string object from the given object. If encoding or | errors is specified, then the object must expose a data buffer | that will be decoded using the given encoding and error handler. | Otherwise, returns the result of object.__str__() (if defined) | or repr(object). | encoding defaults to 'utf-8'. | errors defaults to 'strict'. | | Methods defined here: | | __add__(self, value, /) | Return self+value. | | __contains__(self, key, /) | Return bool(key in self). | | __eq__(self, value, /) | Return self==value. | | __format__(self, format_spec, /) | Return a formatted version of the string as described by format_spec. | | __ge__(self, value, /) -- More -- ``` - dir([object]):返回对象的所有属性和方法列表(无参数时返回当前作用域的变量)。 ```python print(dir(str)) # 输出字符串的所有方法,如 'upper', 'lower' 等 ``` 输出结果: ```python >>> print(dir(str)) ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] >>> >>> print(dir()) ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 's'] >>> ``` ## 其他常用函数 - range(stop) 或 range(start, stop[, step]):生成整数序列(返回迭代器),常用于循环。 ```python print(list(range(5))) # [0, 1, 2, 3, 4] print(list(range(2, 10, 2))) # [2, 4, 6, 8] ``` - open(file, mode='r', encoding=None):打开文件,返回文件对象(推荐用 with 语句管理)。 ```python with open("test.txt", "w", encoding="utf-8") as f: f.write("Hello World") ``` - eval(expression, globals=None, locals=None):执行字符串中的 Python 表达式,并返回结果(慎用,有安全风险)。 ```python print(eval("1 + 2 * 3")) # 7 print(eval("'abc' + 'def'")) # "abcdef" ``` ## 总结 Python 内置函数有近百个,以上是最常用的部分。可以通过 dir(__builtins__) 查看所有内置函数,或用 help(函数名) 查看详细用法。 内置函数是 Python 简洁高效的核心原因之一,熟练掌握能显著提升编码速度。
毛林
2025年9月7日 11:45
转发文档
收藏文档
上一篇
下一篇
手机扫码
复制链接
手机扫一扫转发分享
复制链接
Markdown文件
PDF文档(打印)
分享
链接
类型
密码
更新密码