Match Case with the Sequence Pattern
Python match case statements are commonly used to match sequence patterns such as lists and strings. It is quite easy and can use positional arguments for checking the the patterns.
Example: In this example, we are using a python string to check if a character is present in the string or not using match case. We provide the string along with the index of the character we want to check for in the string to the match case. Then we defined the match cases as to what that character might be.
# match case to check a character in a string
def runMatch():
myStr = "Hello World"
# match case
match (myStr[6]):
case "w":
print("Case 1 matches")
case "W":
print("Case 2 matches")
case _:
print("Character not in the string")
runMatch()
Output:
Case 2 matches
Example: In this example we are using a python list for pattern matching. We are matching the first element of the lost and also used positional arguments to match the rest of the list.
# python match case with list
def runMatch(mystr):
# match case
match mystr:
# pattern 1
case ["a"]:
print("a")
# pattern 2
case ["a", *b]:
print(f"a and {b}")
# pattern 3
case [*a, "e"] | (*a, "e"):
print(f"{a} and e")
# default pattern
case _:
print("No data")
runMatch([])
runMatch(["a"])
runMatch(["a", "b"])
runMatch(["b", "c", "d", "e"])
Output:
No data
a
a and ['b']
['b', 'c', 'd'] and e
Python Match Case Statement
Developers coming from languages like C/C++ or Java know that there is a conditional statement known as a Switch Case. This Match Case is the Switch Case of Python which was introduced in Python 3.10. Here we have to first pass a parameter and then try to check with which case the parameter is getting satisfied. If we find a match we will execute some code and if there is no match at all, a default action will take place.