代码点读机 / Python / re.sub

re.sub Python · 模块功能

把字符串里匹配正则的部分替换成新内容。

怎么用

import re
re.sub(pattern, repl, s)

小例子

import re
print(re.sub(r'\d', '*', 'a1b2'))

运行结果

a*b*

提醒:替换所有匹配。

官方文档:https://docs.python.org/zh-cn/3/library/re.html#re.sub

在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← Python全部词条