Python 字符串方法全景图
从大小写到编码,一篇文章搞定 str 全部常用方法
"hello".upper() → "HELLO"
Python 中处理文本主要用 str 类型。实例方法通过 "文本".方法名(...) 调用;另有少量与字符串强相关的内置函数(如 len、ord)。字符串不可变:方法大多返回新字符串,不原地修改。
| |
|---|
capitalize() | |
casefold() | |
lower() | |
upper() | |
swapcase() | |
title() | |
| |
|---|
isalnum() | |
isalpha() | |
isdecimal() | |
isdigit() | |
isnumeric() | |
islower() / isupper() | |
isspace() | |
isidentifier() | |
isprintable() | |
istitle() | |
| |
|---|
find(sub[, start[, end]]) | |
index(sub[, start[, end]]) | |
rfind / rindex | |
count(sub[, start[, end]]) | |
startswith / endswith | |
| |
|---|
split(sep=None, maxsplit=-1) | |
rsplit | |
splitlines(keepends=False) | |
partition(sep) | |
rpartition(sep) | |
join() 在分隔字符串上调用,把可迭代对象里的字符串接起来:
# 用逗号拼接列表中的字符串",".join(["a", "b", "c"])# 结果: 'a,b,c'
| |
|---|
replace(old, new[, count]) | |
strip([chars]) | |
lstrip / rstrip | |
ljust / rjust / center | |
zfill(width) | |
expandtabs(tabsize=8) | |
| |
|---|
format(*args, **kwargs) | |
format_map(mapping) | 类似 format,参数为映射对象(如 dict) |
| |
|---|
encode(encoding='utf-8') | |
str.maketrans(...) | |
translate(table) | |
| |
|---|
len(s) | |
ord(c) | |
chr(n) | |
str(x) | |
repr(x) | |
ascii(x) | |
enumerate(iterable) | |
map(func, iterable) | |
bool、int、float、hash、id、type 等适用于任意对象,不单针对字符串,需要时再查文档即可。
📌 小结
● 绝大多数「字符串操作」在 str 实例方法上;注意 join 写在分隔符上。
● 需要某一方法的参数细节、边界情况,请查官方 str 页面。
📖 参考文档
› 文本序列类型 str — Python 官方文档
› 内置函数 — Python 官方文档
Python 基础系列 · 持续更新中
str.methods() ✦ Done