Python常用函数整理

360影视 动漫周边 2025-04-05 12:21 1

摘要:以下是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 / ord
Unicode字符与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中常用核心函数(精选部分),覆盖日常开发的大部分场景。实际应用中,结合具体需求查阅官方文档可更深入掌握每个函数的用法!

来源:老客数据一点号

相关推荐