Python lambda与正则表达式

Sto*_*oof 6 python regex lambda python-2.7

当使用re的re.sub()部分为python时,如果我没有弄错,可以使用一个函数作为sub.据我所知,它将匹配传递给传递的任何函数,例如:

r = re.compile(r'([A-Za-z]')
r.sub(function,string)
Run Code Online (Sandbox Code Playgroud)

除了使用调用方法的lambda之外,还有更聪明的方法让它传递给第二个arg吗?

r.sub(lambda x: function(x,arg),string)
Run Code Online (Sandbox Code Playgroud)

bra*_*zzi 8

你可以使用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
Run Code Online (Sandbox Code Playgroud)

在你的例子中:

def function(x, y):
     pass # ...
r.sub(functools.partial(function, y=arg),string)
Run Code Online (Sandbox Code Playgroud)

和正则表达式一起使用:

>>> 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'
Run Code Online (Sandbox Code Playgroud)