本文目录导读:

- 使用
str.replace()方法(最常用) - 使用
re.sub()正则表达式(复杂替换) - 使用
str.maketrans()和str.translate()(字符映射) - 实战示例
- 性能对比
- 总结建议
在Python中替换指定字符串有多种方法,我来介绍几种常用的:
使用 str.replace() 方法(最常用)
# 基本用法
text = "Hello World, Hello Python"
new_text = text.replace("Hello", "Hi")
print(new_text) # 输出: Hi World, Hi Python
# 指定替换次数
text = "apple apple apple apple"
new_text = text.replace("apple", "orange", 2) # 只替换前2个
print(new_text) # 输出: orange orange apple apple
使用 re.sub() 正则表达式(复杂替换)
import re # 简单替换 text = "Hello 123 World 456" new_text = re.sub(r'\d+', 'NUM', text) print(new_text) # 输出: Hello NUM World NUM # 忽略大小写 text = "Hello hello HELLO" new_text = re.sub(r'hello', 'Hi', text, flags=re.IGNORECASE) print(new_text) # 输出: Hi Hi Hi
使用 str.maketrans() 和 str.translate()(字符映射)
# 创建映射表
trans_table = str.maketrans({
'a': '1',
'b': '2',
'c': '3'
})
text = "abcabc"
new_text = text.translate(trans_table)
print(new_text) # 输出: 123123
实战示例
def replace_text(text, old, new, case_sensitive=True):
"""
自定义替换函数
"""
if case_sensitive:
return text.replace(old, new)
else:
import re
return re.sub(re.escape(old), new, text, flags=re.IGNORECASE)
# 示例
text = "Python is great, python is powerful"
# 区分大小写替换
print(replace_text(text, "Python", "Java"))
# 输出: Java is great, python is powerful
# 忽略大小写替换
print(replace_text(text, "python", "Java", case_sensitive=False))
# 输出: Java is great, Java is powerful
# 处理文件内容
def replace_in_file(filename, old, new):
"""替换文件中的字符串"""
with open(filename, 'r', encoding='utf-8') as f:
content = f.read()
new_content = content.replace(old, new)
with open(filename, 'w', encoding='utf-8') as f:
f.write(new_content)
print(f"文件 {filename} 中的 '{old}' 已替换为 '{new}'")
# 批量替换多个字符串
def batch_replace(text, replacements):
"""批量替换多个字符串"""
result = text
for old, new in replacements.items():
result = result.replace(old, new)
return result
# 使用示例
text = "Hello World, Hello Python"
replacements = {
"Hello": "Hi",
"World": "Universe",
"Python": "Java"
}
new_text = batch_replace(text, replacements)
print(new_text) # 输出: Hi Universe, Hi Java
性能对比
import timeit
import re
text = "test" * 10000
# 方法1: str.replace()
def method1():
return text.replace("test", "demo")
# 方法2: re.sub()
def method2():
return re.sub(r'test', 'demo', text)
# 测试性能
print("str.replace:", timeit.timeit(method1, number=1000))
print("re.sub:", timeit.timeit(method2, number=1000))
总结建议
- 简单替换:使用
str.replace()(性能最好) - 正则替换:使用
re.sub()(功能最强大) - 字符映射:使用
str.translate()(适合一对一字符替换) - 批量替换:使用循环或字典映射
根据具体需求选择最合适的方法!
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播