Python Practice › RegEx Programs › Program 5
Extract all numbers
Write a Python program to extract integers and decimals from text.
Output
[-3.5, 1013.0, 82.4]
Approach
-?\d+(?:\.\d+)?.
Solution
import re text = "Temp -3.5C, pressure 1013 hPa, humidity 82.4%"print([float(x) for x in re.findall(r"-?\d+(?:\.\d+)?", text)])Output
[-3.5, 1013.0, 82.4]
Line by line
Line 4
(?:...) groups the decimal part without creating a capture, so findall returns whole matches.
Learn the concept
New to this topic? Read the lesson, then come back.