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.
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!
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With