Using the "in" operator in Python 3.10 Match Case

Question:

Is there a "in" operator in python 3.10 Match Case like with if else statements

if "n" in message:

the in operator doesn’t work in match case

match message:
    case "n" in message:

This doesn’t work.
How to have something like the "in" operator in Match-Case.

Asked By: Levani

||

Answers:

In match-case we can use the split() method on the message string.

Example:

def match_case_with_if(command):
    match command.split():
        case [*command_list] if 'install' in command_list:
            print(f"Hey you are installing {command_list[-1]}....")
        case [*command_list] if 'uninstall' in command_list:
            print(f"Are you sure you want to uninstall {command_list[-1]} ?")


match_case_with_if('pip install numpy')
# Output: Hey you are installing numpy....
match_case_with_if('pip uninstall numpy')
# Output: Are you sure you want to uninstall numpy ?

Here, the string can be split into a list and if condition can be applied on it’s contents.
Hope this helps!!

For completeness, it can be done indirectly using guards (as used in the other answer).

match message:
    case message if "n" in message:
        ... some code...
    case message if "foo" in message:
        ... some other code...

Note using the name message in each case statement is not required (this does have the side effect of binding the name x to a value):

match message:
    case x if "n" in x:
        ... some code...
    case x if "foo" in x:
        ... some other code...
    

Or you can also use wildcards (which skips the name binding):

match message:
    case _ if "n" in message:
        ... some code...
    case _ if "foo" in message:
        ... some other code...

But you’re probably better off just using an if statement since using match-case is more code and has worse readability for this situation

if "n" in message:
    ... some code ...
elif "foo" in message:
    ... some code ...
else:
    ... some code ...
Answered By: User
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.