Python lambda with regex

When using the re.sub () part of re for python, the function can be used for sub, if I'm not mistaken. As far as I know, it passes any function in the match, for example:

r = re.compile(r'([A-Za-z]') r.sub(function,string) 

Is there a smarter way to pass it in a second argument other than the lambda that calls the method?

 r.sub(lambda x: function(x,arg),string) 
+6
source share
1 answer

You can use functools.partial :

 >>> from functools import partial >>> def foo(x, y): ... print x+y ... >>> partial(foo, y=3) <functools.partial object at 0xb7209f54> >>> f = partial(foo, y=3) >>> f(2) 5 

In your example:

 def function(x, y): pass # ... r.sub(functools.partial(function, y=arg),string) 

And the real use with regular expressions:

 >>> s = "the quick brown fox jumps over the lazy dog" >>> def capitalize_long(match, length): ... word = match.group(0) ... return word.capitalize() if len(word) > length else word ... >>> r = re.compile('\w+') >>> r.sub(partial(capitalize_long, length=3), s) 'the Quick Brown fox Jumps Over the Lazy dog' 
+8
source

Source: https://habr.com/ru/post/914924/


All Articles