Python字符串替换:str.replace()完全指南及进阶方法
Updated on
字符串替换是文本处理中最常见的操作之一。你需要清理用户输入、规范化数据格式、脱敏敏感信息或转换模板字符串。Python的str.replace()可以用一行代码处理简单情况,但当你需要不区分大小写的匹配、正则表达式模式或条件替换时,它就力不从心了。选择错误的工具意味着要么不必要地复杂化简单任务,要么为复杂任务编写脆弱的代码。
本指南涵盖了Python中字符串替换的所有方法——从基本的str.replace()到基于正则的re.sub()、字符级别的translate(),以及用于实际文本处理的实用模式。
str.replace(old, new, count)
最简单也是最常用的方法。将所有old替换为new。可选的count参数限制替换次数。
text = "Hello World, Hello Python, Hello Everyone"
# 替换所有出现
print(text.replace("Hello", "Hi"))
# Hi World, Hi Python, Hi Everyone
# 仅替换前2次出现
print(text.replace("Hello", "Hi", 2))
# Hi World, Hi Python, Hello Everyone
# 删除子字符串(替换为空字符串)
messy = " extra spaces here "
print(messy.replace(" ", ""))
# extraspaceshere关键行为
- 返回一个新字符串(Python中字符串是不可变的)
- 默认区分大小写
- 除非指定
count,否则替换所有出现 - 如果未找到
old,返回原始字符串不变
original = "Python is great"
new = original.replace("great", "awesome")
print(original) # Python is great(未改变)
print(new) # Python is awesome不区分大小写的替换
str.replace()始终区分大小写。要进行不区分大小写的替换,使用re.sub()配合re.IGNORECASE标志。
import re
text = "Python is Great, python is Fun, PYTHON is Everywhere"
# 不区分大小写替换
result = re.sub(r'python', 'Java', text, flags=re.IGNORECASE)
print(result)
# Java is Great, Java is Fun, Java is Everywhere使用re.sub()进行正则替换
re.sub(pattern, replacement, string, count, flags)替换正则表达式模式的匹配项。
import re
# 将数字替换为'#'
text = "Call 555-1234 or 555-5678"
print(re.sub(r'\d', '#', text))
# Call ###-#### or ###-####
# 替换完整的电话号码
print(re.sub(r'\d{3}-\d{4}', '[已脱敏]', text))
# Call [已脱敏] or [已脱敏]
# 将多个空格替换为单个空格
messy = "too many spaces here"
print(re.sub(r'\s+', ' ', messy))
# too many spaces here使用捕获组
import re
# 交换姓和名
names = "Smith, John\nDoe, Jane\nBrown, Bob"
swapped = re.sub(r'(\w+), (\w+)', r'\2 \1', names)
print(swapped)
# John Smith
# Jane Doe
# Bob Brown
# 为日期添加格式
dates = "Meeting on 2026-02-10 and 2026-03-15"
formatted = re.sub(r'(\d{4})-(\d{2})-(\d{2})', r'\2/\3/\1', dates)
print(formatted)
# Meeting on 02/10/2026 and 03/15/2026使用函数进行动态替换
传入函数而非字符串来进行条件替换:
import re
def censor_word(match):
word = match.group()
return word[0] + '*' * (len(word) - 1)
text = "The password is secret and the code is hidden"
censored = re.sub(r'secret|hidden', censor_word, text)
print(censored)
# The password is s***** and the code is h*****import re
# 仅对特定单词转换为标题大写
def smart_capitalize(match):
word = match.group()
minor_words = {'a', 'an', 'the', 'and', 'or', 'but', 'in', 'on', 'at', 'to'}
if word.lower() in minor_words:
return word.lower()
return word.capitalize()
title = "the quick BROWN fox AND the lazy DOG"
result = re.sub(r'\b\w+\b', smart_capitalize, title)
print(result)
# the Quick Brown Fox and the Lazy Dog多重替换
链式调用replace()
text = "Hello World! How are you?"
result = text.replace("Hello", "Hi").replace("World", "Earth").replace("you", "they")
print(result) # Hi Earth! How are they?基于字典的替换
对于大量替换,使用字典配合re.sub():
import re
def multi_replace(text, replacements):
"""使用字典替换多个子字符串。"""
pattern = re.compile('|'.join(re.escape(k) for k in replacements))
return pattern.sub(lambda m: replacements[m.group()], text)
text = "The cat sat on the mat with another cat"
replacements = {
'cat': 'dog',
'mat': 'rug',
'sat': 'stood',
}
print(multi_replace(text, replacements))
# The dog stood on the rug with another dog使用translate()进行字符级替换
替换单个字符时,str.translate()配合str.maketrans()是最快的选择:
# 替换字符: a->@, e->3, o->0
table = str.maketrans('aeo', '@30')
text = "Hello World"
print(text.translate(table))
# H3ll0 W0rld
# 删除特定字符
remove_vowels = str.maketrans('', '', 'aeiouAEIOU')
print("Hello World".translate(remove_vowels))
# Hll Wrld
# 一次调用中同时替换和删除
table = str.maketrans({'a': '@', 'e': '3', ' ': None})
print("apple pie".translate(table))
# @ppl3pi3方法比较
| 方法 | 最适用场景 | 正则 | 速度 | 灵活性 |
|---|---|---|---|---|
str.replace() | 简单的字面替换 | 否 | 最快 | 低 |
re.sub() | 模式匹配、复杂规则 | 是 | 中等 | 最高 |
str.translate() | 单字符映射 | 否 | 非常快 | 低 |
链式 .replace() | 少量字面替换 | 否 | 快 | 低 |
Dict + re.sub() | 大量同时替换 | 是 | 中等 | 高 |
实用示例
清理和规范化文本
import re
def clean_text(text):
"""规范化文本以进行处理。"""
text = text.strip()
text = re.sub(r'\s+', ' ', text) # 合并空白
text = re.sub(r'[^\w\s.,!?-]', '', text) # 删除特殊字符
text = text.lower()
return text
raw = " Hello!!! This is MESSY @#$ text... "
print(clean_text(raw))
# hello!!! this is messy text...模板字符串替换
template = "Dear {name}, your order #{order_id} ships on {date}."
data = {
'name': 'Alice',
'order_id': '12345',
'date': 'Feb 15, 2026',
}
# 使用str.format_map(比手动替换更好)
result = template.format_map(data)
print(result)
# Dear Alice, your order #12345 ships on Feb 15, 2026.脱敏敏感数据
import re
def redact_pii(text):
"""脱敏邮箱、电话号码和SSN。"""
text = re.sub(r'\b[\w.]+@[\w.]+\.\w+\b', '[邮箱]', text)
text = re.sub(r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b', '[电话]', text)
text = re.sub(r'\b\d{3}-\d{2}-\d{4}\b', '[SSN]', text)
return text
msg = "Contact john@example.com or call 555-123-4567. SSN: 123-45-6789"
print(redact_pii(msg))
# Contact [邮箱] or call [电话]. SSN: [SSN]在Jupyter中处理文本数据
文本清理和转换是迭代性的工作——你需要针对样本数据测试模式、调整正则表达式并验证结果。RunCell (opens in a new tab)是一个Jupyter AI代理,可以帮助你交互式地构建和调试文本处理管道,实时针对你的实际数据测试替换模式。
FAQ
如何在Python中替换子字符串?
使用str.replace(old, new)进行简单替换:"hello world".replace("world", "python")返回"hello python"。这会替换所有出现。添加第三个参数来限制替换次数:text.replace("a", "b", 2)只替换前2个匹配。
如何在Python中进行不区分大小写的替换?
使用re.sub()配合re.IGNORECASE标志:re.sub(r'python', 'Java', text, flags=re.IGNORECASE)。内置的str.replace()方法不支持不区分大小写的匹配。
如何一次替换多个不同的字符串?
从替换字典构建正则表达式模式:创建一个匹配所有键的编译模式,然后使用lambda查找每个匹配的替换值。或者,对于少量的字面替换,链式调用.replace()。
str.replace()和re.sub()有什么区别?
str.replace()只进行字面字符串匹配——速度更快也更简单。re.sub()使用正则表达式,支持模式匹配、捕获组、反向引用和基于函数的替换。简单的字面替换用str.replace(),需要模式灵活性时用re.sub()。
如何从Python字符串中删除字符?
三种方法:str.replace(char, "")删除特定子字符串的所有出现。str.translate(str.maketrans("", "", chars))高效地删除所有指定字符。re.sub(r"[pattern]", "", text)删除匹配正则模式的字符。
总结
Python提供了多种字符串替换工具,每种都适合不同的复杂度级别。简单的字面替换用str.replace(),模式匹配和复杂规则用re.sub(),快速字符级映射用str.translate()。对于多重同时替换,基于字典的re.sub()方法能让你的代码保持整洁和可维护。