When it is required to sort given list of strings by numeric part of string, the regular expression and the ‘findall’ method is used.
Example
Below is a demonstration of the same −
import re def my_num_sort(my_str): return list(map(int, re.findall(r'\d+', my_str)))[0] my_list = ["pyth42on", '14is', '32fun', '89to', 'lea78rn'] print("The list is :") print(my_list) my_list.sort(key=my_num_sort) print("The result is :") print(my_list)
Output
The list is : ['pyth42on', '14is', '32fun', '89to', 'lea78rn'] The result is : ['14is', '32fun', 'pyth42on', 'lea78rn', '89to']
Explanation
The required packages are imported into the environment.
A method is defined that takes a string as a parameter.
It uses the ‘findall’ method to find a match to the specific pattern.
This is converted to a string using the ‘map’ method, and then to a ‘list’.
This is returned as output of the method.
Outside the method, a list of strings is defined and displayed on the console.
The list is sorted based on the key as the previously defined method.
This list is displayed as the output on the console.