Python 字符串处理完全指南:常用操作与技巧
·
Python 字符串处理完全指南:常用操作与技巧
字符串是 Python 里最常用的数据类型之一。学字符串处理才发现,Python 自带的字符串方法强大得离谱,大部分场景根本不需要正则表达式。这篇文章把我常用的字符串操作全部分享出来。
字符串基础
# 定义字符串
s1 = "hello"
s2 = 'world'
s3 = """多行
字符串"""
# 转义字符
s4 = "你好\n世界" # 换行
s5 = "路径:C:\\Users\\Name" # 反斜杠
# 原始字符串
s6 = r"C:\Users\Name" # 不转义
常用操作
拼接和重复
# 拼接
s1 = "Hello" + " " + "World"
print(s1) # Hello World
# 重复
s2 = "ha" * 3
print(s2) # hahaha
# join 连接
words = ["Python", "is", "awesome"]
s3 = " ".join(words)
print(s3) # Python is awesome
切片
s = "Hello, World!"
print(s[0]) # H
print(s[-1]) # !
print(s[0:5]) # Hello
print(s[7:12]) # World
print(s[::-1]) # !dlroW ,olleH(反转)
大小写转换
s = "Hello, World!"
print(s.upper()) # HELLO, WORLD!
print(s.lower()) # hello, world!
print(s.capitalize()) # Hello, world!
print(s.title()) # Hello, World!
print(s.swapcase()) # hELLO, wORLD!
查找和替换
s = "Hello, World!"
# 查找
print(s.find("World")) # 7(首次出现的位置,-1表示未找到)
print(s.find("Python")) # -1
print(s.index("World")) # 7(类似find,但未找到会报错)
print(s.count("l")) # 3(出现次数)
# 替换
print(s.replace("World", "Python")) # Hello, Python!
print(s.replace("o", "O", 1)) # HellO, World!(只替换1次)
判断相关
s = "Hello123"
# 判断开头/结尾
print(s.startswith("Hello")) # True
print(s.endswith("123")) # True
# 判断类型
print(s.isdigit()) # False(有字母)
print(s.isalpha()) # False(有数字)
print(s.isalnum()) # True(全是字母或数字)
print(s.isupper()) # False
print(s.islower()) # False
print(s.isspace()) # False
print(s.istitle()) # False
# 判断是否包含
print("Hello" in s) # True
print("Python" in s) # False
去除空白
s = " Hello, World! "
print(s.strip()) # 去除两边空白
print(s.lstrip()) # 去除左边空白
print(s.rstrip()) # 去除右边空白
# 去除指定字符
s2 = "!!!Hello!!!"
print(s2.strip("!")) # Hello
print(s2.strip("!")) # Hello
分割和连接
s = "apple,banana,orange"
# 分割
print(s.split(",")) # ['apple', 'banana', 'orange']
print(s.split(",", 1)) # ['apple', 'banana,orange'](只分割1次)
# 按行分割
text = "第一行\n第二行\n第三行"
print(text.splitlines()) # ['第一行', '第二行', '第三行']
# 连接
words = ["Python", "is", "awesome"]
print(" ".join(words)) # Python is awesome
print("-".join(words)) # Python-is-awesome
格式化
f-string(推荐)
name = "张三"
age = 25
score = 95.5
print(f"姓名: {name}, 年龄: {age}")
print(f"成绩: {score:.1f}") # 保留1位小数
print(f"{age}年后是{2026 + age}年") # 2031年后是2051年
format()
print("{} + {} = {}".format(1, 2, 3)) # 1 + 2 = 3
print("{1} + {0} = {2}".format(1, 2, 3)) # 2 + 1 = 3
print("{name}的成绩是{score:.1f}".format(name="张三", score=95.5))
% 格式化
name = "张三"
score = 95.5
print("%s的成绩是%.1f" % (name, score)) # 张三的成绩是95.5
实战案例
案例1:敏感信息脱敏
def mask_info(text):
"""手机号、身份证脱敏"""
import re
# 手机号脱敏
text = re.sub(r'(\d{3})\d{4}(\d{4})', r'\1****\2', text)
# 身份证脱敏
text = re.sub(r'(\d{6})\d{8}(\d{4})', r'\1********\2', text)
return text
phone = "我的手机号是13812345678"
id_card = "身份证号是110101199001011234"
print(mask_info(phone)) # 我的手机号是138****5678
print(mask_info(id_card)) # 身份证号是110101********1234
案例2:歌词解析
lyrics = """
[00:00.00]作曲 : 某人
[00:01.00]作词 : 某人
[00:02.50]这是一段歌词
[00:05.30]每行有时间戳
"""
for line in lyrics.strip().split('\n'):
if not line.strip():
continue
# 提取时间戳和歌词
import re
match = re.match(r'\[(\d{2}):(\d{2})\.\d{2}\](.+)', line)
if match:
minutes, seconds, lyric = match.groups()
print(f"{minutes}:{seconds} {lyric}")
案例3:日志解析
log = """
2026-04-11 10:30:15 INFO 用户登录成功
2026-04-11 10:30:20 ERROR 数据库连接超时
2026-04-11 10:30:25 WARNING 内存使用率 85%
"""
import re
for line in log.strip().split('\n'):
match = re.match(r'(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) (\w+) (.+)', line)
if match:
time, level, msg = match.groups()
print(f"[{level}] {msg}")
我踩过的坑
坑1:字符串是不可变的
s = "hello"
# s[0] = "H" # 报错!字符串不能这样修改
# 正确做法
s = "H" + s[1:]
print(s) # Hello
坑2:中文字符编码
# Python 3 默认 str 是 Unicode,不需要特别处理
s = "你好,世界"
print(len(s)) # 6(字符数)
print(len(s.encode('utf-8'))) # 18(字节数)
# 文件读写时指定编码
with open('file.txt', 'r', encoding='utf-8') as f:
content = f.read()
坑3:strip() 默认去除所有空白字符
s = " hello \n\t "
print(repr(s.strip())) # 'hello'(换行和tab都被去掉了)
print(repr(s)) # ' hello \n\t '(原字符串不变)
写在最后
字符串方法虽然多,但大部分场景常用的就那么十几个。我的经验是:能用 f-string + split/join/strip/replace 解决的问题,就不要上正则。
有帮助的话点个赞,有问题评论区见!
更多推荐


所有评论(0)