Python中的sub()函数是re模块提供的正则表达式替换方法,用于在字符串中搜索匹配正则表达式的模式,并将其替换为指定的内容。该函数是处理文本替换任务的核心工具之一。
re.sub(pattern, repl, string, count=0, flags=0)
import re
result = re.sub(r'apple', 'orange', 'I have an apple')
print(result) # 输出: I have an orange
# 重组日期格式
text = '2023-08-15'
result = re.sub(r'(\d{4})-(\d{2})-(\d{2})', r'\2/\3/\1', text)
print(result) # 输出: 08/15/2023
def double_match(match):
return str(int(match.group()) * 2)
result = re.sub(r'\d+', double_match, '找到数字: 123 和 456')
print(result) # 输出: 找到数字: 246 和 912
result = re.sub(r'a', 'A', 'banana', count=2)
print(result) # 输出: bAnAna
Python的sub()函数是处理文本替换的强大工具,结合正则表达式可以实现复杂的字符串操作。掌握其用法能够大大提高文本处理任务的效率和灵活性。