大约一年前,我从Perl切换到Python,并且没有回头。我发现只有 一个 成语比起Python更容易实现:
if ($var =~ /foo(.+)/) { # do something with $1 } elsif ($var =~ /bar(.+)/) { # do something with $1 } elsif ($var =~ /baz(.+)/) { # do something with $1 }
由于if语句不断嵌套,因此相应的Python代码不太好用:
m = re.search(r'foo(.+)', var) if m: # do something with m.group(1) else: m = re.search(r'bar(.+)', var) if m: # do something with m.group(1) else: m = re.search(r'baz(.+)', var) if m: # do something with m.group(2)
有没有人有优雅的方法可以在Python中重现此模式?我已经看到使用了匿名函数调度表,但是对于少量的正则表达式来说,这些表对我来说似乎有点笨拙……
从开始Python 3.8,并引入赋值表达式(PEP 572)(:=运算符),我们现在可以将条件值捕获到re.search(pattern, text)变量match中,以便检查是否存在条件值None,然后在条件主体内重新使用它:
Python 3.8
:=
re.search(pattern, text)
match
None
if match := re.search(r'foo(.+)', text): # do something with match.group(1) elif match := re.search(r'bar(.+)', text): # do something with match.group(1) elif match := re.search(r'baz(.+)', text) # do something with match.group(1)