我试图使用re.sub()
执行多个替换,除了我希望第一个替换是不同的.一个简单的方法是在第一次调用时使用count = 1
运行两次re.sub()
,但是因为re.sub()
允许repl
参数成为函数,所以我们可以在一次调用中实现这一点:
import re
def repl(matchobj):
global first_sub
if first_sub:
first_sub = False
print(f"Replacing '{matchobj.group()}' at {matchobj.start()} with ':)'")
return ":)"
else:
print(f"Deleting '{matchobj.group()}' at {matchobj.start()}")
return ""
text = "hello123 world456"
first_sub = True
text = re.sub(r"\d+", repl, text)
# Output:
# Replacing '123' at 5 with ':)'
# Deleting '456' at 14
不幸的是,这使用了global
,这不是很好.有没有更好的办法?