从开始Python 3.8
,并引入赋值表达式(PEP 572)(:=
运算符),我们现在可以将条件值捕获到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)