pythonregextuplesvariable-assignmentmultiple-return-values

How to use re.findall in python


Here is my program:

import re
string = "I have 56 apples, Tom has 34 apples, Mary has 222 apples"

apple = re.findall(r'\d{1,100}', string)
print (apple)

And the outcome is:

['56', '34', '222']

I want to name the three numbers above so that I can do some calculation. I also want to name the first outcome a, second one b, third one c. And then calculate a+b or a+c, something like that. Could anyone tell me how to do it.

If re.findall can't solve my case here, is there another way to achieve this goal?


Solution

  • If you want, you can use tuple assignment on the LHS:

    a,b,c = re.findall(r'\d{1,100}', string)
    

    This is equivalent to writing (a,b,c) = ... ; you no longer need to put parentheses around a tuple if it's on LHS of an assignment.

    This is bad coding style as @SterlingArcher said, because unless you get exactly three items, or if your string was bad, or regex failed, you get an error.

    One tactic is to use a trailing _ as a don't-care variable to soak up any extra items: a,b,c,_ = ... But this will still break if your string or regex did not give at least three items.