Kevin Guo Kevin Guo - 1 year ago 113
Python Question

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
, second one
, third one
. And then calculate
, something like that. Could anyone tell me how to do it.

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download