02-26-2023, 02:45 PM
How To Extract Numbers From A String In Python?
5/5 – (4 votes)
The easiest way to extract numbers from a Python string is to use the expression . For example, yields the list of strings that you can then convert to numbers using or .
There are some tricks and alternatives, so keep reading to learn about them.![[Image: 1f447.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f447.png)
In particular, you’ll learn about the following methods to extract numbers from a given string in Python:
Problem Formulation
![[Image: image-346.png]](https://blog.finxter.com/wp-content/uploads/2023/02/image-346.png)
Extracting digits or numbers from a given string might come up in your coding journey quite often. For instance, you may want to extract certain numerical figures from a CSV file, or you need to separate complex digits and figures from given patterns.
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:
This is your desired output:
Let us discuss the methods that we can use to extract the numbers from the given string:
Method 1: Using Regex Module
![[Image: image-347.png]](https://blog.finxter.com/wp-content/uploads/2023/02/image-347.png)
The most efficient approach to solving our problem is to leverage the power of the module. You can easily use Regular Expressions () 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 module, which is already included in Python’s standard library, and then with the help of the function we can extract the numbers from the given string.
◈ Learn More: is an easy-to-use regex function that returns a list containing all matches. To learn more about check out our blog tutorial here.
Let us have a look at the following code to understand how we can use the module to solve our problem:
Output
This is a Python code that uses the module, which provides support for regular expressions in Python, to extract numerical values from a string.
Code explanation:![[Image: 1f447.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f447.png)
The line uses the function from the module to search the string for numerical values.
Specifically, it looks for strings of characters that match the regular expression pattern. This pattern matches an optional minus sign, followed by one or more digits, followed by an optional decimal point, followed by zero or more digits.
The function returns a list of all the matching strings.
The list comprehension takes the list of matching strings returned by and converts each string to a floating-point number using the function. This resulting list of floating-point numbers is then assigned to the variable .
Recommended: Python List Comprehension
Method 2: Split and Append The Numbers To A List using split() and append()
Another workaround for our problem is to split the given string using the function and then extract the numbers using the built-in method then append the extracted numbers to the list.
Note:
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:
Output
Method 3: Using isdigit() Function In A List Comprehension
Another approach to solving our problem is to use the inbuilt function to extract the digits from the string and then store them in a list using a list comprehension.
The function is used to check if a given string contains digits. Thus if it finds a character that is a digit, then it returns . Otherwise, it returns .
Let us have a look at the code given below to see how the above concept works:
Output
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 typing explicit code to extract numbers from a string.
You can import a library known as 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 library is not a part of the standard Python library, you have to install it before use. Use the following command to install this useful library:
The following program demonstrates the usage of :
Output
Conclusion
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 and functions provide simpler and more readable code and faster. However, as mentioned earlier, it does not return numbers that are negative (in reference to Method 2) and also does not work for floats that have no space between them and other characters like (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.
If you are not very supportive of the 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. ![[Image: 1f92f.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f92f.png)
![[Image: 1f92f.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f92f.png)
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.
5/5 – (4 votes)
The easiest way to extract numbers from a Python string
Code:
sCode:
re.findall('\d+', s)Code:
re.findall('\d+', 'hi 100 alice 18 old 42')Code:
['100', '18', '42']Code:
int()Code:
float()There are some tricks and alternatives, so keep reading to learn about them.
![[Image: 1f447.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f447.png)
In particular, you’ll learn about the following methods to extract numbers from a given string in Python:
- Use the module.Code:
regex
- Use andCode:
split()functions on a list.Code:append()
- Use a List Comprehension with andCode:
isdigit()functions.Code:split()
- Use the module.Code:
num_from_string
Problem Formulation
![[Image: image-346.png]](https://blog.finxter.com/wp-content/uploads/2023/02/image-346.png)
Extracting digits or numbers from a given string might come up in your coding journey quite often. For instance, you may want to extract certain numerical figures from a CSV file, or you need to separate complex digits and figures from given patterns.
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:
Code:
s = 'Extract 100, 1000 and 10000 from this string'This is your desired output:
Code:
[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
![[Image: image-347.png]](https://blog.finxter.com/wp-content/uploads/2023/02/image-347.png)
The most efficient approach to solving our problem is to leverage the power of the
Code:
reCode:
RegExThus to solve our problem, we must import the
Code:
regexCode:
findall()◈ Learn More:
Code:
re.findall()Code:
re.findall()Let us have a look at the following code to understand how we can use the
Code:
regexCode:
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)Output
Code:
[100.0, 100.45, 10000.0]This is a Python code that uses the
Code:
reCode explanation:
![[Image: 1f447.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f447.png)
The line
Code:
s = [float(s) for s in re.findall(r'-?\d+\.?\d*', sentence)]Code:
re.findall()Code:
reCode:
sentenceSpecifically, it looks for strings of characters that match the regular expression pattern
Code:
r'-?\d+.?\d*'The
Code:
re.findall()The list comprehension
Code:
[float(s) for s in re.findall(r'-?\d+\.?\d*', sentence)]Code:
findallCode:
float()Code:
s
Recommended: Python List ComprehensionMethod 2: Split and Append The Numbers To A List using split() and append()
Another workaround for our problem is to split the given string using the
Code:
split()Code:
float()Note:
- is a built-in python method which is used to split a string into a list.Code:
split()
- is a built-in method in python that adds an item to the end of a list.Code:
append()
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:
Code:
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)Output
Code:
[100.0, 100.45, 10000.0]Another approach to solving our problem is to use the
Code:
isdigit()The
Code:
isdigit()Code:
TrueCode:
FalseLet us have a look at the code given below to see how the above concept works:
Code:
sentence = 'Extract 100 , 100.45 and 10000 from this string'
s = [int(s) for s in str.split(sentence) if s.isdigit()]
print(s)Output
Code:
[100, 10000]
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 typing explicit code to extract numbers from a string.
You can import a library known as
Code:
nums_from_stringSince the
Code:
nums_from_stringCode:
pip install nums_from_stringThe following program demonstrates the usage of
Code:
nums_from_stringCode:
import nums_from_string sentence = 'Extract 100 , 100.45 and 10000 from this string'
print(nums_from_string.get_nums(sentence))Output
Code:
[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
Code:
reYou might argue that using other methods like the
Code:
isdigit()Code:
split()Code:
'25.50k'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.
If you are not very supportive of the
Code:
re![[Image: 1f92f.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f92f.png)
![[Image: 1f92f.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f92f.png)
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.

