python 正则表达式re.sub(re.subn)与lambda表达式

今天看见一位大佬把lambda与re.subn写到一块了, 于是好奇自己也写了一个

def func(ret, key, value):
    ret[key] = value
    return ''


string = 'apple pear banana meat'
ret = {}

re.subn(r'(apple|banana)\s(\w+)\s?', lambda x: func(ret, x.group(1), x.group(2)), string

基本功能是把字符串里面的前两个和后两个分别组成了两对键值对保存到ret里面,打印出ret的值看一下:

{'apple': 'pear', 'banana': 'meat'}

可以在ipython里面看一下这个模块的描述:

In [12]: re.sub?
Signature: re.sub(pattern, repl, string, count=0, flags=0)
Docstring:
Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl.  repl can be either a string or a callable;
if a string, backslash escapes in it are processed.  If it is
a callable, it's passed the Match object and must return
a replacement string to be used.
File:      c:\programdata\anaconda3\lib\re.py
Type:      function

因为python里面的函数也是callable的,所以也就可以用lambda了

你可能感兴趣的:(python)