大小写

"hello".upper()       # 'HELLO'
"HELLO".lower()       # 'hello'
"hello world".title() # 'Hello World'   每词首字母大写
"hELLO".swapcase()    # 'Hello'         大小写互换

去空白

"  hello  ".strip()    # 'hello'    两端
"  hello  ".lstrip()   # 'hello  '  左端
"  hello  ".rstrip()   # '  hello'  右端
"---hi---".strip("-")  # 'hi'       自定义去除字符

分割与合并

"a,b,c".split(",")              # ['a', 'b', 'c']
"hello world".split()            # ['hello', 'world']  默认按空白
"line1\nline2\nline3".splitlines()  # ['line1', 'line2', 'line3']

",".join(["a", "b", "c"])        # 'a,b,c'
" - ".join(["A", "B", "C"])      # 'A - B - C'

splitjoin 是日常处理 CSV、日志、URL 的主力。

替换

"hello world".replace("world", "Python")    # 'hello Python'
"aaa".replace("a", "b", 2)                  # 'bba'  最多替换 2 次

查找

"hello".find("ll")     # 2     找到返回下标
"hello".find("xx")     # -1    找不到返回 -1
"hello".index("ll")    # 2     找不到会抛 ValueError
"hello".count("l")     # 2     出现次数

判断

"hello".startswith("he")     # True
"hello.txt".endswith(".txt") # True
"123".isdigit()              # True
"abc".isalpha()              # True
"hello".islower()            # True

链式调用

"  Hello, World!  ".strip().lower().replace(",", "")
# 'hello world!'

下一篇讲字符串格式化——把变量塞进字符串里的三种姿势。