Search code examples
pythonrubyregexcoding-styleblock

Pythonic way to do Ruby-like regular expression replace while evaluating the matched string


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?


Solution

  • 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.