How to Extract Numbers from a String in Python?

Spread the love

Problem –

You want to extract numbers from a string in python.

Solution –

Using List Comprehension –

To extract numbers from a string in python, we can use list comprehension and string.isdigit() method. The isdigit() method returns True if all characters of a string are digits otherwise it returns False.

In [1]: string = "The price of apples is 120 and Mango is 80"

In [2]: numbers = [int(word) for word in string.split() if word.isdigit()]

In [3]: numbers
Out[3]: [120, 80]

Using re module –

In [5]: import re

In [6]: [int(str_num) for str_num in re.findall(r'-?\d+\.?\d*', string)]
Out[6]: [120, 80]

Rating: 1 out of 5.

Leave a Reply