5 Ways to Extract Numbers from a String in Python
Many times we, face difficulties while working with string or string manipulations. So in this tutorial, we will how to extract numbers from a string in Python not only that we will 10 ways to extract numbers from a string using Python.
Letβs experiment with each method and see how to extract number from string in Python.
Method 1: Using Regular Expressions (re module)
Regular expressions or re is one of the most powerful packages of python its deals with all kinds of task-related strings and text.
import re
text = βHello, my age is 25 and my GPA is 3.75β
numbers = re.findall(rβ\d+\.\d+|\d+β, text)
print(numbers)
Method 2: Using isdigit() method
Python isdigit() is a built-in string method that is used to check if a given string is a digit or not.
text = βHello, my age is 25 and my GPA is 3.75β
numbers = [float(word) for word in text.split() if word.replace(β.β, ββ, 1).isdigit()]
print(numbers)
Method 3: Using a loop to check and extract numbers:
In this method, we will pure Python loop and condition statement to extract numbers.
text = βHello, my age is 25 and my GPA is 3.75β
numbers = []
current_number = ββ
for char in text:
if char.isdigit() or char == β.β:
current_number += char
elif current_number:
numbers.append(float(current_number))
current_number = ββ
if current_number:
numbers.append(float(current_number))
print(numbers)
Method 4: Using a generator expression and itertools:
Python itertools is also a built-in package with many different tools.
import itertools
text = βHello, my age is 25 and my GPA is 3.75β
numbers = [float(ββ.join(group)) for is_number, group in itertools.groupby(text, key=str.isdigit) if is_number]
print(numbers)
Method 5: Using a third-party library, NumPy:
Here we will use the numpy package that is used to deal with Python arrays.
import numpy as np
text = βHello, my age is 25 and my GPA is 3.75β
numbers = [float(num) for num in np.fromstring(text, dtype=float, sep=β β)]
print(numbers)
python extract number from string
extract number from string python
how to extract numbers from a string in Python
