当使用re的re.sub()部分为
python时,如果我没有弄错,可以使用一个函数作为sub.据我所知,它将匹配传递给传递的任何函数,例如:
- r = re.compile(r'([A-Za-z]')
- r.sub(function,string)
除了使用调用方法的lambda之外,还有更聪明的方法让它传递给第二个arg吗?
- r.sub(lambda x: function(x,arg),string)
解决方法
你可以使用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
在你的例子中:
- def function(x,y):
- pass # ...
- r.sub(functools.partial(function,y=arg),string)
和正则表达式一起使用:
- >>> 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'