Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python match case part of a string

I want to know if I can use match cases within Python to match within a string - that is, if a string contains the match case. Example:

mystring = "xmas holidays"
match mystring:
      case "holidays":
           return true
      case "workday":
           return false

I can see why it wouldn't, since this could potentially match several cases at once, but I wanted to know if it was possible.

like image 307
Soop Avatar asked Mar 02 '26 03:03

Soop


2 Answers

You can simply use the guard feature along with capture:

>>>my_str = "iwill/predict_something"
>>>match my_str:
...    case str(x) if 'predict' in x:
...        print("match!")
...    case _:
...        print("nah, dog")
...
match!
like image 169
hyperGeoMetric Avatar answered Mar 04 '26 16:03

hyperGeoMetric


You could use the [*_] wildcard sequence capture pattern: https://peps.python.org/pep-0622/#sequence-patterns

def is_holiday(yourstring: str):
    match yourstring.split():
        case [*_, "holidays"]:
            return True
        case [*_, "workday"]:
            return False


print(is_holiday("xmas holidays"))

like image 45
Flynn Avatar answered Mar 04 '26 17:03

Flynn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!