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了

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值