import re if __name__ == "__main__": text = "yeah, but no, but yeah, but no, but yeah" # 简单的替换可以使用replace函数来完成 text_change = text.replace('yeah', 'yep') print(text_change) # 对复杂的替换,我们可以使用re.sub模块 text = "Today is 11/27/2012. PyCon starts 3/12/2013" text_change = re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', text) print(text_change) # 如果需要多次替换,记得先编译再sub datepat = re.compile(r'(\d+)/(\d+)/(\d+)') print(datepat.sub(r'\3-\1-\2', text)) # 想要知道完成了几次替换,可以使用subn # subn返回一个元组,结构为(替换后的字符串, 替换次数) print(datepat.subn(r'\3-\1-\2', text))