摘要:以下是Python中常用函数整理,涵盖内置函数、标准库及常用操作,按类别分类并附带示例说明:
以下是Python中常用函数整理,涵盖内置函数、标准库及常用操作,按类别分类并附带示例说明:
一、基础内置函数
print输出内容到控制台。
python
print("Hello, World!") # Hello, World!
len返回对象的长度(元素个数)。
python
len([1, 2, 3]) # 3
type返回对象的类型。
python
type(10) #
input从用户输入获取字符串。
python
name = input("Enter your name: ")
range生成整数序列。
python
list(range(3)) # [0, 1, 2]
sorted返回排序后的新列表。
python
sorted([3, 1, 2], reverse=True) # [3, 2, 1]
sum计算可迭代对象的总和。
python
sum([1, 2, 3]) # 6
min / max返回最小/最大值。
python
min(5, 2, 8) # 2
abs返回绝对值。
python
abs(-10) # 10
round四舍五入浮点数。
python
round(3.1415, 2) # 3.14
二、类型转换
int / float / str类型转换。
python
int("123") # 123
str(100) # "100"
list / tuple / set / dict转换为对应容器类型。
python
list("abc") # ['a', 'b', 'c']
bool转换为布尔值。
python
bool(0) # False
bin / hex / oct转换为二进制、十六进制、八进制字符串。
python
bin(10) # '0b1010'
chr / ordUnicode字符与ASCII码转换。
python
chr(65) # 'A'
ord('A') # 65
三、字符串处理
str.split按分隔符分割字符串。
python
"a,b,c".split(",") # ['a', 'b', 'c']
str.join将可迭代对象连接为字符串。
python
"-".join(["2020", "10", "01"]) # "2020-10-01"
str.replace替换子字符串。
python
"hello".replace("l", "x") # "hexxo"
str.strip去除首尾空白字符。
python
" text ".strip # "text"
str.format格式化字符串。
python
"{} + {} = {}".format(1, 2, 3) # "1 + 2 = 3"
str.startswith / endswith检查字符串开头/结尾。
python
"file.txt".endswith(".txt") # True
str.upper / lower转换大小写。
python
"Abc".lower # "abc"
str.find / index查找子字符串位置(find未找到返回-1,index抛出异常)。
python
"python".find("th") # 2
四、列表操作
list.append添加元素到列表末尾。
python
lst = [1]; lst.append(2) # [1, 2]
list.extend合并另一个可迭代对象。
python
lst = [1]; lst.extend([2,3]) # [1, 2, 3]
list.insert在指定位置插入元素。
python
lst = [1,3]; lst.insert(1, 2) # [1, 2, 3]
list.pop移除并返回指定位置的元素。
python
lst = [1,2,3]; lst.pop(1) # 2 → lst变为[1,3]
list.remove删除第一个匹配的元素。
python
lst = [1,2,2]; lst.remove(2) # [1,2]
list.sort原地排序。
python
lst = [3,1,2]; lst.sort # [1,2,3]
list.reverse反转列表。
python
lst = [1,2,3]; lst.reverse # [3,2,1]
五、字典操作
dict.get安全获取键对应的值(避免KeyError)。
python
d = {'a':1}; d.get('b', 0) # 0
dict.keys / values / items获取键、值或键值对。
python
d = {'a':1}; list(d.keys) # ['a']
dict.update合并字典。
python
d = {'a':1}; d.update({'b':2}) # {'a':1, 'b':2}
dict.pop删除键并返回值。
python
d = {'a':1}; d.pop('a') # 1
dict.setdefault若键不存在,设置默认值并返回。
python
d = {}; d.setdefault('a', 100) # 100
六、文件操作
open打开文件。
python
with open("file.txt", "r") as f:
content = f.read
file.read / readline / readlines读取文件内容。
python
f.read # 读取全部内容
f.readline # 读取一行
file.write写入内容到文件。
python
f.write("Hello")
os.remove删除文件。
python
import os; os.remove("file.txt")
os.path.join拼接路径。
python
os.path.join("folder", "file.txt") # "folder/file.txt"
七、数学与随机数
math.sqrt计算平方根。
python
import math; math.sqrt(4) # 2.0
random.randint生成随机整数。
python
import random; random.randint(1, 10)
random.choice从序列中随机选择一个元素。
python
random.choice([1,2,3]) # 可能返回2
math.ceil / floor向上/向下取整。
python
math.ceil(3.1) # 4
八、时间与日期
datetime.datetime.now获取当前时间。
python
from datetime import datetime
now = datetime.now
strftime / strptime格式化时间与解析字符串。
python
now.strftime("%Y-%m-%d") # "2023-10-01"
九、函数式编程
map对可迭代对象应用函数。
python
list(map(str.upper, ["a", "b"])) # ['A', 'B']
filter过滤元素。
python
list(filter(lambda x: x>0, [-1, 0, 1])) # [1]
lambda匿名函数。
python
f = lambda x: x*2; f(3) # 6
zip将多个可迭代对象打包成元组。
python
list(zip([1,2], ["a","b"])) # [(1, 'a'), (2, 'b')]
enumerate为可迭代对象添加索引。
python
list(enumerate(["a", "b"])) # [(0, 'a'), (1, 'b')]
十、系统与模块
os.getcwd获取当前工作目录。
python
import os; os.getcwd
os.listdir列出目录内容。
python
os.listdir(".")
sys.argv获取命令行参数。
python
import sys; print(sys.argv)
import动态导入模块。
python
math = __import__("math")
十一、装饰器与类
@property定义属性访问方法。
python
class MyClass:
@property
def value(self):
return self._value
@classmethod / @staticmethod类方法与静态方法。
python
class MyClass:
@classmethod
def create(cls):
return cls
super调用父类方法。
python
class Child(Parent):
def __init__(self):
super.__init__
十二、异常处理
try...except...finally捕获异常。
python
try:
1/0
except ZeroDivisionError:
print("Error")
raise抛出异常。
python
raise ValueError("Invalid value")
其他常用函数
eval / exec执行字符串代码。
python
eval("2 + 2") # 4
hasattr / getattr / setattr操作对象属性。
python
hasattr(obj, "x") # 检查属性是否存在
isinstance / issubclass检查类型与继承关系。
python
isinstance(10, int) # True
globals / locals获取全局/局部变量字典。
python
globals
callable检查对象是否可调用。
python
callable(print) # True
以上为Python中常用核心函数(精选部分),覆盖日常开发的大部分场景。实际应用中,结合具体需求查阅官方文档可更深入掌握每个函数的用法!
来源:老客数据一点号