Open In App

Python | Extract Numbers from String

Last Updated : 16 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Many times, while working with strings we come across this issue in which we need to get all the numeric occurrences. This type of problem generally occurs in competitive programming and also in web development. Let’s discuss certain ways in which this problem can be solved in Python

Example

Use a loop to iterate over each character in the string and check if it is a digit using the isdigit() method. If it is a digit, append it to a list.

test_string = "There are 2 apples for 4 persons"

numbers = []
for char in test_string:
    if char.isdigit():
        numbers.append(int(char))

print("The numbers list is:", numbers)

Output
The numbers list is: [2, 4]

Extract numbers from string using List Comprehension

This problem can be solved by using the split function to convert string to list and then the list comprehension which can help us iterate through the list and isdigit function helps to get the digit out of a string. 

test_string = "There are 2 apples for 4 persons"

# printing original string 
print("The original string : " + test_string)

# using List comprehension + isdigit() +split()
# getting numbers from string 
res = [int(i) for i in test_string.split() if i.isdigit()]

# print result
print("The numbers list is :" + str(res))

Output
The original string : There are 2 apples for 4 persons
The numbers list is :[2, 4]

Extract Interger from string using isnumeric() Method

In Python, we have isnumeric function which can tell the user whether a particular element is a number or not so by this method we can also extract the number from a string.

test_string = "There are 2 apples for 4 persons"

# printing original string
print("The original string : " + test_string)


# getting numbers from string
res = []
x=test_string.split()
for i in x:
    if i.isnumeric():
        res.append(int(i))

# print result
print("The numbers list is : " + str(res))

Output
The original string : There are 2 apples for 4 persons
The numbers list is : [2, 4]

Extract Digit from string using RegEx

This particular problem can also be solved using Python regex, we can use the findall function to check for the numeric occurrences using a matching regex string. 

import re

# initializing string 
test_string = "There are 2 apples for 4 persons"

# printing original string 
print("The original string : " + test_string)

# getting numbers from string 
temp = re.findall(r'\d+', test_string)
res = list(map(int, temp))

# print result
print("The numbers list is : " + str(res))

Output
The original string : There are 2 apples for 4 persons
The numbers list is : [2, 4]

Extract Digit from String using Filter() Function

First, we define the input string then print the original string and split the input string into a list of words using the split() method. Use the filter() function to filter out non-numeric elements from the list by applying the lambda function x.isdigit() to each elementConvert the remaining elements in the filtered list to integers using a list comprehension. Print the resulting list of integers

test_string = "There are 2 apples for 4 persons"
print("The original string : " + test_string)

# use the split() method to split
# use the filter() function to filter out non-numeric elements from the list
res = list(filter(lambda x: x.isdigit(), test_string.split()))

# use a list comprehension to convert the remaining elements to integers
res = [int(s) for s in res]

# print the resulting list of integers
print("The numbers list is : " + str(res))

Output
The original string : There are 2 apples for 4 persons
The numbers list is : [2, 4]

Extract Numbers from string using str.translate() with str.maketrans() 

Define the input string then Initialize a translation table to remove non-numeric characters using str.maketrans(). Use str.translate() with the translation table to remove non-numeric characters from the string and store the result in a new string called numeric_string. Use str.split() to split the numeric_string into a list of words and store the result in a new list called words. Initialize an empty list called numbers to store the resulting integers and then iterate over each word in the list of words. Check if the word is a numeric string using str.isdigit().If the word is a numeric string, convert it to an integer using int() and append it to the list of numbers.

# Define the input string
test_string = "There are 2 apples for 4 persons"
# Print the original string
print("The original string : " + test_string)

# Initialize a translation table to remove non-numeric characters
translation_table = str.maketrans(
    '', '', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')

# Use str.translate() with the translation table to remove non-numeric characters
numeric_string = test_string.translate(translation_table)

# Use str.split() to split the string into a list of word
words = numeric_string.split()
numbers = [int(i) for i in words]

print("The numbers list is : " + str(numbers))

Output
The original string : There are 2 apples for 4 persons
The numbers list is : [2, 4]


Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg