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

Time:01-19

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

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

CodePudding user response:

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.

  • Related