Skip to content

字符串常用 API ​

学习目标 ​

  • 用索引、切片和常用方法处理文本。
  • 掌握 f-string、join、split、查找和替换。
  • 知道 Unicode、编码和正则表达式的使用边界。

核心知识点 ​

str 是不可变的 Unicode 字符序列。索引取一个字符,切片产生新字符串;方法不会原地修改字符串。编码是字符串与字节之间的转换,文件和网络边界必须明确编码。

常用用法 ​

索引与切片 ​

python
text = "Python"
result = (text[0], text[-1], text[1:4], text[::-1])
print(result)
# 输出:('P', 'n', 'yth', 'nohtyP')

切片区间是左闭右开,步长为负时可倒序;越界切片不会报错,越界索引会抛出 IndexError。

str.strip() ​

python
text = "  hello\n"
print(text.strip(), text.lstrip(), text.rstrip())
# 输出:hello hello\n   hello

strip(chars) 移除两端字符集合,而不是移除一个完整子串。

str.split() 与 str.splitlines() ​

python
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() ​

python
words = ["Python", "3.11"]
sentence = " ".join(words)
print(sentence)
# 输出:Python 3.11

调用者是分隔符,参数必须是字符串可迭代对象;"".join(...) 适合拼接字符或片段。

str.replace() ​

python
text = "spam spam"
print(text.replace("spam", "ham", 1))
# 输出:ham spam

replace 返回新字符串,第三个参数限制替换次数;复杂模式使用 re.sub。

查找与判断 ​

python
text = "Python 3.11"
print(text.find("3"), text.startswith("Py"), text.isascii())
# 输出:7 True True

find 找不到返回 -1,index 找不到会抛异常;只判断是否存在时用 in 更直观。

f-string 格式化 ​

python
name, score = "Lin", 98.456
print(f"{name} 得分 {score:.1f}")
# 输出:Lin 得分 98.5

表达式放在 {} 中;用户可控格式不要直接拼接进复杂表达式。

编码与解码 ​

python
text = "你好"
data = text.encode("utf-8")
decoded = data.decode("utf-8")
print(data, decoded)
# 输出:b'\xe4\xbd\xa0\xe5\xa5\xbd' 你好

文件和网络接口要明确编码;出现 UnicodeDecodeError 时先确认数据实际编码,不要盲目忽略错误。

不常用但需要知道 ​

str.translate() ​

python
table = str.maketrans({"-": " ", "_": " "})
print("a-b_c".translate(table))
# 输出:a b c

大量一对一字符替换时比多次 replace 更适合。

str.removeprefix() 与 str.removesuffix() ​

python
path = "file:///tmp/demo.txt"
clean = path.removeprefix("file://").removesuffix(".txt")
print(clean)
# 输出:/tmp/demo

它们按完整前缀/后缀处理,避免把 strip 误当成子串删除。

re.fullmatch() ​

python
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 拼接大量片段通常比循环中反复 + 更清晰高效。

课后小问 ​

  1. 为什么 "-".join(["a", "b"]) 中 join 属于连接符? 答案:join 的调用对象就是插入元素之间的分隔符。 解析:结果等于在序列元素之间插入调用者 "-",元素本身必须是字符串。

  2. 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