简体   繁体   中英

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?

There's an easier way, with a simple loop check.

string = "I have 56 apples, Tom has 34 apples, Mary has 222 apples"
x = [int(num) for num in string.split() if num.isdigit()]

>>> x
[56, 34, 222]

This will split the string and check if it's a number, and return it to a list. If you desire these numbers to be in string for (I can't see why, if it's a number, let it be a number) then remove the int() casting.

The issue with your question, is that if you want to assign these parsed numbers to variables, you'll have to do it manually, which is bad. If you end up having a dynamic number of numbers returned, this will be incredibly tedious and potentially unreliable. You may want to reconsider the logic here.

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.

This solution may not help the particular problem with re.findall, but this solution will allow you to do the calculation you desire. Use a dictionary:

>>>applesDict = {"My apples": 56, "Tom apples": 34, "Mary apples":222}

now you can store and solve for any calculation.

>>>c = applesDict["My apples"]
>>>d = applesDict["Tom apples"]

print c + d
>>> 90

This code may not be as efficient but easy to understand and gets what you need done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM