Skip to content
Advertisement

Walrus operator for filtering regex searches in list comprehension

I have a Python list of strings. I want to do the regex search on each element, filtering only those elements where I managed to capture the regex group. I think I can do the regex search only once using the walrus operator from Python 3.8. So far I have:

JavaScript

The logic is: I take the found group if the regex search returned anything, which means it is not None. The problem is, the bevahiour is weird – I can print() before this list comprehension, the program finishes with code 0, but there is no result and print() after the list comprehension does not work. What am I doing wrong?

EDIT:

Full code:

JavaScript

Advertisement

Answer

Remove the .group() is not None. If there isn’t any match, re.search() returns None and exception is thrown:

JavaScript

Prints:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement