Python 字符串处理小结
Python 中字符串相关的常用方法和注意事项。整理这篇主要是为自己后续翻看,例子都用最简的形式。
基本概念
Python 3 的字符串默认是 Unicode(str 类型),与 Python 2 不同。这意味着 "中文" 这种字面量本身就可以处理,不需要前缀。
大小写转换
"Hello".upper() # 'HELLO'
"Hello".lower() # 'hello'
"hello world".title() # 'Hello World'
"Hello".swapcase() # 'hELLO'
去除空白
" hi ".strip() # 'hi'
" hi ".lstrip() # 'hi '
" hi ".rstrip() # ' hi'
"abc".strip("a") # 'bc' 去除指定字符
查找与替换
"hello".find("ll") # 2(找不到返回 -1)
"hello".index("ll") # 2(找不到抛异常)
"hello".count("l") # 2
"hello".replace("l", "L") # 'heLLo'
"hello".startswith("he") # True
"hello".endswith("lo") # True
分割与拼接
"a,b,c".split(",") # ['a', 'b', 'c']
"a b\nc".split() # ['a', 'b', 'c'] 按任意空白分
"line1\nline2".splitlines() # ['line1', 'line2']
",".join(["a", "b", "c"]) # 'a,b,c'
"".join(["a", "b"]) # 'ab'
注意 join 的接收者是分隔符,参数是序列,刚学的时候经常写反。
格式化
三种主流写法:
# 1. f-string(推荐,Python 3.6+)
name, age = "小明", 20
s = f"{name} 今年 {age} 岁"
# 2. str.format
s = "{} 今年 {} 岁".format(name, age)
s = "{n} 今年 {a} 岁".format(n=name, a=age)
# 3. % 老风格(不推荐新代码用)
s = "%s 今年 %d 岁" % (name, age)
f-string 进阶
num = 3.14159
f"{num:.2f}" # '3.14' 保留 2 位
f"{num:10.2f}" # ' 3.14' 右对齐,占 10 列
f"{num:<10.2f}" # '3.14 ' 左对齐
f"{num:^10.2f}" # ' 3.14 ' 居中
n = 1234567
f"{n:,}" # '1,234,567' 千分位
# 调试输出(Python 3.8+):
x = 42
f"{x=}" # 'x=42'
编码与解码
"中文".encode("utf-8") # b'\xe4\xb8\xad\xe6\x96\x87'
b'\xe4\xb8\xad'.decode("utf-8") # '中'
常见陷阱
- 字符串不可变。
s.replace(...)不会修改s,而是返回新串,要赋值给变量才生效。 "" in any_string总是 True,空串属于任意串的子串。- 拼接大量字符串用
"".join(list)比+=快很多。 - 判断空字符串直接
if s:即可,空串、None、0 都会 False。
小结
字符串方法很多,但常用的就十来个。重点掌握 split / join / strip / replace / startswith / endswith / find,和 f-string 的格式化语法,日常 90% 的字符串活就够用了。