能否在Python的match case语句中使用endswith/startswith方法?
Python match case中使用endswith/startswith的正确方式
你给出的写法不被Python支持,match case的case分支里不能直接以.endswith()或.startswith()的形式作为匹配模式,这种语法不符合Python模式匹配的规则。
要实现匹配字符串开头/结尾的需求,有两种常用方式:
1. 使用守卫条件(最直接)
在case分支后添加if条件判断方法调用结果,这是日常开发里最简便的写法:
match text_string: case 'bla-bla': return 'bla' case s if s.endswith('endofstring'): return 'ends' case s if s.startswith('somestart'): return 'start'
这里的s会绑定当前匹配的text_string变量,如果你不需要这个变量,也可以用_代替:
case _ if _.endswith('endofstring'): return 'ends'
2. 自定义匹配模式(适合复用场景)
如果需要在多个地方复用相同的开头/结尾匹配逻辑,可以定义自定义模式类,利用Python 3.10+支持的__match__魔法方法:
class EndsWith: def __init__(self, suffix): self.suffix = suffix def __match__(self, value): return isinstance(value, str) and value.endswith(self.suffix) class StartsWith: def __init__(self, prefix): self.prefix = prefix def __match__(self, value): return isinstance(value, str) and value.startswith(self.prefix)
使用时就可以像内置模式一样调用:
match text_string: case 'bla-bla': return 'bla' case EndsWith('endofstring'): return 'ends' case StartsWith('somestart'): return 'start'
内容的提问来源于stack exchange,提问作者Ilya
相关产品推荐
相关产品推荐

