Extract numbers from a string in python

How to extract numbers from a string in python ?

This tutorial guides you on how to extract numbers from a string in python programming language. Let’s say you have a string which contain numbers in it and you wanted to extract the numbers from the whole string, then you are at the right place. Let’s see how to extract numbers from string using various approaches.

Extract numbers from a string in python

Extract numbers from a string in python

 

For example, the given string is as follows:

str = "hello 404 your age is 65"

And, let’s say you wanted to extract the numbers 404 and 65 from the string.

Method 1: Extract numbers using regex

Let’s see how to extract numbers from string using regex.

import re
n = [int(n) for n in re.findall(r'-?\d+\.?\d*', text) ]
print (n)

Output

[404, 65]

Method 2: Using split() and isdigit()

In the previous example, you need an additional module/library called “re” for regex to perform this extraction. But in this case you don’t need any additional library, therefore it is better than regex method.

Note, there are limitations with this method. You can use this only if you wanted to extract positive numbers. Also this method does not recognize floats, integers in hexadecimal format apart from negative numbers. So go with this method only if you are ok with these limitations.

n = [int(n) for n in text.split() if n.isdigit()]
print(n)

Output

[404, 65]

Method 3: Using split() and append()

In this method, we are using split() function to split the given string and then extract the integer numbers using int() and append the number to the list as shown below.

n = []
for i in text.split():
    try:
        n.append(int(i))
    except ValueError:
        pass
print(n)

Output

[404, 65]

Method 4: Using Numbers from String Library

To use this method, first you need to install package/ library called nums_from_string with pip as shown below.

> pip install nums_from_string

Collecting nums_from_string
  Downloading nums_from_string-0.1.2-py3-none-any.whl (5.0 kB)
Installing collected packages: nums-from-string
Successfully installed nums-from-string-0.1.2
WARNING: You are using pip version 20.1.1; however, version 21.1 is available.
You should consider upgrading via the 'c:\users990\appdata\local\programs\python\python38-32\python.exe -m pip install --upgrade pip' command.

After that, you need to import the library. The following program will let you to extract the numbers in a quick way.

import nums_from_string
print(nums_from_string.get_nums(text))

Output

[404, 65]

That’s it. We have learnt numerous ways to extract the numbers from given string using python programming.

I hope you had find this tutorial helpful 🙂

You’ll also like:

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments