This tutorial explains how to get numbers from a string in Python. It also lists some example codes to further clarify the concept using different approaches.
Use List Comprehension to Extract Numbers From a String
Numbers from a string can be obtained by simple list comprehension.
split() method is used to convert string to a list of characters and
isdigit() method is used to check if a digit is found through the iteration.
A basis code example is given as:
temp_string = "Hi my age is 32 years and 250 days12" print(temp_string) numbers = [int(temp)for temp in temp_string.split() if temp.isdigit()] print(numbers)
Hi my age is 32 years and 250 days12 [32, 250]
However, this code does not identify numbers that come with alphabets.
RegEx Module to Extract Numbers From a String
re module of Python also provides functions that can search through the string and extract results. The
re module provides with
findall() method that returns a list of all the matches. An example code is given below:
import re temp_string = "Hi my age is 32 years and 250.5 days12" print(temp_string) print([float(s) for s in re.findall(r'-?\d+\.?\d*', temp_string)])
Hi my age is 32 years and 250.5 days12 [32.0, 250.5, 12.0]
RegEx solution works for negative and positive both numbers and overcomes the problem encountered in the List Comprehension approach.