Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there pattern matching functions in Python like this?

I just found the pattern matching feature in Racket very powerful.

> (match '(1 2 3) [(list a b c) (list c b a)])

'(3 2 1)

> (match '(1 2 3) [(list 1 a ...) a])

'(2 3)

> (match '(1 2 3)
    [(list 1 a ..3) a]
    [_ 'else])

'else

> (match '(1 2 3 4)
    [(list 1 a ..3) a]
    [_ 'else])

'(2 3 4)

> (match '(1 2 3 4 5)
    [(list 1 a ..3 5) a]
    [_ 'else])

'(2 3 4)

> (match '(1 (2) (2) (2) 5)
    [(list 1 (list a) ..3 5) a]
    [_ 'else])

'(2 2 2)

Is there similar syntax sugar or library to do that in Python?

like image 732
Hanfei Sun Avatar asked Aug 10 '12 21:08

Hanfei Sun


People also ask

Does Python have pattern matching?

'Structural Pattern Matching' was newly introduced in Python 3.10. The syntax for this new feature was proposed in PEP 622 in JUne 2020. The pattern matching statement of Python was inspired by similar syntax found in Scala, Erlang, and other languages.

How do you perform pattern matching in Python?

regex = r"([a-zA-Z]+) (\d+)" if re.search(regex, "Jan 2"): match = re.search(regex, "Jan 2") # This will print [0, 5), since it matches at the beginning and end of the # string print("Match at index %s, %s" % (match. start(), match. end())) # The groups contain the matched values. In particular: # match.

Does Python 3.9 have match?

As of early 2021, the match keyword does not exist in the released Python versions <= 3.9. Since Python doesn't have any functionality similar to switch/case in other languages, you'd typically use nested if/elif/else statements or a dictionary.

How do you check a pattern in Python?

Use re. match() to check if a string matches a pattern A pattern specifies a sequence of characters that can be matched to a string and follows the regular expression syntax in Python. re. match(pattern, string) tests if the regex pattern matches string .


1 Answers

No there is not, python's pattern matching is only iterable unpacking like this:

>>> (x, y) = (1, 2)
>>> print x, y
1 2

Or in function definition:

>>> def x((x, y)):
    ...

Or in python 3:

>>> x, *y = (1, 2, 3)
>>> print(x)
1
>>> print(y)
[2, 3]

But there are some of external libraries that realize pattern matching.

like image 175
Fedor Gogolev Avatar answered Sep 17 '22 20:09

Fedor Gogolev