Search code examples
pythonpattern-matchingwildcardpython-3.10

SyntaxError when using python pattern matching with condition and a wildcard


I want to use pattern matching to pass through two variables and I need to use conditions with both of them in different cases.

match '12345', '23456':
    case _, b if '456' in b:
        print('True')
    case a if '123' in a, _:
        print('True')
    case _:
        print('False')

I got SyntaxError: invalid syntax on that second case. The first one seems to be working though. It seems like one cannot use wildcard _ after condition. I know I could use two match/case constructions or classical if/elif/else, but I would prefer single match/case construction to work.

Python version - 3.10.6


Solution

  • I think you've simply got the wrong idea about how the syntax works.

    (disclaimer: I've never used this new feature of python 3)

    I think you should have the pattern to the left and the if on the right:

    match '12345', '23456':
        case _, b if '456' in b:
            print('True')
        case a,_ if '123' in a:
            print('True')
        case _:
            print('False')