You are currently viewing Python Extract Numbers From String

How to extract numbers from a string in Python? To extract numbers(both integers and floating-point numbers) from a string in Python, you can use regular expressions from the re module or use a simple loop to iterate through the characters in the string and identify numeric characters.

Advertisements

You can extract numbers from a string in Python using many ways, for example, by using list comprehension & isdigit(), filter(), re.findall(), isnumeric(), for loop & isdigit(), str.translate() & str.maketrans(), and NumPy module. In this article, I will explain how to extract numbers from a string by using all these methods with examples.

Related: In Python, you can remove numbers from a string.

1. Quick Examples of Extracting Numbers from String

If you are in a hurry, below are some quick examples of extracting numbers from a string.


# Quick examples of extracting numbers from a string

import re
import numpy as np

# Initialize the string
string = "Hello, my age is 29 years and 140 days"

# Example 1: Using list comprehension and isdigit() method
numbers = [int(word) for word in string.split() if word.isdigit()]

# Example 2: Using filter() function
numbers = list(filter(lambda x: x.isdigit(), string.split()))
result = [int(s) for s in numbers]

# Example 3: Using re.findall() function
numbers = re.findall(r'\d+', string)
result = list(map(int, numbers))

# Example 4: Using isnumeric() method
result = []
x = string.split()
for i in x:
    if i.isnumeric():
        result.append(int(i))

# Example 5: Using a loop and isdigit() method
result = []
for char in string:
    if char.isdigit():
        result.append(int(char))

# Example 6: Using str.translate() with str.maketrans() functions
translation_table = str.maketrans('', '', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')
numeric_string = string.translate(translation_table)
words = numeric_string.split()
numbers = [int(i) for i in words]

# Example 7: Using numpy module
numbers = np.array(string.split())
result = numbers[np.char.isnumeric(numbers)].astype(int)

2. Extract Numbers from String Using List Comprehension and isdigit()

You can extract numbers from a string using list comprehension and the isdigit() method. For instance, you can start with an input string string that contains a mix of letters, numbers, and punctuation. Then you can use the split() method to split the input string into a list of words based on whitespace.

You then use a list comprehension to iterate through each word in the list and check if it consists entirely of digits using the isdigit() method. If a word consists only of digits, it is converted to an integer using int(word), and the resulting integers are collected in the numbers list.

Related: You can split the string based by delimiter or multiple delimiters in Python


# Initialize the string
string = "Hello, my age is 29 years and 140 days"
print("Original string:",string)

# Using list comprehension and isdigit() method
numbers = [int(word) for word in string.split() if word.isdigit()]
print("After extracting numbers from a string:", numbers)

Yields below output.

python extract numbers string

When you run this code, it will extract the numbers 29 and 140 from the input string and print them as a list.

3. Extract numbers from a string Using filter() Function

To extract numbers from a string use the filter() function and a lambda function. For instance, you can start with a string that contains text numbers. You can use the split() method to split the string into a list of words.

You can use the filter() function with a lambda function to filter out elements from the list that consist of digits only (x.isdigit()). The result of the filter() function is a filter object, so you can convert it to a list using list(). Finally, you use a list comprehension to convert the filtered elements (which are strings) into integers, resulting in the result list.


# Initialize the string
string = "Hello, my age is 29 years and 140 days"
print("Original string:",string)

# Using filter() function
# Extract numbers from string
numbers = list(filter(lambda x: x.isdigit(), string.split()))
result = [int(s) for s in numbers]
print("After extracting numbers from a string:", result)

Yields the same output as above.

4. Extract numbers from a string Using re.findall() Method

To extract numbers from a string use the re.findall() function from the re module. For instance, You can start with an string that contains text with numbers.

You can use the re.findall() function with the regular expression r'\d+' to find all sequences of one or more digits in the string. This regex pattern \d+ matches one or more digits. The result re.findall() is a list of strings containing the extracted numbers. Then, you can use map(int, numbers) it to convert each of the extracted strings into integers. Finally, you convert the result into a list, resulting in the result list.


import re

# Initialize the string
string = "Hello, my age is 29 years and 140 days"
print("Original string:",string)

# Using re.findall() function
# Extract numbers from string
numbers = re.findall(r'\d+', string)
result = list(map(int, numbers))
print("After extracting numbers from a string:", result)

Yields the same output as above.

5. Using isnumeric() Method

You can use isnumeric() method to extract numbers from a string. First, you can start with a string that contains text with numbers.

In the below example, you can apply the split() method over the given string to split the string into a list of words. You iterate through each word in the list using a for loop. For each word, you can use the isnumeric() method to check if it consists entirely of numeric characters. If a word is numeric, you convert a string to an integer using int() and append it to the result list.


# Initialize the string
string = "Hello, my age is 29 years and 140 days"
print("Original string:",string)

# Using isnumeric() method
# Extract numbers from string
result = []
x = string.split()
for i in x:
    if i.isnumeric():
        result.append(int(i))
print("After extracting numbers from a string:", result)

Yields the same output as above.

6. Using a For Loop and isdigit() Method

Similarly, you can use a for loop and the isdigit() method to extract numbers from a string. For instance, you can start with a string that contains text numbers. Then you can initialize an empty list called result to store the extracted numbers.

You can iterate over the string using a for loop. For each character, you can use the isdigit() method to check if it is a digit. If a character is a digit, then you can convert it to an integer using int() and append it to the result list.


# Initialize the string
string = "Hello, my age is 29 years and 140 days"
print("Original string:",string)

# Using a loop and isdigit() method
# Extract numbers from string
result = []
for char in string:
    if char.isdigit():
        result.append(int(char))
print("After extracting numbers from a string:", result)

# Output:
# Original string: Hello, my age is 29 years and 140 days
# After extracting numbers from a string: [2, 9, 1, 4, 0]

7. Using str.translate() with str.maketrans() Functions

To extract numbers from a string use the str.translate() method with str.maketrans() to remove non-numeric characters.

In the below example, you can start with an string that contains text with numbers and various other characters. Then you can create a translation_table using str.maketrans() where you specify that you want to remove all characters that are not digits. You can use str.translate() it with the translation_table to remove all non-numeric characters from the string, resulting in numeric_string. You can split numeric_string it into words using the split() method. After you can use a list comprehension to convert each word (which should contain only numeric characters) into an integer, resulting in the numbers list.


# Initialize the string
string = "Hello, my age is 29 years and 140 days"
print("Original string:",string)

# Using str.translate() with str.maketrans() functions
# Extract numbers from string
translation_table = str.maketrans('', '', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')
numeric_string = string.translate(translation_table)
words = numeric_string.split()
numbers = [int(i) for i in words]
print("After extracting numbers from a string:", numbers)

# Output:
# Original string: Hello, my age is 29 years and 140 days
# After extracting numbers from a string: [29, 140]

8. Extract Numbers from String Using NumPy Module

You can also use the NumPy module to extract numbers from a string. For example, you can start with an string that contains text with numbers. Then, you can use string.split() it to split a given string into an array of words. Then you can create a NumPy array called numbers from the resulting array of words.

You can use np.char.isnumeric(numbers) to create a Boolean mask that checks if each element in the numbers array is numeric. You can use this Boolean mask to index the numbers array, which filters out the non-numeric elements. Finally, you can use astype(int) to convert the filtered numeric elements to integers, resulting in the result array.


import numpy as np

# Initialize the string
string = "Hello, my age is 29 years and 140 days"
print("Original string:",string)

# Using numpy module
numbers = np.array(string.split())
result = numbers[np.char.isnumeric(numbers)].astype(int)
print("After extracting numbers from a string:", result)

# Output:
# Original string: Hello, my age is 29 years and 140 days
# After extracting numbers from a string: [ 29 140]

Conclusion

In this article, I have explained how to extract numbers from a string in Python by using the list comprehension & isdigit(), filter(), re.findall(), isnumeric(), for loop & isdigit(), str.translate() & str.maketrans(), and NumPy module with examples.

Happy Learning !!