ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] >[success] # 文字替换 re.sub和str.replace >[danger] ##### str.replace ~~~ line = "asdf fjdk; afed,asdf, foo foo" line_replace = line.replace("asdf", "ss") print(line_replace) 打印结果: ss fjdk; afed,ss, foo foo ~~~ >[danger] ##### re.sub("正则把什么",“替换成什么”,在哪个str中) ~~~ import re line = "asdf fjdk; afed,asdf, foo foo" a = re.sub(r'(^a\w+)',"bbb",line) print(a) 打印结果: bbb fjdk; afed,asdf, foo foo ~~~ >[danger] ##### sub 日期替换例子 ~~~ import re line = "Today is 11/27/2012 pyCon starts 3/13/2013" # 利用分组 重新匹配顺序 a = re.sub(r'(\d+)/(\d+)/(\d+)',r'\3-\1-\2',line) print(a) 打印结果: Today is 2012-11-27 pyCon starts 2013-3-13 ~~~