Files
Python_CookBook_repo/2.字符串和文本/5.查找和替换文本.py
2025-09-10 16:12:45 +08:00

23 lines
756 B
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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))