【问题标题】:python match case part of a stringpython匹配字符串的大小写部分
【发布时间】:2022-11-14 12:45:38
【问题描述】:

我想知道我是否可以在 Python 中使用匹配案例来匹配字符串 - 也就是说,如果字符串包含匹配案例。例子:

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

我可以明白为什么它不会,因为这可能会同时匹配多个案例,但我想知道它是否可能。

【问题讨论】:

  • 你能分享错误信息吗?请注意,这仅适用于python 3.10
  • 类似于 the answers here 的方法可能会奏效,尽管对于此类问题,其中任何一种方法都可能有点矫枉过正。

标签: python match python-3.10


【解决方案1】:

match语句中,strings are compared using == operator意味着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...

【讨论】:

  • Raymond Hettinger(长期 Python 核心开发人员)最近做了something similar 并没有说任何负面的东西,所以我猜这不是一件坏事......
  • @KellyBundy 哦,谢谢您的评论。 Raymond Hettinger 的超级粉丝在这里。首先,我没有发现覆盖 __eq__ 以委托给 __contains__ 作为一个好的模式。我将编辑我的答案以删除这些陈述。
  • 我现在无法使用match 进行测试,但我认为这些two variations 也可以。
【解决方案2】:

您可以使用 [*_] 通配符序列捕获模式: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"))

【讨论】:

    猜你喜欢
    • 2010-11-08
    • 2013-05-03
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-26
    • 2017-12-09
    相关资源
    最近更新 更多