在 if 语句中使用海象运算符不起作用

Using a walrus operator in if statement does not work

我有一个简单的函数,它应该根据模式输出前缀,如果不匹配则 None。试图做一只海象似乎没有用。有什么想法吗?

import re

def get_prefix(name):
    if m := re.match(f'^.+(\d\d)-(\d\d)-(\d\d\d\d)$', name) is not None:
        return m.group(3) + m.group(2) + m.group(1)

get_prefix('abc 10-12-2020')

回溯

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in get_prefix
AttributeError: 'bool' object has no attribute 'group'

您正在将 m 设置为 re.match(f'^.+(\d\d)-(\d\d)-(\d\d\d\d)$', name) is not None,这是一个布尔值。

你的意思可能是

if (m := re.match(f'^.+(\d\d)-(\d\d)-(\d\d\d\d)$', name)) is not None:

但是这里你不需要 is not None。匹配是真实的,None 是虚假的。所以你只需要:

if m := re.match(f'^.+(\d\d)-(\d\d)-(\d\d\d\d)$', name):

(可以说,每当您使用赋值表达式时,最好使用 () 来明确赋值的内容。)

PEP572#Relative precedence of :=