Home > other >  How to use the `match` keyword to match a range?
How to use the `match` keyword to match a range?

Time:07-16

Is it possible to use the new match keyword to match a range of characters?

Basically to do something like this?

match "b":
    case "a":
        print("a")
    case range("a", "z"):
        print("alphabet")

If not, what are the cheap in characters alternatives ?

CodePudding user response:

You would need to define a class which has an instance that can compare equal to "b", then find a way to refer to such an object using a dotted name. Something like

class CharRange:
    def __init__(self, start, stop):
        self.start = start
        self.stop = stop

    def __eq__(self, other):
        if isinstance(other, str):
            return self.start <= other <= self.stop
        else:
            return self.start == other.start and self.stop == other.stop

class CharRanges:
    lowercase = CharRange("a", "z")

match "b":
    case "a":
        print("a")
    case CharRanges.lowercase:
        print("alphabet")

You can't use case CharRange("a", "z") because that's a class pattern, which (without going into how class patterns work) won't help you here, and you can't use

x = CharRange("a", "z")
match "b":
    case x:
        ...

because x is a capture pattern, matching anything and binding it to the name x.

CodePudding user response:

If you are looking for the target value in a list of values, in the case of individual lowercase characters from b-z, you want to use the in operator to find your target value.

def main():
    target = 'b'
    values = [chr(ascii) for ascii in list(range(ord('b'), ord('z') 1))]
    match target:
        case "a":
            print("a")
        case values if target in values:
            print("alphabet minus a")
        case _:
            print("other")

    return
  • Related