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 from letters which can be used for future calculations.

Using split() Method

The split() function 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 numbers. We will use that along with list comprehension to extract each number ?

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

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

# Extracting numbers using split
num_list = [int(item.split('-')[1]) for item in days_with_numbers]

# print result
print("List only with numbers : ", num_list)
Given list : ['Mon-2', 'Wed-8', 'Thu-2', 'Fri-7']
List only with numbers : [2, 8, 2, 7]

Using 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 elements ?

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

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

# Extracting numbers using isnumeric
num_list = list(map(lambda item: int(''.join(
    [char for char in item if char.isnumeric()])), days_with_numbers))

# print result
print("List only with numbers : ", num_list)
Given list : ['Mon-2', 'Wed-8', 'Thu-2', 'Fri-7']
List only with numbers : [2, 8, 2, 7]

Using Regular Expressions

For more complex patterns, regular expressions provide a powerful solution to extract all numbers from mixed strings ?

import re

mixed_strings = ['abc123def', 'hello456world789', 'test42']

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

# Extracting all numbers using regex
num_list = [int(''.join(re.findall(r'\d+', item))) for item in mixed_strings]

# print result
print("List only with numbers : ", num_list)
Given list : ['abc123def', 'hello456world789', 'test42']
List only with numbers : [123, 456789, 42]

Comparison

Method Best For Complexity
split() Fixed separator patterns Simple
isnumeric() Any numeric characters Medium
Regular expressions Complex patterns Advanced

Conclusion

Use split() for simple separator-based extraction, isnumeric() for mixed character strings, and regular expressions for complex pattern matching. Choose the method that best fits your data structure and requirements.

Updated on: 2026-03-15T17:48:14+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements