Python(二十二) 常用内置方法与函数
本文面向初学者,用通俗语言讲解 Python 最常用的内置方法(变量名.方法名)和内置函数(直接调用)。每个知识点都配有代码示例,建议边写边运行。
一、字符串常用方法
字符串是 不可变 的,所有方法都返回新字符串,不会修改原字符串。
s = " Hello, Python! "
方法
作用
示例
结果
strip()
去掉首尾空白
s.strip()
"Hello, Python!"
lstrip()
去掉左边空白
s.lstrip()
"Hello, Python! "
rstrip()
去掉右边空白
s.rstrip()
" Hello, Python!"
upper()
转大写
"abc".upper()
"ABC"
lower()
转小写
"ABC".lower()
"abc"
title()
每个单词首字母大写
"hello world".title()
"Hello World"
capitalize()
首字母大写,其余小写
"hello WORLD".capitalize()
"Hello world"
startswith()
是否以某子串开头
"abc".startswith("ab")
True
endswith()
是否以某子串结尾
"abc".endswith("bc")
True
find()
查找子串位置,找不到返回 -1
"abcabc".find("b")
1
index()
查找子串位置,找不到报错
"abcabc".index("b")
1
replace()
替换子串
"abcabc".replace("b", "X")
"aXcaXc"
split()
按分隔符拆成列表
"a,b,c".split(",")
['a', 'b', 'c']
join()
用字符串连接可迭代对象
"-".join(['a', 'b', 'c'])
"a-b-c"
count()
统计子串出现次数
"abcabc".count("ab")
2
isdigit()
是否全是数字
"123".isdigit()
True
isalpha()
是否全是字母
"abc".isalpha()
True
len()
字符串长度(内置函数)
len("abc")
3
经典示例:清洗用户输入
text = input("请输入一段话:")
text = text.strip().lower()
print("清洗后:", text)
二、列表常用方法
列表是 可变 的,方法会直接修改原列表。
fruits = ["apple", "banana"]
方法
作用
示例
结果
append(x)
末尾添加一个元素
fruits.append("cherry")
['apple', 'banana', 'cherry']
extend(iterable)
末尾批量添加
fruits.extend(["date", "fig"])
在末尾追加多个
insert(i, x)
在位置 i 插入
fruits.insert(1, "apricot")
在索引 1 处插入
remove(x)
删除第一个值为 x 的元素
fruits.remove("banana")
删除香蕉
pop(i)
删除并返回索引 i 的元素
fruits.pop()
删除并返回最后一个
clear()
清空列表
fruits.clear()
[]
index(x)
查找 x 的索引
fruits.index("apple")
0
count(x)
统计 x 出现次数
fruits.count("apple")
次数
sort()
原地排序
fruits.sort()
升序排列
reverse()
原地反转
fruits.reverse()
反转顺序
copy()
浅拷贝列表
new = fruits.copy()
得到新列表
排序与反转
nums = [3, 1, 4, 1, 5, 9]
nums.sort() # 升序
nums.sort(reverse=True) # 降序
print(nums)
列表与字符串互转
# 字符串 → 列表
chars = list("hello") # ['h', 'e', 'l', 'l', 'o']
words = "a b c".split() # ['a', 'b', 'c']
# 列表 → 字符串
s = "".join(['h', 'e', 'l', 'l', 'o']) # "hello"
s2 = "-".join(['2026', '07', '01']) # "2026-07-01"
三、字典常用方法
字典通过 键:值 存储数据,查询速度极快。
person = {"name": "小明", "age": 18, "city": "北京"}
方法
作用
示例
结果
get(key, default)
安全取值
person.get("age")
18
keys()
返回所有键
person.keys()
dict_keys(['name', 'age', 'city'])
values()
返回所有值
person.values()
dict_values(['小明', 18, '北京'])
items()
返回键值对
person.items()
可遍历的 (key, value)
update(dict2)
合并另一个字典
person.update({"gender": "男"})
添加/覆盖键值
pop(key)
删除并返回某键的值
person.pop("age")
18
popitem()
删除并返回最后一个键值对
person.popitem()
最后一对
setdefault(key, default)
键不存在则设置默认值
person.setdefault("score", 0)
不存在才设置
clear()
清空字典
person.clear()
{}
len()
键值对数量(内置函数)
len(person)
3
遍历字典
for key, value in person.items():
print(f"{key}: {value}")
安全取值
# 直接取值,键不存在会报错
# score = person["score"]
# 安全写法
score = person.get("score", 0)
print(score) # 0
四、集合常用方法
集合(set)是 不重复 、无序 的数据结构,适合去重和集合运算。
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
方法
作用
示例
结果
add(x)
添加元素
a.add(5)
{1, 2, 3, 4, 5}
remove(x)
删除元素,不存在报错
a.remove(1)
删除 1
discard(x)
删除元素,不存在不报错
a.discard(10)
不变
pop()
随机删除并返回一个元素
a.pop()
不确定
clear()
清空集合
a.clear()
set()
union(b) 或 a | b
并集
a.union(b)
{1, 2, 3, 4, 5, 6}
intersection(b) 或 a & b
交集
a.intersection(b)
{3, 4}
difference(b) 或 a - b
差集
a.difference(b)
{1, 2}
symmetric_difference(b) 或 a ^ b
对称差集
a ^ b
{1, 2, 5, 6}
去重示例
nums = [1, 2, 2, 3, 3, 3]
unique_nums = list(set(nums))
print(unique_nums) # [1, 2, 3](顺序不一定保留)
五、类型转换函数
Python 提供了很多内置函数用来转换数据类型。
函数
作用
示例
结果
int(x)
转整数
int("42")
42
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])
{1, 2}
dict(x)
转字典
dict([('a', 1)])
{'a': 1}
type(x)
查看类型
type(123)
<class 'int'>
类型判断
age = 18
if isinstance(age, int):
print("age 是整数")
# 判断是否是多个类型之一
if isinstance(age, (int, float)):
print("age 是数字")
六、输入输出函数
函数
作用
示例
print()
输出到控制台
print("你好")
input()
从键盘读取
name = input("请输入姓名:")
open()
打开文件
f = open("test.txt", "r", encoding="utf-8")
print 的常用技巧
print("a", "b", "c") # 自动用空格分隔:a b c
print("a", "b", sep="-") # 指定分隔符:a-b
print("hello", end="") # 不换行
print(f"我叫{name},今年{age}岁") # 格式化字符串(推荐)
# 格式化数字
pi = 3.14159
print(f"π 约等于 {pi:.2f}") # 保留两位小数
七、数学与数字函数
函数
作用
示例
结果
abs(x)
绝对值
abs(-5)
5
round(x, n)
四舍五入
round(3.14159, 2)
3.14
max(iterable)
最大值
max([1, 5, 3])
5
min(iterable)
最小值
min([1, 5, 3])
1
sum(iterable)
求和
sum([1, 2, 3])
6
pow(x, y)
x 的 y 次方
pow(2, 3)
8
divmod(x, y)
返回商和余数
divmod(10, 3)
(3, 1)
更复杂的数学运算
如需三角函数、对数、阶乘等,需要导入 math 模块:
import math
print(math.sqrt(16)) # 开平方:4.0
print(math.ceil(3.2)) # 向上取整:4
print(math.floor(3.8)) # 向下取整:3
print(math.pi) # 圆周率
八、可迭代对象操作函数
这些是 Python 中非常强大、常用的函数。
函数
作用
示例
结果
len(x)
求长度
len("abc")
3
sorted(x)
排序(返回新列表)
sorted([3, 1, 2])
[1, 2, 3]
reversed(x)
反转(返回迭代器)
list(reversed([1, 2, 3]))
[3, 2, 1]
enumerate(x)
带索引遍历
enumerate(['a','b'])
(0, 'a'), (1, 'b')
zip(x, y)
并行打包
zip([1,2], ['a','b'])
(1,'a'), (2,'b')
map(func, iterable)
批量映射
list(map(str, [1,2]))
['1', '2']
filter(func, iterable)
批量过滤
list(filter(lambda x: x>0, [-1,1,2]))
[1, 2]
range(start, stop, step)
生成整数序列
list(range(5))
[0, 1, 2, 3, 4]
enumerate 示例
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits, start=1):
print(f"{index}. {fruit}")
# 输出:
# 1. apple
# 2. banana
# 3. cherry
zip 示例
names = ["小明", "小红"]
ages = [18, 20]
for name, age in zip(names, ages):
print(f"{name} {age}岁")
# 输出:
# 小明 18岁
# 小红 20岁
列表推导式(推荐替代 map/filter)
# 把数字列表转成字符串列表
nums = [1, 2, 3]
strs = [str(n) for n in nums] # ['1', '2', '3']
# 过滤大于 0 的数
positives = [n for n in nums if n > 0]
九、逻辑判断函数
函数
作用
示例
结果
all(iterable)
所有元素为真返回 True
all([1, 2, 3])
True
any(iterable)
任一元素为真返回 True
any([0, 1, 0])
True
scores = [80, 90, 70]
print(all(s >= 60 for s in scores)) # 是否全部及格:True
print(any(s == 100 for s in scores)) # 是否有人满分:False
十、文件操作
文件操作通常与 open() 函数一起使用。推荐使用 with 语句,它会自动关闭文件。
# 读取整个文件
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
# 逐行读取
with open("data.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip())
# 写入文件
with open("output.txt", "w", encoding="utf-8") as f:
f.write("你好,Python!\n")
f.write("第二行内容\n")
# 追加内容
with open("output.txt", "a", encoding="utf-8") as f:
f.write("追加一行\n")
常用文件模式
模式
含义
"r"
只读(默认)
"w"
写入,会覆盖原文件
"a"
追加
"rb" / "wb"
二进制读写
十一、其他实用内置函数
函数
作用
示例
结果
help(obj)
查看帮助
help(str.upper)
显示文档
dir(obj)
查看对象所有属性和方法
dir("abc")
字符串方法列表
id(obj)
查看对象内存地址
id(123)
一长串数字
repr(obj)
返回对象的官方字符串表示
repr("a\nb")
'a\\nb'
callable(obj)
是否可调用
callable(print)
True
globals()
返回全局变量字典
—
—
locals()
返回局部变量字典
—
—
十二、学习方法建议
先记最常用的 :print()、input()、len()、type()、int()、str()、list()、range()、enumerate()、zip()、sorted()、map()、filter()。
遇到字符串处理就查字符串方法 :strip()、split()、join()、replace()、find()、startswith()。
列表增删改查四件套 :append()、remove()、pop()、insert()、sort()。
字典核心三方法 :get()、keys()/values()/items()、update()。
多写小例子 :比如写一个“统计一段话中每个字出现次数”的程序。
十三、综合小练习
练习 1:统计单词出现次数
text = "apple banana apple cherry banana apple"
words = text.split()
count = {}
for word in words:
count[word] = count.get(word, 0) + 1
print(count)
# {'apple': 3, 'banana': 2, 'cherry': 1}
练习 2:筛选成绩合格的学生
students = [
{"name": "小明", "score": 85},
{"name": "小红", "score": 55},
{"name": "小刚", "score": 72},
]
passed = [s["name"] for s in students if s["score"] >= 60]
print(passed) # ['小明', '小刚']
练习 3:读取文件并统计行数
with open("data.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
print(f"共有 {len(lines)} 行")
记住:Python 的内置函数和方法非常多,不需要一次性全背下来。理解它们的作用,在需要时查文档、多练习,就能慢慢熟练掌握。