Search code examples
pythonwalrus-operator

python: walrus operator and re.search() in list comprehension


I have a list of strings and I want to extract a pattern from elements.

For instance, given list ["A 12345bcd", "BYT 676 CCC"] and pattern r'\d\d\d\d\d', I would like to obtain: ["12345", ""]

I know how to do without it, but I want to use walrus operator :=.

I tried:

[(m:=re.search(r'\d\d\d\d\d', x), m.group() if m else "") for x in ["A 12345bcd", "BYT 676 CCC"]]

But the result is:

[(<re.Match object; span=(2, 7), match='12345'>, '12345'), (None, '')]

Hence, not what I want


Solution

  • This is a tuple:

    (m:=re.search(r'\d\d\d\d\d', x), m.group() if m else "")
    

    This is the group/empty conditional expression with m := evaluated appropriately early:

    m.group() if (m := re.search(r'\d\d\d\d\d', x)) else ""