Levani
Levani

Reputation: 53

Using the "in" operator in Python 3.10 Match Case

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.

Upvotes: 5

Views: 4273

Answers (2)

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 its contents. Hope this helps!!

Upvotes: 1

User
User

Reputation: 66071

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 ...

Upvotes: 8

Related Questions