Reputation: 7856
I have this simple regexp replacement code with a block in it. When Ruby does the gsub the match is passed to the block and whatever is returned from the block is used as replacement.
string = "/foo/bar.####.tif"
string.gsub(/#+/) { | match | "%0#{match.length}d" } # => "/foo/bar.%04d.tif"
Is there a way to do this in Python while keeping it concise? Is there a ++replace++ variant that supports lambdas or the with statement?
Upvotes: 1
Views: 275
Reputation:
re.sub
accepts a function as replacement. It gets the match object as sole parameter and returns the replacement string.
If you want to keep it a oneliner, a lambda will do work: re.sub(r'#+', lambda m: "%0"+str(len(m.group(0))), string)
. I'd just use a small three-line def
to avoid having all those parens in one place, but that's just my opinion.
Upvotes: 8
Reputation: 114025
I'm not well versed in Ruby, but you might be looking for re.sub
Hope this helps
Upvotes: 1