Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Sort given list of strings by part the numeric part of string
When it is required to sort a given list of strings based on the numeric part of the string, we can use regular expressions with the sort() method's key parameter to extract and compare the numeric values.
Example
Below is a demonstration of sorting strings by their numeric parts ?
import re
def extract_numeric_part(string):
return list(map(int, re.findall(r'\d+', string)))[0]
strings = ["pyt23hon", "fu30n", "lea14rn", 'co00l', 'ob8uje3345t']
print("Original list:")
print(strings)
strings.sort(key=extract_numeric_part)
print("\nSorted list by numeric part:")
print(strings)
Original list: ['pyt23hon', 'fu30n', 'lea14rn', 'co00l', 'ob8uje3345t'] Sorted list by numeric part: ['co00l', 'ob8uje3345t', 'lea14rn', 'pyt23hon', 'fu30n']
How It Works
The
extract_numeric_part()function usesre.findall(r'\d+', string)to find all digit sequences in the stringIt converts the first found numeric sequence to an integer using
map(int, ...)[0]The
sort()method uses this function as thekeyparameter to determine sort orderStrings are sorted based on their numeric values: 0, 8, 14, 23, 30
Alternative Approach Using Lambda
You can also use a lambda function for more concise code ?
import re
strings = ["pyt23hon", "fu30n", "lea14rn", 'co00l', 'ob8uje3345t']
sorted_strings = sorted(strings, key=lambda x: int(re.findall(r'\d+', x)[0]))
print("Sorted strings:")
print(sorted_strings)
Sorted strings: ['co00l', 'ob8uje3345t', 'lea14rn', 'pyt23hon', 'fu30n']
Handling Multiple Numbers
If strings contain multiple numbers and you want to sort by the first number ?
import re
strings = ["abc12def34", "xyz5ghi78", "pqr1stu90"]
# Sort by first number found
sorted_strings = sorted(strings, key=lambda x: int(re.findall(r'\d+', x)[0]))
print("Sorted by first number:")
print(sorted_strings)
Sorted by first number: ['pqr1stu90', 'xyz5ghi78', 'abc12def34']
Conclusion
Use re.findall(r'\d+', string) to extract numeric parts from strings and sort them using the key parameter. This approach works efficiently for sorting mixed alphanumeric strings based on their numeric content.
