Summary: To extract numbers from a given string in Python you can use one of the following methods:
- Use the
append()functions on a list.
- Use a List Comprehension with
- Use the
Extracting digits or numbers from a given string might come up in your coding journey quite often. Whether you are automating a script in python and you want to extract certain numerical figures from a CSV file or you are a data scientist and you need to separate complex digits and figures from given patterns or you are a python enthusiast who wants to learn more about strings and numerical data types then you will certainly find this article helpful. Having said that, let us dive into our mission-critical question:
Problem: Given a string; how to extract numbers from the string in Python?
Example: Consider that you have been given a string and you want to extract all the numbers from the string as given in the following example:
Given is the following string:
Extract 100, 1000 and 10000 from this string
This is your desired output:
[100, 1000, 10000]
Let us discuss the methods that we can use to extract the numbers from the given string:
Method 1: Using Regex Module
The most efficient approach to solve our problem is to leverage the power of the
regex module. You can easily use Regular Expressions (
RegEx) to check or verify if a given string contains a specified pattern (be it a digit or a special character or any other pattern).
Thus to solve our problem we must import the regex module which is already included in Pythons standard library and then with the help of the
findall() function we can extract the numbers from the given string.
findall() is an easy-to-use regex function that returns a list containing all matches. To learn more about
findall() check out our blog tutorial here.
Let us have a look at the following code to understand how we can use the
regex module to solve our problem:
import re sentence = 'Extract 100 , 100.45 and 10000 from this string' s = [float(s) for s in re.findall(r'-?\d+\.?\d*', sentence)] print(s)
[100.0, 100.45, 10000.0]
Method 2: Split and Append The Numbers To A List using split() and append() Functions
Another workaround for our problem is to split the given string using the
split() function and then extract the numbers using the built-in
float() method then append the extracted numbers to the list.
split()is a built-in python method which is used to split a string into a list.
append()is a built-in method in python that adds an item to the end of a list.
Now that we have the necessary tools to solve our problem based on the above concept, let us dive into the code to see how it works:
sentence = 'Extract 100 , 100.45 and 10000 from this string' s =  for t in sentence.split(): try: s.append(float(t)) except ValueError: pass print(s)
[100.0, 100.45, 10000.0]
Method 3: Using isdigit() Function In A List Comprehension
Another approach to solving our problem is to use the
isdigit() inbuilt function to extract the digits from the string and then store them in a list using a list comprehension. The
isdigit() function is used to check if a given string contains digits. Thus if it finds a character which is a digit then it returns True, otherwise, it returns False.
Let us have a look at the code given below to see how the above concept works:
sentence = 'Extract 100 , 100.45 and 10000 from this string' s = [int(s) for s in str.split(sentence) if s.isdigit()] print(s)
☢ Alert! This technique is best suited to extract only positive integers. It won’t work for negative integers, floats, or hexadecimal numbers.
Method 4: Using Numbers from String Library
This is a quick hack if you want to avoid spending time behind typing explicit code to extract numbers from a string. You can import a library known as
nums_from_string and then use it to extract numbers from a given string. It contains several regex rules with comprehensive coverage and can be a very useful tool for NLP researchers.
Since the Numbers from String library is not a part of the standard Python library, you have to install it before being able to use it. Use the following command to install this useful library:
pip install nums_from_string
The following program demonstrates the usage of
import nums_from_string sentence = 'Extract 100 , 100.45 and 10000 from this string' print(nums_from_string.get_nums(sentence))
[100.0, 100.45, 10000.0]
Thus from the above discussions, we found that there are numerous ways of extracting a number from a given string in python. My personal favorite though would certainly be the regex module. You might argue that using other methods like the
split() functions provide a simpler and more readable code and are faster. However, as mentioned earlier it does not return numbers that are negative (in reference to method 2) and also do not work for floats that have no space between them and other characters like ‘25.50k’ (in reference to method 2). Furthermore, speed is kind of an irrelevant metric when it comes to log parsing. Now you see why regex is my personal favorite in this list of solutions.
In case you are not very supportive of the re library, especially because you find it difficult to get a strong grip on this concept (just like me in the beginning), here’s THE TUTORIAL for you to become a regex master. 😉
I hope you found this article useful and added some value to your coding journey. Please stay tuned for more interesting stuff in the future.
Where to Go From Here?
Enough theory, let’s get some practice!
To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
Practice projects is how you sharpen your saw in coding!
Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?
Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.