Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I use list slicing on my match/case term in Python3

To elaborate I have a string x that will be in the structure of

"Test_Case_Box 1"
"Test_Case_Box 2"
"Test_Case_Circle 1"

I was using if and elif statements by checking for example if

x[0:19] == "Test_Case_Box"

With the match/case syntax if I set the term as my string x, can I still create if like cases, for example

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

match x:
                case x[0:10] == 'Request_Fun':
                    print(f'-- x[0:10]: {x[0:10]}')

>Solution :

There is no need to use slicing. To use the full benefit of match, you can split the input:

strs = ["Test_Case_Box 1", "Test_Case_Box 2", "Test_Case_Circle 3"]

for s in strs:
    match s.split():
        case ["Test_Case_Box", num]:
            print(num)

Will print:

1
2

The benefit of using match here is that you get both structural matching and assigning variables at one go. Using if/elif you will need to parse the structure and then parse inside the conditions to extract the number for example.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading