I have a simple function that should output a prefix based on a pattern or None
if it does not match. Trying to do a walrus it does not seem to work. Any idea?
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
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
tore.match(f'^.+(\d\d)-(\d\d)-(\d\d\d\d)$', name) is not None
, which is a boolean. Get rid ofis not None
. – Purelyis not None
is redundant anyway, becausere.match
always returns either a (non-falsy) match object orNone
. – Gaytonis None
since it compares the identities directly instead of having to call__bool__()
. Also it's more explicit and, according to PEP-8, more Pythonic. – Howlyn