以下是 Python 常用字符串处理函数与方法的分类汇总,涵盖基础操作、格式化、查找替换、编码转换等核心场景,附示例说明:
一、基础操作
1. 字符串拼接与分割
+或+=s = "Hello" + " " + "World" # "Hello World"
join(iterable)words = ["Python", "is", "awesome"] s = " ".join(words) # "Python is awesome"
split(sep=None, maxsplit=-1)s = "a,b,c".split(",") # ["a", "b", "c"]
splitlines([keepends=False])lines = "Line1\nLine2\r\nLine3".splitlines() # ["Line1", "Line2", "Line3"]
2. 大小写转换
upper()/lower()"Hello".upper() # "HELLO" "World".lower() # "world"
title()/capitalize()"hello world".title() # "Hello World" "hello world".capitalize() # "Hello world"
swapcase()"HeLLo".swapcase() # "hEllO"
二、查找与替换
1. 子串查找
find(sub[, start[, end]])/index(sub[, start[, end]])s = "Python" s.find("th") # 2(返回索引,未找到返回-1) s.index("th") # 2(未找到抛出 ValueError)
count(sub[, start[, end]])"ababa".count("aba") # 1(非重叠计数)
2. 替换操作
replace(old, new[, count])"Hello World".replace("World", "Python") # "Hello Python"
expandtabs(tabsize=8)"a\tb".expandtabs(4) # "a b"
三、格式化与对齐
1. 格式化字符串
format(*args, **kwargs)"{} + {} = {}".format(2, 3, 5) # "2 + 3 = 5"
- f-string(Python 3.6+)
name = "Alice" f"Hello, {name}!" # "Hello, Alice!"
2. 对齐与填充
ljust(width[, fillchar])/rjust(width[, fillchar])"42".rjust(5, "0") # "00042"
center(width[, fillchar])"Hi".center(10, "-") # "----Hi----"
zfill(width)"7".zfill(3) # "007"
四、修剪与检查
1. 去除空白字符
strip([chars])/lstrip([chars])/rstrip([chars])" Hello ".strip() # "Hello" "##Python##".strip("#") # "Python"
2. 字符串检查
startswith(prefix[, start[, end]])/endswith(suffix[, start[, end]])"file.txt".endswith(".txt") # True
isalnum()/isalpha()/isdigit()/isspace()"123abc".isalnum() # True(字母或数字) " ".isspace() # True
五、编码与解码
1. 编码转换
encode(encoding='utf-8', errors='strict')"中文".encode("utf-8") # b'\xe4\xb8\xad\xe6\x96\x87'
bytes.decode(encoding='utf-8', errors='strict')b'\xe4\xb8\xad\xe6\x96\x87'.decode("utf-8") # "中文"
六、正则表达式(需 re 模块)
常用方法:
re.findall(pattern, string)import re re.findall(r'\d+', "a1b22c") # ['1', '22']
re.sub(pattern, repl, string)re.sub(r'\s+', '-', "Hello World") # "Hello-World"
注意事项
- 字符串不可变性:所有字符串方法均返回新字符串,原字符串不变。
- 索引规则:Python 字符串索引从
0开始,支持负数索引(如s[-1]表示最后一个字符)。 - 切片操作:
s[start:end:step](如s[::-1]反转字符串)。
总结
Python 的字符串处理功能强大且灵活,结合内置方法和正则表达式可应对多数文本处理需求。建议在实际编码中根据场景选择最简洁高效的方法!
