Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to extract numbers from a string in Python?
Python provides several methods to extract numbers from strings. Whether you need integers, floating-point numbers, or both, these techniques will help you parse numeric data from text efficiently.
Using Regular Expressions (re.findall)
The most powerful approach uses regular expressions to match different number patterns ?
import re
# Extract integers and floats
text = "The price is $29.99 and quantity is 5"
numbers = re.findall(r'\d+\.\d+|\d+', text)
print("String format:", numbers)
# Convert to appropriate numeric types
numeric_values = []
for num in numbers:
if '.' in num:
numeric_values.append(float(num))
else:
numeric_values.append(int(num))
print("Numeric format:", numeric_values)
String format: ['29.99', '5'] Numeric format: [29.99, 5]
Using isdigit() Method
For simple integer extraction, split the string and check each word ?
text = "There are 10 apples and 25 oranges"
numbers = []
for word in text.split():
if word.isdigit():
numbers.append(int(word))
print("Extracted numbers:", numbers)
Extracted numbers: [10, 25]
Character-by-Character Extraction
This method handles multi-digit numbers that aren't separated by spaces ?
text = "Room123has456windows"
numbers = []
current_number = ""
for char in text:
if char.isdigit():
current_number += char
elif current_number:
numbers.append(int(current_number))
current_number = ""
# Don't forget the last number
if current_number:
numbers.append(int(current_number))
print("Extracted numbers:", numbers)
Extracted numbers: [123, 456]
Using List Comprehension with re.findall
A concise one-liner approach for integer extraction ?
import re
text = "I bought 3 books for $45 each"
numbers = [int(num) for num in re.findall(r'\d+', text)]
print("Extracted numbers:", numbers)
Extracted numbers: [3, 45]
Extracting Negative Numbers
To include negative numbers, modify the regex pattern ?
import re
text = "Temperature dropped to -15 degrees and rose to 23"
numbers = re.findall(r'-?\d+(?:\.\d+)?', text)
numbers = [float(num) if '.' in num else int(num) for num in numbers]
print("Extracted numbers:", numbers)
Extracted numbers: [-15, 23]
Method Comparison
| Method | Handles Floats? | Handles Negatives? | Best For |
|---|---|---|---|
re.findall() |
Yes | Yes (with pattern) | Complex patterns |
isdigit() |
No | No | Simple integers |
| Character iteration | No | No | Connected numbers |
isnumeric() |
No | No | Unicode digits |
Conclusion
Use re.findall() for flexible number extraction including floats and negatives. For simple integer extraction from space-separated text, isdigit() with split() is sufficient and more readable.
