Python 字符串方法(String Methods)完整指南
(2025–2026 实用版 · 包含最常用 + 容易忘记但很有用的方法)
Python 的字符串是不可变(immutable)的,所有字符串方法都会返回新字符串,原字符串不变。
一、最常用的 15 个字符串方法(日常开发出现频率 Top 级)
| 方法 | 功能简述 | 常见用法示例 | 返回值类型 | 修改原串? |
|---|---|---|---|---|
strip() / lstrip() / rstrip() | 去除两端/左侧/右侧空白字符 | s.strip()、s.strip(" ,.!") | str | 否 |
replace(old, new) | 替换所有匹配的子串 | s.replace("旧", "新", 1)(可选第3参数限次数) | str | 否 |
split() / rsplit() | 以指定分隔符拆分(默认空白) | line.split(",")、data.rsplit(".", 1) | list[str] | 否 |
join(iterable) | 用当前字符串连接可迭代对象中的字符串 | ",".join(["a","b","c"]) → "a,b,c" | str | 否 |
startswith() / endswith() | 判断开头/结尾是否匹配 | filename.endswith((".jpg", ".png")) | bool | 否 |
find() / rfind() | 查找子串首次/最后出现的位置(没找到返回-1) | text.find("python") | int | 否 |
index() / rindex() | 类似 find,但找不到会抛 ValueError | text.index("关键词")(更严格) | int | 否 |
count(sub) | 统计子串出现次数 | text.count("python") | int | 否 |
lower() / upper() / title() / capitalize() | 大小写转换 | name.title() → “Zhang San” | str | 否 |
isalpha() / isdigit() / isalnum() / isspace() | 判断字符类型 | s.isdigit() 判断是否纯数字 | bool | 否 |
二、2025–2026 越来越常用的进阶 / 实用方法
| 方法 | 功能简述 | 示例代码 | 适用场景 |
|---|---|---|---|
removeprefix() / removesuffix() (3.9+) | 移除前缀/后缀(如果存在) | version.removeprefix("v") | 处理版本号、文件名前缀 |
casefold() | 更激进的小写转换(德语 ß → ss 等) | "Straße".casefold() → "strasse" | 国际化、不区分大小写的比较 |
center(width, fillchar) | 居中对齐并填充 | "标题".center(20, "-") → "-------标题-------" | 控制台美化、日志格式 |
zfill(width) | 左侧补零到指定宽度 | "42".zfill(5) → "00042" | 编号、日期格式、批次号 |
partition(sep) / rpartition() | 从左/右第一个分隔符分成三部分 | "a=b=c".partition("=") → ('a', '=', 'b=c') | 解析 key=value、路径拆分 |
expandtabs(tabsize) | 把 \t 展开为空格 | "a\tb".expandtabs(8) | 处理制表符对齐的文本 |
maketrans() + translate() | 批量字符映射替换(比多个 replace 快) | 见下面完整示例 | 清洗特殊字符、简繁转换 |
三、maketrans + translate 的经典用法(非常实用)
# 去除所有标点符号 + 数字
import string
# 方法1:最常用方式
table = str.maketrans("", "", string.punctuation + string.digits)
clean_text = dirty_text.translate(table)
# 方法2:自定义映射(例如全角转半角)
full_to_half = str.maketrans("ABC0123", "ABC0123")
text = "Hello 123".translate(full_to_half) # → "Hello 123"
四、字符串格式化方法对比(2025–2026 推荐顺序)
| 方式 | 语法示例 | 推荐场景 | Python 版本支持 |
|---|---|---|---|
| f-string | f"Hi {name}, age {age:03d}" | 日常首选 | 3.6+ |
| str.format() | "Hi {}, age {:03d}".format(name, age) | 需要动态键、兼容旧代码 | 2.6+ |
| % 运算符 | "Hi %s, age %03d" % (name, age) | 极老代码、日志格式模板 | 所有版本 |
| str.join + 列表 | " ".join([str(x) for x in items]) | 拼接大量小字符串 | 所有版本 |
2025–2026 推荐优先级:
f-string > str.format() > join > %
五、字符串方法速查口诀(背下来很有用)
- 去空 → strip / lstrip / rstrip
- 换内容 → replace / translate
- 拆分 → split / partition / rsplit
- 拼接 → join
- 找位置 → find / index / startswith / endswith
- 大小写 → lower / upper / title / capitalize / casefold
- 判断 → isalpha / isdigit / isalnum / isspace / istitle
- 补齐 → zfill / center / ljust / rjust
- 去前后缀 → removeprefix / removesuffix (3.9+)
六、一个小而全的实战例子
text = " Hello, 世界! Python3.12 is GREAT! v1.2.3 "
# 链式处理示范
result = (
text.strip() # 去两端空白
.removeprefix("Hello, ") # 去前缀
.replace("世界", "World") # 替换中文
.lower() # 转小写
.removesuffix(" is great!") # 去后缀(注意大小写)
.rstrip("!") # 去右边感叹号
.split() # 拆成单词列表
)
print(result)
# ['python3.12', 'is', 'great!', 'v1.2.3']
你现在最想深入了解哪一类字符串操作?
- 清洗脏数据的完整套路(标点、空格、全半角等)
- 字符串格式化所有细节(f-string 高级用法)
- 正则 vs 字符串方法的选择场景
- 处理中文 / 多语言时的坑与技巧
- 性能敏感场景下的最快写法
告诉我,我可以继续展开~