17370845950

python-字符串替换
Python字符串替换需生成新字符串,常用方法有:1. 使用replace()进行简单替换,如s.replace("world", "Python");2. 用re.sub()支持正则和忽略大小写替换;3. 结合字典与正则实现批量替换;4. 注意原字符串不变,replace()精确匹配速度快,re.sub()功能强但稍慢,复杂场景推荐使用re.escape()防特殊字符错误。

Python字符串替换方法详解

在Python中,字符串是不可变类型,因此不能直接修改原字符串。要实现字符串替换,需要生成一个新的字符串。Python提供了多种方式来进行字符串内容的替换,以下是常用且实用的方法。

1. 使用 replace() 方法

这是最常见、最简单的字符串替换方式。replace(old, new, count) 将字符串中的 old 子串替换成 new 子串。count 是可选参数,表示最多替换几次。

示例:

s = "hello world"
new_s = s.replace("world", "Python")
print(new_s)  # 输出: hello Python

只替换第一次出现

text = "apple apple apple" result = text.replace("apple", "orange", 2) print(result) # 输出: orange orange apple

2. 使用 re.sub() 进行正则替换

当需要更灵活的匹配(如大小写忽略、模式匹配等),可以使用 re 模块的 sub() 函数。

示例:忽略大小写替换

import re

text = "Hello WORLD, hello Python" result = re.sub(r"hello", "Hi", text, flags=re.IGNORECASE) print(result) # 输出: Hi WORLD, Hi Python

也可以使用回调函数动态替换:

# 将数字都加1
def add_one(match):
    num = int(match.group())
    return str(num + 1)

text = "There are 5 apples and 10 oranges" result = re.sub(r'\d+', add_one, text) print(result) # 输出: There are 6 apples and 11 oranges

3. 多次替换的处理方式

如果要一次性替换多个不同的子串,可以使用循环或字典配合 re.sub() 实现。

import re

text = "I love cats and dogs" replacements = {"cats": "birds", "dogs": "fish"}

构造正则表达式,匹配任意一个要替换的词

pattern = re.compile("|".join(re.escape(key) for key in replacements.keys())) result = pattern.sub(lambda match: replacements[match.group()], text)

print(result) # 输出: I love birds and fish

4. 注意事项与建议

  • 字符串替换不会改变原字符串,必须接收返回值。
  • replace() 是精确匹配,不支持模式,速度快。
  • re.sub() 更强大,但性能稍低,适合复杂场景。
  • 使用 re.escape() 防止替换关键词中包含正则特殊字符出错。

基本上就这些。根据实际需求选择合适的方法即可。简单替换用 replace(),复杂规则用 re.sub(),批量替换结合字典和正则处理。不复杂但容易忽略细节。