Python – Extract numbers from list of strings
Last Updated :
30 Jan, 2025
Improve
We are given a list of string we need to extract numbers from the list of string. For example we are given a list of strings s = [‘apple 123’, ‘banana 456’, ‘cherry 789’] we need to extract numbers from the string in list so that output becomes [123, 456, 789].
Using Regular Expressions
This method uses re.findall() to capture all digit sequences in each string.
import re
s = ['apple 123', 'banana 456', 'cherry 789']
n = []
for string in s:
# Convert each found number to an integer and extend the result into the list n
n.extend(map(int, re.findall(r'\d+', string)))
print(n)
Output
[123, 456, 789]
Explanation:
re.findall(r'\d+', s)
function is used to find all sequences of digits (numbers) in each string from the lists
. It returns a list of matched numbers as strings.map(int, ...)
function converts each found number from string to integer and theextend()
method adds them to the listn
. The result is a list of all extracted integers from the strings.
Using List Comprehension with isdigit()
This method checks for numbers by iterating through each string and extracting numbers manually.
s = ['apple 123', 'banana 456', 'cherry 789']
n = []
for string in s:
# Convert the filtered digit words into integers and extend them into the list n
n.extend([int(word) for word in string.split() if word.isdigit()])
print(n)
Output
[123, 456, 789]
Explanation:
- Code incorrectly uses
s.split()
instead ofstring.
split
()
to split each string into words. - It extracts and converts digit words into integers, adding them to the list
n.
Using filter()
and isdigit()
This method uses filter() to extract numbers from each string by checking if the string represents a digit.
s = ['apple 123', 'banana 456', 'cherry 789']
n = []
for string in s:
# Convert and add the numbers to the list n
n.extend(map(int, filter(str.isdigit, string.split())))
print(n)
Output
[123, 456, 789]
Explanation:
- Code splits each string in the list into words and filters out those that are digits using
isdigit
()
. - Valid digit words are converted to integers and added to the
n
list usingextend()
.