Soo*_*oop 5 python match python-3.10
我想知道是否可以在 Python 中使用匹配大小写来在字符串中进行匹配 - 即字符串是否包含匹配大小写。例子:
mystring = "xmas holidays"
match mystring:
case "holidays":
return true
case "workday":
return false
Run Code Online (Sandbox Code Playgroud)
我可以理解为什么它不会,因为这可能会同时匹配多个案例,但我想知道这是否可能。
Fly*_*ynn 10
您可以使用[*_]通配符序列捕获模式: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"))
Run Code Online (Sandbox Code Playgroud)
您可以简单地使用守卫功能和捕获:
>>>my_str = "iwill/predict_something"
>>>match my_str:
... case str(x) if 'predict' in x:
... print("match!")
... case _:
... print("nah, dog")
...
match!
Run Code Online (Sandbox Code Playgroud)
在match语句中,使用运算符比较==字符串,这意味着case模式必须完全等于match表达式(mystring在本例中)。
为了解决这个问题,您可以创建一个继承str并重写该__eq__方法的自定义类。该方法应该委托给__contains__.
>>> class MyStr(str):
... def __eq__(self, other):
... return self.__contains__(other)
...
>>>
>>> mystring = MyStr("xmas holidays")
>>> match mystring:
... case "holiday":
... print("I am here...")
...
I am here...
Run Code Online (Sandbox Code Playgroud)