1

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?

3
  • It'd be useful to include an example of the intended output for people not familiar with ruby. Commented May 9, 2011 at 17:53
  • @zeekay: The expected output is in the comment after the second line. Commented May 9, 2011 at 17:56
  • And I thought the whole thing was gibberish :O Commented May 9, 2011 at 18:04

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I went for the nested def this time, thanks alot! the trick here was the group(0) thing since the default str() for SRE_Match is not as useful as Ruby's to_s()
1

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

Hope this helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.