Sort given list of strings by part the numeric part of string - Python
Last Updated :
10 Apr, 2025
We are given a list of strings containing both letters and numbers, and the goal is to sort them based on the numeric part within each string. To do this, we extract the digits, convert them to integers and use them as sorting keys. For example, in ["Gfg34", "is67", "be3st"], the numbers 34, 67, and 3 are extracted and used for sorting. Let's explore different ways to implement this in Python.
Using re.search()
re.search() from the re module searches for the first occurrence of a pattern in a string. To extract digits, a pattern like \d+ is used, which matches one or more consecutive digits. It helps directly find and retrieve numeric substrings embedded within text.
Python
import re
a = ["Gfg34", "is67", "be3st", "f23or", "ge9eks"]
res = sorted(a, key=lambda x: int(re.search(r'\d+', x).group()))
print(res)
Output['be3st', 'ge9eks', 'f23or', 'Gfg34', 'is67']
Explanation: re.search(r'\d+', x) finds the first sequence of digits in each string and .group() extracts it as a string. This is then converted to an integer and used as the sorting key in sorted(), allowing the list to be ordered by the numeric parts of the strings.
Using filter(str.isdigit)
filter() iterate over each character in a string, keeping only the ones where str.isdigit() returns True. The result is a sequence of digit characters, which can be joined to form a complete number string. It's a clean, built-in alternative to manual loops for digit extraction.
Python
a = ["Gfg34", "is67", "be3st", "f23or", "ge9eks"]
res = sorted(a, key=lambda x: int(''.join(filter(str.isdigit, x))))
print(res)
Output['be3st', 'ge9eks', 'f23or', 'Gfg34', 'is67']
Explanation: filter(str.isdigit, x) picks out all digits from each string and ''.join() combines them into a number string. This is converted to an integer and used as the sorting key, so the list is sorted based on the numbers inside the strings.
Using tuple pairing
Tuple pairing is a technique where each string is paired with its numeric part (extracted using logic like regex or filter(str.isdigit)). These (number, string) tuples are then sorted by the numeric key. Since Python sorts tuples by the first element, this ensures strings are sorted based on the numbers within them.
Python
def fun(s):
num = ''
for ch in s:
if ch.isdigit():
num += ch
return int(num)
a = ["Gfg34", "is67", "be3st", "f23or", "ge9eks"]
res = sorted(a, key=fun)
print(res)
Output['be3st', 'ge9eks', 'f23or', 'Gfg34', 'is67']
Explanation: fun() function goes through each character in a string s, collects all digits, and forms a number. It returns this number as an integer. The sorted() function uses this number as the sorting key, so the strings in list a are sorted based on their numeric parts.
Similar Reads
Python | Sort given list of strings by part of string We are given with a list of strings, the task is to sort the list by part of the string which is separated by some character. In this scenario, we are considering the string to be separated by space, which means it has to be sorted by second part of each string. Using sort() with lambda functionThis
3 min read
Python program to list Sort by Number value in String Given a List of strings, the task is to write a Python program to sort list by the number present in the Strings. If no number is present, they will be taken to the front of the list. Input : test_list = ["gfg is 4", "all no 1", "geeks over 7 seas", "and 100 planets"] Output : ['all no 1', 'gfg is 4
6 min read
Sort Numeric Strings in a List - Python We are given a list of numeric strings and our task is to sort the list based on their numeric values rather than their lexicographical order. For example, if we have: a = ["10", "2", "30", "4"] then the expected output should be: ["2", "4", "10", "30"] because numerically, 2 < 4 < 10 < 30.
2 min read
Python program to Sort a List of Strings by the Number of Unique Characters Given a list of strings. The task is to sort the list of strings by the number of unique characters. Examples: Input : test_list = ['gfg', 'best', 'for', 'geeks'], Output : ['gfg', 'for', 'best', 'geeks'] Explanation : 2, 3, 4, 4 are unique elements in lists. Input : test_list = ['gfg', 'for', 'geek
6 min read
Python - Sort list of numbers by sum of their digits Sorting a list of numbers by the sum of their digits involves ordering the numbers based on the sum of each individual digit within the number. This approach helps prioritize numbers with smaller or larger digit sums, depending on the use case.Using sorted() with a Lambda Functionsorted() function w
2 min read