Kevin Guo Kevin Guo - 9 days ago 6
Python Question

How to use python to extract a number by locating a specific word

I use python for programing, and i wonder how to extract a number by locating a specific word. For example, StoneA weights 10kg moves with speed 20m/s, StoneB weights 30kg moves with speed 40m/s. I know i can use re.findall to extract numbers. But if i just want to extract numbers relate with speed (which is 40 and 20). Is there a way to do it by locating the word "speed" or "m/s"

Answer

You can use re.findall:

>>> s = 'StoneA weights 10kg moves with speed 20m/s, StoneB weights 30kg moves with speed 40m/s'
>>> re.findall(r'(\d+)m/s', s)
['20', '40']

Regular expression (\d+)m/s captures one or more digits immediately followed by m/s.

Comments