字符串与正则表达式 字符串不可变 字符串是 immutable,任何”修改”都会创建新对象:
1 2 3 s = "hello" s.upper() s = s.upper()
常用操作 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 text = " Hello, World! " text.strip() text.lstrip() text.rstrip() text.lower() text.upper() text.title() text.replace("World" , "Python" ) text.startswith("Hello" ) text.endswith("!" ) "World" in texttext.find("World" ) text.index("World" ) text.count("l" ) "a,b,c" .split("," )"\n" .join(["line1" , "line2" ])
格式化 1 2 3 4 5 6 7 8 9 10 11 name, score = "Alice" , 95 f"{name} scored {score:.1 f} " "{} scored {:.1f}" .format (name, score)f"{name:>10 } " f"{score:05d} "
编码与解码 1 2 3 4 5 s = "中文" b = s.encode("utf-8" ) s2 = b.decode("utf-8" )
bytes 与 bytearray 1 2 3 data = b"hello" data = bytes ([72 , 101 , 108 , 108 , 111 ]) ba = bytearray (b"hello" )
正则表达式 re 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import repattern = r"\d{3}-\d{4}" text = "Call 010-1234 or 020-5678" re.search(pattern, text) re.findall(pattern, text) re.sub(r"\d+" , "X" , "a1b22c" ) pat = re.compile (r"(\w+)@(\w+\.\w+)" ) m = pat.search("email: user@example.com" ) if m: m.group(0 ) m.group(1 ) m.group(2 )
常用元字符
模式
含义
.
任意字符(除换行)
\d
数字
\w
字母数字下划线
\s
空白
*
0 次或多次
+
1 次或多次
?
0 次或 1 次
{n,m}
n 到 m 次
^
行首
$
行尾
[]
字符集
()
分组
原始字符串 正则模式前加 r,避免 \ 被转义:
1 re.match(r"\d+" , "123abc" )
小结
字符串不可变,频繁拼接用 "".join() 或 io.StringIO
f-string 是首选格式化方式
文本处理复杂时用 re,简单场景用字符串方法即可