Extract numbers from list of strings in Python


While using python for data manipulation, we may come across lists whose elements are a mix of letters and numbers with a fixed pattern. In this article we will see how to separate the numbers form letters which can be used for future calculations.

With split

The split functions splits a string by help of a character that is treated as a separator. In the program below the list elements have hyphen as their separator between letters and text. We will use that along with a for loop to capture each

Example

 Live Demo

listA = ['Mon-2', 'Wed-8', 'Thu-2', 'Fri-7']

# Given list
print("Given list : " + str(listA))

# Extracting numbers
num_list = [int(i.split('-')[1]) for i in listA]

# print result
print("List only with numbers : ",num_list)

Output

Running the above code gives us the following result −

Given list : ['Mon-2', 'Wed-8', 'Thu-2', 'Fri-7']
List only with numbers : [2, 8, 2, 7]

With map and isnumeric

In this approach we go through each element and check for the numeric part present in each element. The map function is used to apply the same function repeatedly on each of the element.

Example

listA = ['Mon-2', 'Wed-8', 'Thu-2', 'Fri-7']

# Given list
print("Given list : " + str(listA))

# Extracting numbers
num_list = list(map(lambda sub:int(''.join(
[i for i in sub if i.isnumeric()])), listA))

# print result
print("List only with numbers : ",num_list)

Output

Running the above code gives us the following result −

Given list : ['Mon-2', 'Wed-8', 'Thu-2', 'Fri-7']
List only with numbers : [2, 8, 2, 7]

Updated on: 05-May-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements