字符串常用 API
学习目标
- 用索引、切片和常用方法处理文本。
- 掌握 f-string、
join、split、查找和替换。 - 知道 Unicode、编码和正则表达式的使用边界。
核心知识点
str 是不可变的 Unicode 字符序列。索引取一个字符,切片产生新字符串;方法不会原地修改字符串。编码是字符串与字节之间的转换,文件和网络边界必须明确编码。
常用用法
索引与切片
text = "Python"
result = (text[0], text[-1], text[1:4], text[::-1])
print(result)
# 输出:('P', 'n', 'yth', 'nohtyP')切片区间是左闭右开,步长为负时可倒序;越界切片不会报错,越界索引会抛出 IndexError。
str.strip()
text = " hello\n"
print(text.strip(), text.lstrip(), text.rstrip())
# 输出:hello hello\n hellostrip(chars) 移除两端字符集合,而不是移除一个完整子串。
str.split() 与 str.splitlines()
line = "red,green,blue"
parts = line.split(",")
lines = "a\nb\n".splitlines()
print(parts, lines)
# 输出:['red', 'green', 'blue'] ['a', 'b']不传分隔符时会按连续空白切分并丢弃首尾空白;读取文本行时 splitlines() 通常比手写 split("\n") 稳妥。
str.join()
words = ["Python", "3.11"]
sentence = " ".join(words)
print(sentence)
# 输出:Python 3.11调用者是分隔符,参数必须是字符串可迭代对象;"".join(...) 适合拼接字符或片段。
str.replace()
text = "spam spam"
print(text.replace("spam", "ham", 1))
# 输出:ham spamreplace 返回新字符串,第三个参数限制替换次数;复杂模式使用 re.sub。
查找与判断
text = "Python 3.11"
print(text.find("3"), text.startswith("Py"), text.isascii())
# 输出:7 True Truefind 找不到返回 -1,index 找不到会抛异常;只判断是否存在时用 in 更直观。
f-string 格式化
name, score = "Lin", 98.456
print(f"{name} 得分 {score:.1f}")
# 输出:Lin 得分 98.5表达式放在 {} 中;用户可控格式不要直接拼接进复杂表达式。
编码与解码
text = "你好"
data = text.encode("utf-8")
decoded = data.decode("utf-8")
print(data, decoded)
# 输出:b'\xe4\xbd\xa0\xe5\xa5\xbd' 你好文件和网络接口要明确编码;出现 UnicodeDecodeError 时先确认数据实际编码,不要盲目忽略错误。
不常用但需要知道
str.translate()
table = str.maketrans({"-": " ", "_": " "})
print("a-b_c".translate(table))
# 输出:a b c大量一对一字符替换时比多次 replace 更适合。
str.removeprefix() 与 str.removesuffix()
path = "file:///tmp/demo.txt"
clean = path.removeprefix("file://").removesuffix(".txt")
print(clean)
# 输出:/tmp/demo它们按完整前缀/后缀处理,避免把 strip 误当成子串删除。
re.fullmatch()
import re
matched = re.fullmatch(r"[A-Z]{2}\d{3}", "AB123") is not None
print(matched)
# 输出:True正则适合模式匹配;简单的前缀、包含和替换不要过度使用正则。
易混点
- 字符串不可变,
text.replace(...)不会改变text本身。 strip("ab")移除两端连续的 a/b,不是移除字符串"ab"。split(" ")与split()对连续空格的处理不同。encode得到bytes,decode才回到str。- 用
join拼接大量片段通常比循环中反复+更清晰高效。
课后小问
为什么
"-".join(["a", "b"])中join属于连接符? 答案:join的调用对象就是插入元素之间的分隔符。 解析:结果等于在序列元素之间插入调用者"-",元素本身必须是字符串。find和index找不到文本时分别怎样? 答案:find返回 -1,index抛出ValueError。 解析:需要分支判断时find方便;希望异常暴露数据错误时可用index。
本节小结
日常文本处理优先组合切片、strip、split、join、replace 和 f-string;到编码边界时再明确 str 与 bytes。
快速回顾
- 文本是不可变 Unicode:
str - 切分/连接:
split、join - 清理/替换:
strip、replace - 查找/判断:
find、in、startswith - 边界转换:
encode、decode
阿源的知识库