适用场景:数据处理 | 爬虫清洗 | 日志分析 | 面试巩固
一、字符串的常用方法
一、split():字符串分割的艺术
功能:将字符串按指定分隔符切割为列表。
核心参数:
-
sep
:分隔符(默认按空白符分割,如空格、换行符) -
maxsplit
:最大分割次数(默认全部分割)
使用场景:
1.基础分割:
text = "apple,banana,orange"
fruits = text.split(',') # 以,作为分割依据
print(fruits)
# ['apple', 'banana', 'orange']
2.限制分割次数:
data = "2024-07-15-09-30"
date_parts = data.split('-', 2) # 以-作为分割依据,分割两次
print(date_parts)
# ['2024', '07', '15-09-30']
3.处理连续分隔符:
text = "a,,b,c"
parts = [s for s in text.split(',') if s] # 过滤空字符串
# text.split(',')的结果为:['a', '', 'b', 'c']
# 因为第一次分割:a ,b,c
# 第二次分割:a '' b,c -- 第二个,前为空,分割出了一个空字符串
# 故而用 if s 来判断s是否为空,为空的话便去掉空字符串
print(parts) # ['a', 'b', 'c']
"""相当于"""
parts = []
for s in text.split(','):
if s: # 如果 s 不是空字符串(即有内容)
parts.append(s)
print(parts)
4.避坑指南:
-
若分隔符不存在,返回包含原字符串的列表
-
空字符串调用
split()
会返回空列表# 分隔符不存在 s = '#hello world!!!' parts = s.split('?') # 字符串之中没有?,分割符不存在 print(parts) # 输出['#hello world!!!'] # 空字符串调用split() str = '' part = str.split() # 空字符串调用 print(part) # 输出[]
二、join():字符串的高效拼接
功能:用指定字符串连接可迭代对象中的元素。
核心规则:
-
必须作用于字符串类型的可迭代对象(列表/元组)
-
拼接效率远高于循环使用
+=
使用场景:
1.基础拼接:
words = ["Python", "优快云", "开发者"]
sentence = " ".join(words) # 字符串之间以空格的形式结合
# 即 "Python" + " " + "优快云" + " " + "开发者"
print(sentence) # Python 优快云 开发者
2.路径拼接:
path_parts = ["home", "user", "docs"]
full_path = "/".join(path_parts) # 字符串之间以/的形式结合
# 即 "home" + "/" + "user" + "/" + "docs"
print(full_path) # home/user/docs
3.处理非字符串元素:
numbers = [1, 2, 3]
# 需先转换为字符串
result = "-".join(map(str, numbers))
print(result) # 1-2-3
4.性能对比:
# 低效方式(时间复杂度O(n²))
s = ""
for i in range(10000):
s += str(i)
# 高效方式(时间复杂度O(n))
s = "".join(str(i) for i in range(10000))
三、strip():字符串修剪专家
功能:去除字符串首尾指定字符(默认去除空白符)。
扩展方法:
-
lstrip()
:仅处理左侧 -
rstrip()
:仅处理右侧
使用场景:
1.基础清理:
text = " Hello 优快云 "
clean_text = text.strip() # 去掉Hello 优快云前后的空格
print(clean_text) # "Hello 优快云"
2.自定义去除字符:
filename = "###temp_file.txt###"
clean_name = filename.strip('#') # 去掉temp_file.txt前后的#
print(clean_name) # temp_file.txt
3.多层清理:
data = "**重要通知** 2024年度计划 **"
# 先去除*,再去除空格
result = data.strip('*').strip()
# 先去除*变成:"重要通知** 2024年度计划 ",此时计划后面还有一个空格
# 再去除空格,变成"重要通知** 2024年度计划"
print(result) # 重要通知** 2024年度计划
4.特殊技巧:
-
使用
str.translate()
批量删除指定字符
remove_chars = str.maketrans('', '', '#!%')
text = "#Hello! 优快云%"
print(text.translate(remove_chars)) # Hello 优快云
四、replace():精准替换大师
功能:替换字符串中的指定子串。
核心参数:
-
old
:被替换的子串 -
new
:新子串 -
count
:最大替换次数(默认全部替换)
使用场景:
1.基础替换:
text = "I like Java"
new_text = text.replace("Java", "Python") # Java替换成Python
print(new_text) # I like Python
2.限制替换次数:
text = "apple apple apple"
new_text = text.replace("apple", "orange", 2) # apple替换成orange,替换两次
print(new_text) # orange orange apple
3.删除特定内容:
html = "<div>内容</div>"
clean_text = html.replace("<div>", "").replace("</div>", "")
# 字符串替换为空格,即删掉了原来的字符串
print(clean_text) # 内容
4.高阶应用:
-
配合正则表达式实现模式替换
import re text = "订单号:ABC123, 日期:2024-07-15" # 隐藏订单号 masked = re.sub(r'[A-Z]{3}\d{3}', '***', text) print(masked) # 订单号:***, 日期:2024-07-15
三、避坑指南
字符串不可变性
s = "Python"
s[0] = "J" # 报错!字符串不可直接修改
s = "J" + s[1:] # 正确:创建新对象
四、综合实战:日志清洗
需求:清理含冗余字符的日志数据
raw_log = '[ERROR] 2024-07-15 10:00:00, Invalid input: " test@demo.com " \n'
# 清洗步骤
cleaned_log = (
raw_log.strip() # 去除首尾空白
.replace('[ERROR]', '') # 删除错误标记
.replace('"', '') # 去除引号
.replace(' ', ' ') # 压缩连续空格
.split(',')[0] # 提取时间部分
)
print(cleaned_log) # 2024-07-15 10:00:00
五、总结
掌握字符串四大核心方法(split/join/strip/replace)是处理文本数据的基础。关键要点:
-
split:关注分隔符与空值处理
-
join:优先用于批量拼接
-
strip:灵活处理多种边界字符
-
replace:控制替换次数避免意外修改
进阶建议:
-
结合正则表达式处理复杂模式
-
使用
f-string
提升格式化代码可读性 -
在数据清洗场景中组合使用多个方法