How do you translate this regular-expression idiom from Perl into Python?

后端 未结 15 681
情深已故
情深已故 2020-12-04 11:16

I switched from Perl to Python about a year ago and haven\'t looked back. There is only one idiom that I\'ve ever found I can do more easily in Perl than in Python:<

15条回答
  •  甜味超标
    2020-12-04 11:58

    A minimalist DataHolder:

    class Holder(object):
        def __call__(self, *x):
            if x:
                self.x = x[0]
            return self.x
    
    data = Holder()
    
    if data(re.search('foo (\d+)', string)):
        print data().group(1)
    

    or as a singleton function:

    def data(*x):
        if x:
            data.x = x[0]
        return data.x
    

提交回复
热议问题