Open In App
Related Articles

Python – Sort given list of strings by part the numeric part of string

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

In Python, you can neatly arrange a list of words with numbers by using special methods for sorting. Just look at the numbers in each word, and use sorting techniques that pay attention to these numbers. This helps to put the words in order based on their numerical parts in a way that fits the list perfectly.

Given a list of strings. The task is to sort the list by the numeric part of the string in Python.

Examples:

Input : test_list = ["Gfg34", "is67", "be3st", "f23or", "ge9eks"] 
Output : ['be3st', 'ge9eks', 'f23or', 'Gfg34', 'is67'] methods
Explanation : 3 < 9 < 23 < 34 < 67, numbers extracted from strings.

Ways in Python to Sort List of Strings With Numbers

There are various methods to Python sort list of strings with numbers, here we are explaining some generally used methods for Python sort list of strings with numbers those are follows.

Create a List

In this example code initializes a list called `test_list` with strings containing alphanumeric characters. It then prints the original list as a string.

Python3

# initializing list
test_list = ["Gfg34", "is67", "be3st", "f23or", "ge9eks"]
 
# printing original list
print("The original list is : " + str(test_list))

                    

Output :

The original list is : ['Gfg34', 'is67', 'be3st', 'f23or', 'ge9eks']

Time Complexity : O(n)
Space Complexity : O(1)

Python Sort List of Strings With Numbers Using sort() + re.findall()

In this, we perform the task of sorting using sort(), the explicit function is used to extract numbers using findall(). sort() function for sorting and employs a custom function, implemented with findall(), to extract numerical values from the elements being sorted.

Example : In this example the below Python code takes a list of strings (test_list) containing alphanumeric elements and sorts them based on their numerical substrings. It uses a helper function (num_sort) along with the sort() function and regular expressions.

Python3

# Python3 code to demonstrate working of
# Sort Strings on numerical substrings
# Using sort() + findall()
import re
 
# helper function to perform sort
def num_sort(test_string):
    return list(map(int, re.findall(r'\d+', test_string)))[0]
 
# calling function
test_list.sort(key=num_sort)
 
# printing result
print("Strings after numerical Sort  : " + str(test_list))

                    

Output :

Strings after numerical Sort  : ['be3st', 'f23or', 'Gfg34', 'ge9eks', 'is67']

Time Complexity: O(nlogn)
Auxiliary Space: O(n)

Python Sort List of Strings With Numbers Using sort() + lambda + findall()

This method uses Python’s `sort()` with a custom lambda function and `findall()` from the `re` module to sort a list of strings containing both letters and numbers based on numerical values embedded in the strings. The lambda function extracts numerical substrings using `findall()` and converts them to integers for sorting.

Example : In this example Python code sorts a list of strings based on their numerical substrings. It uses regular expressions to find all integers in each string, converts them to integers, and then sorts the strings based on the first integer found.

Python3

# Python3 code to demonstrate working of
# Sort Strings on numerical substrings
# Using sort() + lambda + findall()
import re
 
# findall() getting all integers.
# conversion to integers using map()
test_list.sort(key=lambda test_string : list(
    map(int, re.findall(r'\d+', test_string)))[0])
 
# printing result
print("Strings after numerical Sort  : " + str(test_list))

                    

Output :

Strings after numerical Sort  : ['be3st', 'f23or', 'Gfg34', 'ge9eks', 'is67']

Time Complexity: O(nlogn)
Auxiliary Space: O(n)

Python Sort List of Strings With Numbers using extend(),sort() and index() Methods

In this `extend()` method appends elements of another iterable to a list. The `sort()` method arranges the list elements in ascending order. The `index()` method finds the index of a specified element in the list.

Example : In this example the code takes a list of strings (test_list), extracts numerical substrings from each string, sorts the list based on these numerical substrings, and then prints the original and sorted lists.

Python3

# Python3 code to demonstrate working of
# Sort Strings on numerical substrings
x=[]
dig="0123456789"
for i in test_list:
    p=""
    for j in i:
        if j in dig:
            p+=j
    x.append(int(p))
y=[]
y.extend(x)
x.sort()
res=[]
for i in x:
    res.append(test_list[y.index(i)])
     
# printing result
print("Strings after numerical Sort : " + str(res))

                    

Output :

Strings after numerical Sort : ['be3st', 'f23or', 'Gfg34', 'ge9eks', 'is67']

Time Complexity : O(NlogN)
Auxiliary Space : O(N)

Python Sort List of Strings using the sorted() , lambda and re.split()

In this method employs `sorted()`, lambda, and `re.split()` in Python to sort a list of strings containing both text and numbers. The lambda function ensures proper sorting by considering both alphanumeric components, while `re.split()` facilitates the tokenization of strings for comprehensive sorting.

Example : In this example code sorts a list of strings (test_list) based on a custom sorting key that considers both alphabetic and numeric parts of each string. The output shows the original and sorted lists

Python3

import re
 
# Sorting using lambda function and re.split()
sorted_list = sorted(test_list, key=lambda s: [int(text) if text.isdigit() else text.lower() for text in re.split('([0-9]+)', s)])
 
# Printing result
print("List after sorting: " + str(sorted_list))

                    

Output :

List after sorting: ['be3st', 'f23or', 'Gfg34', 'ge9eks', 'is67']

Time Complexity : O(n * m * log(n))
Auxiliary Space : O(m * n)

Sort given list of strings by Numeric part of string using List Comprehension

In this Python method utilizes list comprehension to sort a list of strings containing both letters and numbers. It extracts numeric portions from each string using a custom function, then sorts the list based on both letters and the extracted numeric values, ensuring a natural sorting order.

Example : In this example the code sorts a list of strings (test_list) based on their numerical substrings using regular expressions. It extracts and sorts the numerical substrings and then rearranges the original list accordingly.

Python3

import re
 
# Extract numerical substrings and sort them
substrings = sorted(int(x) for string in test_list for x in re.findall(r'\d+', string))
 
# Sort the original list based on numerical substrings
res = sorted(test_list, key=lambda s: int(re.findall(r'\d+', s)[0]))
 
print("Strings after numerical Sort:", res)

                    

Output :

Strings after numerical Sort: ['be3st', 'f23or', 'Gfg34', 'ge9eks', 'is67']

Time Complexity : O(NlogN)
Auxiliary Space : O(N)

Python Sort List of Strings With Numbers Using isdigit() Method

In this “isdigit()” method in Python is used to check if all characters in a string are digits. In the context of sorting a list of strings with numbers, this method is applied to each string element to identify numeric portions. By utilizing the “isdigit()” result as a key for sorting, the list is organized numerically rather than lexicographically.

Example : In this example code sorts a list of strings (test_list) based on the numeric values extracted from each string using the isdigit() method. The output is the original list and the sorted list based on numeric values.

Python3

#sorting the list using the isdigit() method
sorted_list = sorted(test_list, key=lambda x: int(''.join(filter(str.isdigit, x))))
 
#printing the result. MB
print("List after numeric sort is:",sorted_list)

                    

Output :

List after numeric sort is: ['be3st', 'Gfg34', 'f23or', 'ge9eks', 'is67']

Time Complexity : O(NlogN)
Auxiliary Space : O(N)

Python Sort List of Strings With Numbers using the natsorted Function

In this “natsorted” function in Python is a natural sorting method for lists of strings containing both text and numbers. Unlike standard sorting, it orders numeric components numerically rather than lexicographically, ensuring a more intuitive sequence. This function is particularly useful when dealing with filenames.

Example : In this example code uses the natsort library to perform natural sorting on a list of alphanumeric strings (test_list). It prints the original list and the list after natural sorting

Python3

from natsort import natsorted
 
# sorting using natsorted()
sorted_list = natsorted(test_list)
 
# printing result
print("List after sorting : " + str(sorted_list))

                    

Output :

List after sorting : ['Gfg34', 'be3st', 'f23or', 'ge9eks', 'is67']

Time Complexity : O(N log N)
Space Complexity : O(N)

Using the sorted() with custom function using str.translate()

In this method employs Python’s `sorted()` function with a custom sorting function that utilizes `str.translate()` for sorting a list of strings containing numbers. This function helps maintain numerical order by translating each character in the strings, distinguishing between digits and non-digits.

Example : In this example Python code demonstrates custom sorting of a list containing alphanumeric strings. The custom_sort_key function uses the str.translate() method to remove letters from each string, and then converts the result to an integer.

Python3

import string
 
# Custom sorting function using str.translate()
def custom_sort_key(s):
    translation = str.maketrans("", "", string.ascii_letters)
    return int(s.translate(translation))
 
# Sorting using the custom sorting function
sorted_list = sorted(test_list, key=custom_sort_key)
 
# Printing result
print("List after sorting: " + str(sorted_list))

                    

Output :

List after sorting: ['be3st', 'f23or', 'Gfg34', 'ge9eks', 'is67']

Time Complexity : O(n * m * log(n))
Auxiliary Space : O(m * n)



Last Updated : 19 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads