Julik
Julik

Reputation: 7856

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?

Upvotes: 1

Views: 275

Answers (2)

user395760
user395760

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

inspectorG4dget
inspectorG4dget

Reputation: 114025

I'm not well versed in Ruby, but you might be looking for re.sub

Hope this helps

Upvotes: 1

Related Questions