pythonmatchcase

Is there a way to use endswith/startswith in match case statements?


Is there a way to use match case to select string endings/beginnings like below?

match text_string:
  case 'bla-bla':
    return 'bla'
  case .endswith('endofstring'):
    return 'ends'
  case .startswith('somestart'):
    return 'start'

Solution

  • You were close. You wanted a conditional guard on a pattern. In the following case, one that simply matches the value.

    match text_string:
      case 'bla-bla':
        return 'bla'
      case s if s.endswith('endofstring'):
        return 'ends'
      case s if s.startswith('somestart'):
        return 'start'
    

    This doesn't gain much over the following.

    if text_string == 'bla-bla':
      return 'bla'
    elif text_string.endswith('endofstring'):
      return 'ends'
    elif text_string.startswith('somestart'):
      return 'start'
    

    Unless you're also using the match and want to differentiate between two otherwise identical patterns.