Open In App

Python – Extract numbers from list of strings

Last Updated : 30 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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 list s. It returns a list of matched numbers as strings.
  • map(int, ...) function converts each found number from string to integer and the extend() method adds them to the list n. 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 of string.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 using extend().


Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg