Appearance
06|字符串方法
Python 字符串自带大量方法,覆盖了查找、替换、切分、格式化等常见操作。这些方法都不会修改原字符串(字符串不可变),而是返回新字符串或新列表。
一、大小写转换
python
"hello".upper() # 'HELLO'
"HELLO".lower() # 'hello'
"hello world".title() # 'Hello World',每个单词首字母大写
"hello world".capitalize() # 'Hello world',仅首字母大写
"Hello".swapcase() # 'hELLO'大小写转换在比较时很有用。需要忽略大小写判断相等时,先把两边都转成同一种大小写:
python
answer = input("是否继续(y/n): ")
if answer.lower() == "y":
print("继续执行")二、查找与判断
python
"hello world".find("world") # 6,返回子串首次出现的索引,找不到返回 -1
"hello world".find("xyz") # -1
"hello world".index("world") # 6,找不到时抛出 ValueError
"hello world".startswith("hello") # True
"hello world".endswith("world") # True
"hello world".endswith((".txt", ".md")) # False,支持多个后缀元组
"123".isdigit() # True
"abc".isalpha() # True
"abc123".isalnum() # True
" ".isspace() # Truefind() 和 index() 的区别:find() 找不到返回 -1,index() 找不到抛异常。不确定子串是否存在时,用 find() 更安全。
从右侧开始查找:
python
"/path/to/file.txt".rfind("/") # 8,最后一个斜杠的位置
"/path/to/file.txt".rsplit("/", 1) # ['/path/to', 'file.txt']三、替换
python
"hello world".replace("world", "Python") # 'hello Python'
"aaa".replace("a", "b", 2) # 'bba',只替换前 2 次replace() 返回新字符串,原字符串不变。
四、切分与连接
split() 按分隔符切分成列表:
python
"a,b,c".split(",") # ['a', 'b', 'c']
"a, b, c".split(", ") # ['a', 'b', 'c']
" a b c ".split() # ['a', 'b', 'c'],默认按任意空白切分
"a,b,c".split(",", 1) # ['a', 'b,c'],只切分一次rsplit() 从右侧切分:
python
"/path/to/file.txt".rsplit("/", 1) # ['/path/to', 'file.txt']join() 用分隔符连接序列:
python
",".join(["a", "b", "c"]) # 'a,b,c'
"".join(["h", "e", "l", "l", "o"]) # 'hello'
"-".join("abc") # 'a-b-c',字符串也是序列split() 和 join() 是一对常用组合。把字符串切分处理后再拼接,是最常见的文本处理模式之一。
五、去除空白
python
" hello ".strip() # 'hello',去除两端空白
" hello ".lstrip() # 'hello ',去除左端
" hello ".rstrip() # ' hello',去除右端
"...hello...".strip(".") # 'hello',去除指定字符空白包括空格、制表符 \t、换行符 \n 等。读取文件或接收用户输入后,通常先用 strip() 清理首尾空白。
六、格式化字符串
三种格式化方式:
1. % 格式化(旧式)
python
name = "Alice"
age = 25
"Name: %s, Age: %d" % (name, age) # 'Name: Alice, Age: 25'
"%.2f" % 3.14159 # '3.14'2. str.format()(推荐用于复杂格式)
python
"Name: {}, Age: {}".format(name, age) # 按位置
"Name: {0}, Age: {1}".format(name, age) # 按索引
"Name: {n}, Age: {a}".format(n=name, a=age) # 按关键字
"{:.2f}".format(3.14159) # '3.14'
"{:>10}".format("hi") # ' hi',右对齐,宽度 10
"{:0>4d}".format(42) # '0042',补零,宽度 43. f-string(Python 3.6+,最常用)
python
f"Name: {name}, Age: {age}"
f"Pi = {pi:.2f}" # 'Pi = 3.14'
f"{num:>10}" # 右对齐,宽度 10
f"{num:0>4d}" # 补零,宽度 4
f"{big_num:,}" # '1,000,000',千位分隔符f-string 支持在花括号里写表达式:
python
a, b = 10, 20
f"sum = {a + b}" # 'sum = 30'
f"upper = {name.upper()}" # 'upper = ALICE'三种方式都能用,但 f-string 最简洁、性能最好。维护旧代码时会遇到 % 和 format(),新代码优先用 f-string。
记忆锚点:字符串不可变,方法都返回新值;find() 找不到返回 -1,index() 找不到抛异常;split() 和 join() 是常见组合;strip() 去除两端空白;f-string 最简洁,{变量:.2f} 控制格式。